You are on page 1of 75

Software Development

 Problem Definition
 Analysis & Design
 Coding
 Testing and debugging
 Implementation
 Modification and maintenance
Software Development
Cont…
 Problem Definition
o What is to be done?
o How much is to be done?
 Analysis
o Interviewing the persons involved
o Question/answer
o Documents reading
o Observation / monitoring etc.
Software Development
Cont…
o Design
• ER diagram
• Data flow diagram
• Condition table
• System flow chart
 Design
o Form Design – GUI – for input
o Report Design – for output
o Database Design – to store data
Software Development
Cont…
 Coding
o As per the requirement

 Testing and Debugging


o To identify the position of errors.
o To remove the errors.
Software Development
Cont…
 Implementation
 Modification and Maintenance
Design a program to add
two numbers.
/* program to add two numbers */
#include <stdio.h> //include header file
int main( )
{
int a, b, sum;
printf(“Enter two values: ”); //display statement

scanf(“%d%d”, &a, &b); //input statement


sum = a + b;
printf(“The sum is: %d“, sum); //output statement
return 0;
}
Some commands:

F1 details of error & help


Ctrl+F1 Detailed help of a construct
Alt + F9 Compilation only
Ctrl + F9 Run
Alt + F5 user / result screen
F2 Save
F9 Make “exe” file on hard disk
F3 to open a new or existing file
 The text inside /* and */ is called
comment or documentation.
 The statement starting with # (hash
sign) is called pre-processor
statement.
 stdio.h is a header file.
o Prototype or declaration only of the
library functions
o Predefined constants
 Header file does not contain the code of
library functions. It only contains the
header or prototype.
 A program may contain many functions,
but it essentially contains a main
function.
 The return type of main function is kept
int type. A program should return value.
o 0 (zero) in case of normal termination.Non-
zero in case of abnormal termination, i.e.
termination due to some error.
Steps of Program Execution

 Pre-processing
Alt + F9
 Compilation

 Linking
 Loading Ctrl+ F9
 Execution
 Pre-processing:
o Pre-processing statements are processed first
o All the statements starting with #(hash) sign are
preprocessing statements
o eg. #include and #define
 Compilation: The syntactical validity of the
complete program is checked
o If there is no error the compiler generates the object
code (.obj)
 Linking: Symbolic Links are resolved in this phase
o A function call is called symbolic link
o A function can be user defined or ready made function
in the library
o The linker substitutes the name of the function with the
address of the first instruction of the function
 Execution: The Instruction of object code are
executed one by one. It has four major steps
o Instruction Fetch
o Instruction Decode
o Operand Fetch
o Operand Execute
Types of Errors
 Syntax error: When there is the
violation of the grammatical ( Syntax)
rule. Detected at the compilation time.
o Semicolon not placed
o Standard Construct not in proper format
o Identifier not declared
 Linker Error: When definition or code of
a program is not found.
o Path of header not properly defined
o Library file not found
o The function name is misspelled
Types of Errors Cont...
 Runtime error: It is generated during execution phase. Due
to mathematical or some operation generated at the run
time.
o Division by zero
o Square root of negative number
o File not found
o Trying to write a read only file

 Logical Error: Produced due to wrong logic of program.


Tough to identify and even tougher to remove.
o Variables not initialized
o Boundary case errors in loops
o Misunderstanding of priority and associativity of
operators
Types of Statements in C
Prog.
 Preprocessing Statements: Also called compiler directives. The
purpose depends on the type of commands.
o # include statement inserts a specified file in our program
o They don't exist after compilation
 Declarative Statements: Used to declare user identifier i.e. to
declare data types for exampe: int a, b;
o These statements do not exist in the object code.
o Only used to produce symbol table
Types of Statements in C
Prog. Cont...
 Executable Statements: The statements for which the
executable or binary code is generated. For
o Input/Output Statements like printf(), scanf()
o Assignment Statements. The syntax is
lvalue=rvalue
o Conditional Statements like if(a>b) max =a; else
max=b;
o Looping Statements. Also called Iterative
statements or repetitive statements.
• For
• while
• do while
o Function Call like y=sin(x);
Types of Statements in C Prog.
Cont...
 Special Statements: There are four
special statements
o break
o continue
o return
o exit
Keywords & Identifiers
 The meaning of some words is reserved in a
language which the programmer can use in
predefined manner. Theses are called keywords or
reserve words. For example: do, while, for, if,
break, etc…
 The programmer uses his words for preparing a
program. These words are used to store final or
intermediate results. These words are called
identifiers. The programmer has to define the type
of identifier he is using. For example: a, b, sum,
etc.. These are two categories of identifiers.
o Variable eg. int a;
o Constant – literal eg #define PI 3.14
Rules and Conventions of Making
Identifier

 The first character must be an alphabet.


Remaining characters may be alpha-
numerals (alphabets + numeric digits):
 No special character other than underscore
“__” is permitted.
 Space is not permitted.
 The maximum length is compiler defined.
 Reserve words can not be taken as
identifiers.
Data Types in C
 Standard data type
o Simple data type
• char
• Int
• float
o Structured/composite data type
• array
• struct
• union
o Pointer
Data Types in C
 User Defined data type
o enum
o typedef
 The char holds a character or a small integer. It has
two modifies:
o Unsigned
o Signed
 The int holds a whole number. It has two types of
modifiers:
o Type 1:
• Signed
• unsigned
o Type 2:
• Short
• Int
• long
Data Types in C
 The float can hold a number with
fraction parts. It has three modifiers:
o float
o double
o long double
Name Description Size Range
Char Character 1byte signed: -128 to 127
unsigned: 0 to 255

short int (short) Short Integer. 2bytes signed: -32768 to 32767


unsigned: 0 to 65535
Integral data
Int Integer type 2bytes/ signed: -32768 to 32767
unsigned:- 0 to 65535
4 bytes

long int (long) Long integer. 4bytes signed: -2147483648 to


2147483647
unsigned: 0 to
4294967295
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)

double Double precision floating 8bytes 1.7e +/- 308 (15 digits)
point number.

long double Long double precision 10bytes ??


floating point number.
Character and integer data types use the same
internal format. The only difference is the number of
bytes allocated.

#include <stdio.h>
int main( )
{
char ch = 97; // char ch = ‘a’;
int x = ‘A’;// int x = 65;
printf(“\nCharacter: %c, Equivalent integer:
%d”, ch, ch);
printf(“\nEquivalent Character: %c, integer:
%d”, x, x);
return 0;
}
Operators available in C
Associativity Operators Description
left-to-right .  () [] Highest priority operators

right-to-left ++, --, !, ~, +, -, *, &, sizeof( ) all unary operators


left-to-right * / % arithmetic operators
left-to-right + - arithmetic operators
Decreasing Priority

left-to-right << >> bit shift operators


left-to-right <, <=, >, >=, relational operator
left-to-right = =, != relational operator
left-to-right & ampersand bit wise operator
left-to-right ^ caret
left-to-right | pipeline
left-to-right && Logical operator
left-to-right ||
right-to-left ? : ternary/conditional operator
right-to-left =, +=, -=, *=, /=, %=, &=, ^=, |=, assignment operator
<<=, >>=
left-to-right , sequencing operator
There are three types of operators available in C:
 unary – that requires only one operand.
o For example: &a, ++a, *a
 binary - that requires two operands.
o For example: a + b, a * b
 ternary - that requires three operands.
o For example: (a>b) ? a : b [ ?:]
 Priority and associativity: The higher priority operator is operated
first. If the priority or precedence is same then associativity is
applied.
o a+b*c
o (a + b) * c
o x=a+b
o *a++
o a-b+c
o a *= b += c
o a / b*c
o a+b+c
o x = a++ ?
Token
 In a C source program, the basic
element recognized by the compiler
is the “token.”
 Token is source-program text that the
compiler does not break down into
component elements.
o keyword, identifier, constant, string-
literal, operator, punctuator
Operators in Details

 The “/” (the division) operator:

Data type of op1 Data type of op2 Data type of result

int int int (fractional part


truncated)
float int float
int float float
float float float
Operators in Details
 Modulus operator
 Increment / Decrement Operators ( ++, - -)
o Pre-increment ++a
o Post – increment a++
o Pre-decrement - -a
o Post-decrement a - -
 The expressions in which a single variable
is incremented and decremented and used
more than once, must be strictly avoided.
These are confusing. Moreover, the
compiler may behave in unpredictable
manner.
Operators in Details
 Assignment Operators: An
assignment statement is used to
assign the value of an expression to
a single variable. The syntax is:
lvalue = rvalue
It can only be a a variable, a constant,
single variable an expression, function
call
Printf()

 Writes to the standard output (stdout) a


sequence of data formatted as the format
argument specifies. After the format
parameter, the function expects at least as
many additional arguments as specified in
format.
 The format tags follow this prototype: %
[flags][width][.precision][length]specifier
specifier Output Example

c Character a
d or i Signed decimal integer 392
e Scientific notation (mantissa/exponent) using e character 3.9265e+2

E Scientific notation (mantissa/exponent) using E character 3.9265E+2

f Decimal floating point 392.65


g Use the shorter of %e or %f 392.65
G Use the shorter of %E or %f 392.65
o Signed octal 610
s String of characters sample
u Unsigned decimal integer 7235
x Unsigned hexadecimal integer 7fa
X Unsigned hexadecimal integer (capital letters) 7FA
p Pointer address B800:0000

n Nothing printed. The argument must be a pointer to a signed int, where the number of
characters written so far is stored.

% A % followed by another % character will write % to stdout.


The tag can also contain flags, width, .precision and modifiers sub-specifiers,
which are optional and follow these specifications:
flags description

- Left-justify within the given field width; Right justification is the default (see width
sub-specifier).

+ Forces to preceed the result with a plus or minus sign (+ or -) even for positive
numbers. By default, only negative numbers are preceded with a - sign.

(space) If no sign is going to be written, a blank space is inserted before the value.

# Used with o, x or X specifies the value is preceded with 0, 0x or 0X respectively


for values different than zero.
Used with e, E and f, it forces the written output to contain a decimal point
even if no digits would follow. By default, if no digits follow, no decimal point is
written.
Used with g or G the result is the same as with e or E but trailing zeros are
not removed.

0 Left-pads the number with zeroes (0) instead of spaces, where padding is
specified (see width sub-specifier).
width description

(number) Minimum number of characters to be printed. If the value to be printed is shorter than this number,
the result is padded with blank spaces. The value is not truncated even if the result is larger.

* The width is not specified in the format string, but as an additional integer value argument
preceding the argument that has to be formatted.

.precision description

.number For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be
written. If the value to be written is shorter than this number, the result is padded with leading
zeros. The value is not truncated even if the result is longer. A precision of 0 means that no
character is written for the value 0.
For e, E and f specifiers: this is the number of digits to be printed after the decimal point.
For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters are
printed until the ending null character is encountered.
For c type: it has no effect.
When no precision is specified, the default is 1. If the period is specified without an explicit
value for precision, 0 is assumed.

.* The precision is not specified in the format string, but as an additional integer value argument
preceding the argument thas has to be formatted.
length description

h The argument is interpreted as a short int or unsigned short int


(only applies to integer specifiers: i, d, o, u, x and X).

l The argument is interpreted as a long int or unsigned long int for


integer specifiers (i, d, o, u, x and X), and as a wide character or
wide character string for specifiers c and s.

L The argument is interpreted as a long double (only applies to


floating point specifiers: e, E, f, g and G).

Return Value: On success, the total number of characters written is returned. On


failure, a negative number is returned.
Example
/* fprintf example */
#include <stdio.h>
int main( )
{ printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d %ld\n", 1977, 650000);
printf ("Preceding with blanks: %10d \n", 1977);
printf ("Preceding with zeros: %010d \n", 1977);
printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
printf ("Width trick: %*d \n", 5, 10);
printf ("%s \n", "A string"); return 0;
}

Characters: a A
Decimals: 1977 650000
Preceding with blanks: 1977
Preceding with zeros: 0000001977
Some different radixes: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick: 10
A string
scanf( ):
scanf( ) statement is used to read data from
standard input stream (stdin), the keyboard. The
syntax is:
scanf( format string with specifiers, variable
names)
The specifier list is same as that of printf( ).
Example:
char x;
int y;
float z;
scanf(“%c%d%f”, &x, &y, &z);
scanf( ) returns the number of values successfully
read.
Expression
There are two types of expressions:
 Arithmetic expression: Returns a value
 Relational / Logical / Conditional
Expression: Returns true or false
 if a relational expression is true, it returns
numeric value 1
 if a relational expression is false, it
returns numeric value 0
Logical Operator
There are three logical operators &&
(AND), | | (OR), ! (NOT). These are used
to combine the conditions.

Short circuit evaluation


The ‘if’ Statement

It is used to selectively execute a set


of statements. The set of statements
is executed, if the condition is true
s0; s0;
if (c) if (c)
s1; {
s2; s1;
s2;
}
s3;
if..else structure:

s0; //ex6.c
if (c) { #include
s1;
<stdio.h>
s2;
} int main(){
else { int a = 0, b =
s3; 5, c = 0; OUTPUT ?
s4; if (c=a)
}
printf(“\n
s5;
Hello”);
else
printf(“in
world”);
if (c = b)
Type Conversion
A variable/value of one type can be converted into
variable/value of another type. There are two cases:
 Implicit conversion: Values can be converted by assigning one
expression into the other. There are two types:
o widening conversion
o narrowing conversion
char short  int  longfloat  double long double
Assignment in forward direction is widening conversion; no data is lost in it.
Assignment in backward direction is called narrowing conversion; data loss is
possible in this case.
char a = 10;
int b, c;
float d = 2.6;
b = a; // widening conversion, no data loss
c = d; // narrowing conversion, data loss, c gets value only 2
Narrowing conversion must be type casted. c = (int)d;
 Explicit conversion (Type Casting): Type
casting is used to convert the data type of an
identifier to another data type temporarily.
#inlcude <stdio.h>
int main( ) {
int a=11, b=2;
float c;
c = (float)a / b;
printf(“\n%f”, c);
return 0;
}
The switch statement
The C allows multiple choice of a selection of
items at one level of a conditional where it is a
far neater way of writing multiple if statements:
switch (expression) {
case item1:
statement1;
break;
case item2:
statement2;
break; case itemn:
statementn;
break;
default:
statement;
break;
}
b=10, c =
20;

The sizeof( ) operator:


a = sizeof(b
+ c);
printf( “%d”,
a);
return 0;
It returns the size of its argument
} in
bytes.
The argument may be:
 An identifier
 A constant
 A standard data type
 User defines data type
#include <stdio.h>
#include <stdio.h>
int main( ) int main( )
{ int a, b, c;
{
double x;
int a, b, c;
a = sizeof(int);
b=10, c = 20;
b= sizeof( 4);
c= sizeof(x); a = sizeof(b + c);
printf( “%d%d%d%”, a,b,c); printf( “%d”, a);
return 0;
} return 0;
}
Low Level Operators and Bit
Fields
Many programs (e.g. systems type applications) must actually
operate at a low level where individual bytes must be
operated on.
Bitwise Operators
X=00000010
Table: Bitwise operators

& AND
| OR
^ XOR
~ One's Compliment

10
01
<< Left shift
>> Right Shift
Shifting is much faster than actual multiplication (*) or division (/) by 2. So if you
want fast multiplications or division by 2 use shifts.

#include <stdio.h>
int main() {
char x = 12, y=10, a, b, c, d;
clrscr();
a = x | y;
printf("\n%d", a);
b = x & y;
printf("\n%d", b);
c = x ^ y;
printf("\n%d", c);
d = ~x;
printf("\n%d", d);
return 0;
}
The for loop
For loop consist of two parts.
 Header
 body – C statements that are to be executed repeatedly.
The header contains three sections:
o Initialization
o Condition
o Statement
s0;
for ( s1; c; s2)
s3;
s4;
 
Break and continue
Statement:
Break is used at two places:
• inside switch..case statement
• inside the loop
As soon as break statement is encountered, the execution comes out of the
structure immediately. If break is inside the loop, the loop is terminated.
As soon as continue statement is encountered, the execution comes to the
condition checking immediately, that is, the statements below continue are
skipped.

s0;
s0;
for ( s1; c1;
for ( s1;
s2) {
c1; s2) {
s3;
s3;
if (c2)
if (c2)
continue;
break;
s4;
s4;
}
}
s5;
s5;
While Loop:
It is an entry control indefinite type loop.
s0;
while (c)
s1;
s2;

s0; s0; s0;


while (c)
while (c) while (c);
{
s1; s1;
s1;
s2; s2;
s2;
s3;
}
s3;
do .. while :
It is exit control and indefinite type loop.
s0;
do
s1;
while
Difference between while(c); and do-while :
 In while the conditions2;is checked at the beginning
and in do while the condition is checked at the last.
 It is possible that the stmt inside while may not be
executed even for a single time, if the condition is
false for the first time. In do-while the stmt inside the
loop are executed at least once.
Modular Programming
 A large program is divided into small modules. The basic
idea is – “to develop a small set of statements, is
comparatively simpler”. The C provides the facilities of
functions to support modular programming.
 Modularization is a design time activity. To take full
advantage of modularization, modules should be
independent of one another. One module should perform
one atomic task. One module should not be given too
many responsibilities.
Advantages of modular programming:
 Simplicity in development:
 Faster development:
 Reusability:
 Abstraction:
 Reduced code size:
 Simplicity in testing and modification
Design of Modular Programming to add two
numbers
//add.c /* function to add two
# include <stdio.h> integers
input : two integer x
/*prototype*/ and y
int add( int x, int y); output: sum of x and y
*/
void main( ) { int add(int x, int y)
int a,b,c; {
int z;
a=10;
b=20; z = x + y;
c= add(a, b); /* return z;
function call */ }
printf(“\n The sum is:
%d”, c);
}
 Prototype means the behavior of the function, i.e.
o the return type,
o the name and,
o the number and type of input parameter.
There is no need of identifiers in the prototype. So, the following
is also sufficient: int add(int, int);
The prototype is also called “declaration” or “header”.
 The body of a function that contains actual code for the function
is called “definition.”
 The definition of a function can also be given before main()
function. In this case there is no need of prototype.
 The function main() is the “calling function”, add() is “called
function”.
 In the calling function, there is function call statement. The list
inside parentheses is called “argument list.”
In the header of the called function, the list inside the
parentheses is called the “parameter list.”
 The type and number of arguments must exactly match with
those of parameter.
 The value of arguments is assigned to corresponding parameters.
c = add(a, b); /* call */

int add (int x, int y) /* header of definition */


Effectively, it is an assignment operation: x = a; y = b;
 The identifiers a, b, and c, are called local identifiers of function main(). The
identifiers x, y, and z are called local identifier of add() function.
A local identifier can be used within the function in which it is declared.
So a, b, and c are accessible within main() only. Similarly, x, y and z are
accessible within add() function only.
 A function can contain more than one return statement physically. But, logically
only one will be executed out of them. As soon as, a return in the called function
encounters, execution control is transferred to the calling function at the point
where a function call was made.
c = add(a, b);
Effectively, the returned value is assigned to the lvalue of the assignment
statement of the function call. So, the equivalent effect is: c = z
 The data type of a following three must exactly match:
o The data type of return expression in called function.
o The return type of the function.
o The data type of variable, in which the returned value is being stored.
 The returned value can be discarded, if not required.
 It the function does not return anything, its return type is
void. A void function may or may have not return statement.
If there is no return statement, it is implicitly inserted at the
end of function.
 Guideline: Normally, a function should not contain
input/output statement, because it looses the generality of
function. The input to the function should be supplied as
parameter. The result is normally returned from the function.
 But this scheme has a limitation, that we can return only
single value from the function multiple returned values can
be done with the help of :
o Structures
o call by reference parameter
/*factorial.c /* function to find factorial.
Modular program to find Input : a number n
factorial of a number */ Output : factorial of n */
#include <stdio.h> long factorial(int num)
#include <conio.h> {
/* prototype */ int i;
long factorial(int); long fact = 1L;

void main ( ){ /*loop to calculate factorial */


int n; for (i = 2; i <= num; ++i)
long fact; fact *= i;

printf( "\nEnter a number: "); return fact;


scanf("%d", &n); }
fact = factorial(n);
printf("\n The factorial is : %ld",
fact);
}
hcf.c : program to find hcf */
/*

#include <stdio.h>
/* prototypes */
int hcf(int x, int y );
main( ) {
int a, b, result;
printf( "\n enter two numbers: ");
scanf( "%d%d", &a, &b);
result = hcf(a, b);
printf( "\n The hcf is %d: ", result);
}
/* function to find hcf input : two numbers x and y output: hcf of x
and y*/
int hcf(int x, int y ){
int result, smaller;
smaller = ( x< y) ? x : y; /* get smaller number */
/* loop to generate numbers from smaller downto 1 */
for (result = smaller ; result >= 1; --result ) {
if ( ( x% result == 0) && ( y% result == 0) ) /* result
divides x & y bath */
return result; /* result is the hcf */
} /*for */
countDigit.c :
/* /* function to count digits of a
program to count digits of a number
number */ intput : a number x
output : count of digits of x*/
#include <stdio.h>
int countDigit(long x){
#include <conio.h> int count = 0;
int countDigit( long n ); /* repeat till x contains atleast 1
void main( ){ digit */
long n; while (x > 0){
int count; x = x/10;/* truncate last digit */
clrscr(); ++count;
printf("\n Enter number :"); }
scanf("%ld", &n); return count;
}
count = countDigit(n);
printf("\nThe number of digits
is: %d", count);
}
Scope & Lifetime:
 Scope/Visibility: It is the area of a program in which an identifier is
accessible / visible or usable.
 Lifetime: It is the time duration for which the space will remain allocated
for a variable.

Scope/visibility Life Time


Local auto The function in which it is declared The function in which it is declared

Global Complete program Complete program

Static The function in which it is declared Complete program

 static and a global variable is always initialized to zero automatically;


but a local variable hold garbage value initially.
 If a local variable in a function has the same name as that of global
variable, the global variable is hidden in that function. It means that
priority is always given to local declaration.
 A static variable maintains its value between function calls.
 The use of local and static variables must be preferred over global
variables. Use of global variables creates problems during testing and
debugging. Constants can be taken as global.
Variable Storage Classes

 Local/auto
 Register
 Static
 Extern / global
Automatic: auto
 storage is automatically allocated on
function/block entry and automatically freed
when the function/block is exited
 may not be used with global variables (which
have storage space that exists for the life of the
program)
 auto is the default for function/block variables
o auto int a is the same as int a
o because it is the default, it is almost never used
Register:
 register provides a hint to the compiler that you
think a variable will be frequently used
 compiler is free to ignore register hint
 if ignored, the variable is equivalent to an auto
variable with the exception that you may not take
the address of a register (since, if put in a register,
the variable will not have an address)
 rarely used, since any modern compiler will do a
better job of optimization than most programmers
Static Storage: static
 if used inside a block or function, the
compiler will create space for the variable
which lasts for the life of the program
int counter(void) {
static int cnt = 0;
return cnt++;
}
 causes the counter( ) function to return a
constantly increasing number
External References: extern
 If a variable is declared (with global scope) in one file but
referenced in another, the extern keyword is used to
inform the compiler of the variable's existence:
In a file declare.h:
int x; //definition //space is allocted
In a file use.c:
{
extern int x; //declaration : no new variable is being
declared
int a;
a = x * 2;
}
 Note that the extern keyword is for declarations, not
definitions
 An extern declaration does not create any storage; that
must be done with a global definition
Private Variables: static
Another use for the static keyword is to ensure that code outside this file cannot
modify variables that are globally declared inside this file
If declare.c had declared farvar as:
static int farvar;
then the
extern int farvar
statement in use.c would cause an error.
This use of static is commonly used in situations where a group of functions need
to share information but do not want to risk other functions changing their
internal variables.
static int do_ping = 1; /* start with `PING' */
void ping(void) {
if (do_ping = = 1) {
printf("PING ");
do_ping = 0;
}
}
void pong(void) {
if (do_ping = = 0) {
printf("PONG\n");
do_ping = 1;
}
}
Variable Initialization
 auto, register and static variables may be initialized at creation:
int
main(void)
{
int a = 0;
register int start = 1234;
static float pi = 3.141593;
}
 Any global and static variables which have not been explicitly
initialized by the programmer are set to zero
 If an auto or register variable has not been explicitly initialized, it
contains whatever was previously stored in the space that is
allocated to it
o this means that auto and register variables should always be
initialized before being used
o compiler may provide a switch to warn about uninitialized
variables
ARRAYS
Introduction: An array is a structured/composite data
type. We can store more than one element in an array
simultaneously. An array is also called subscript variable.
One Dimensional Array: Arrays are similar to matrices.
There can be single dimensional array or
multidimensional array.
Ex:
int a[5];
 
 
Data type maximum
Of element permitted size; 
 
array name
i.e. maximum 5 elements can be stored in this array.
 All element of the array are of same data type. In this sense, it is a
homogenous data structure.
 Maximum permitted size is 5. It means that we can store maximum
five integers in this array. These five elements are referred to as:

a[0], a[1], a[2], a[3], a[4]

indices / subscript
 In general an element can be referred to as: a[ i ], where i varies from
0 to 4 here, i is called index or subscript.
 The allocation information about an array is fixed at compile time. Its
entry is done in symbol table at compile time. It means that it is static
allocation.
 During execution the memory space is allocated for array. For all
element of array contiguous space is allocated. The array name is the
start address of this memory.
<100> <102> <104> <106> <108> <110>

a[0] a[1] a[2] a[3] a[4]


<100> <102> <104> <106> <108> <110>

a[0] a[1] a[2] a[3] a[4]


Total occupied size = MAX size x sizeof(data type)
= 5 * 2 = 10
So, for the declared array 10 contiguous bytes are allocated.
 Here the name of array ‘a’ means the start address <100>. It is a constant.
 An element a[ i ] of array ‘a’ is simple integer. It can participate anywhere in
any operations like one integer variable.
 To read the complete array in a single scanf( ) statement is not possible to
read all the element. We will have to use loop. The similar behavior is in
print operation.
 To take an array that has its maximum size variable is not possible.

int main( )
{
int n =5;
int a[n];
maximum size is variable
} (not possible, syntax error)
Normally declaration is done in this manner.
#define MAX 10
void main( )
{
int a[MAX];
}
 It is because #define is processed during preprocessing phase; so in
compilation phase the compiler gets 10 in place of MAX.
 The maximum size of array remains fixed, once declared; but the current
size of the array may vary. But, the current size can never be greater than
maximum size. The space is reserved according to maximum size. We can
use all or less locations. If the maximum size is 10 and current size is 6,
then the remaining 4 locations will remain reserved and empty. These
locations can not be used for any other purpose.
 An array can be initialized at the time of declaration. { Demo initArray.c }
int a[4] = {10, 20, 30, 40};
int b[4] = {10, 20};
int c[ ] = {10, 20, 30, 40};
int d[4] = {0};
Ex: Declare an array of integer; read its current size; prepare a loop to read; display the loop in another array.

#include <stdio.h>
#define MAX 50
int main( ) {
int a[max];
int i, n;
/* read current size of array
*/
printf( “Enter current
size:“ );
scanf( “%d”, &n);
/*loop to read array */
for (i = 0; i < n; ++i) {
printf( “\nEnter %dth
element: ”, i);
scanf(“%d”, &a[i]);}
/*loop to display array */
for (i = 0; i < n; ++i)
printf( “\nThe %dth
element is: %d”, i, a[i] );
There is no bound checking of array in C and C++ neither at compile time nor at
execution time. But, if the subscripts are beyond the valid limits, the results will be
garbage and the behavior of the program may be peculiar. Hence, it is the
responsibility of the programmer to keep the indices within the valid limit.
NOTES:
For calling a function in which an array is passed as parameter, only array name is
used.
The name reflects the start address, so only start address of the array is passed.
When array is passed the start address is passed, not the complete array. It
provides efficiency - it saves memory & time.
Since only the base address is passed, the original data locations are accessed by
the called function. So, any changes, made in the called function are reflected in
the calling function (pass-by-reference).
The contents of the array read in the called function read_1D() are available in the
calling main() function.
In called function header, when parameters are specified, there is no need of
specifying the maximum size of the array.
Ex-: Design a modular program to read and display a one dimensional array. The two functions to
be made are to read and display the array. The main() function calls these functions.

/*function to read an array input: the


array, its size*/
readDispArrayMod.c
//
void read_1D(int a[ ], int size);
#include <stdio.h>
{
#define MAX 20
int I;
/*prototypes */
/*loop to read array */
void read_1D(in a[ ],
for (i = 0; i < size; ++i )
int size);
{
void display_1D(int
printf( “\nEnter %dth element: ”, i);
a[ ], int size);
scanf(“%d”, &a[i]);
/* main function */
}
int main( )
}
{
/*function to display an array input:
int a[MAX], n;
the array, its size */
printf( “\nenter
void display_1D(int a[ ], int size);
current size:”);
{
scanf(“%d”, &n);
int I;
read_1D(a, n);
/*loop to display array */
display_1D(a, n);
for (i = 0; i < size; ++i )
return 0;
printf( “\nThe %dth element is: %d”, i,
}
Two Dimensional Array:
A two dimensional array is like a two dimensional matrix, that has
rows and columns.
An integer 2D array with 10 rows and 20 columns can be declared
as:
int a[10][20];

Maximum Maximum
numb of rows numb of columns

An array item can be referred to as:


a[ i ][ j ]

row number column number

The indices i and j, both are zero starting indices.


Initialization:
Initialization of array can be done as soon as it is declared;
int a[3][2] = { {10, 20},
{30, 40},
{50, 60}
};
int b[2][3] = { {10, 20, 30}, {40, 50, 60} };
Accessing of items:
int a[4][3] = { {10, 63, 59},
{51, 43, 72},
{63, 82, 95},
{22, 84, 18}
};

a[0][0] a[2][1]
70 63 59
51 43 72
63 82 95
22 84 18

You might also like