0% found this document useful (0 votes)
15 views26 pages

Unit 3

C

Uploaded by

Kiruthika Mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views26 pages

Unit 3

C

Uploaded by

Kiruthika Mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT-III

DECISION MAKING AND BRANCHING:


INTRODUCTION
 Program is a set of statements which are normally executed sequentially in the order in
which they appear.
 To change the order of execution of statements based on certain conditions or repeat a group
of statements until certain specified conditions are met, C language provides the following
statements
If statement
Switch statement
Conditional operator statement
Goto statement
These statements are popularly known as decision-making statements. Since these statements
‘control’ the flow of execution, they are also known as control statements.
DECISION MAKING WITH IF STATEMENT
 The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements.
 It is basically a two-way decision statement and is used in conjunction with an expression.
Syntax : if (test expression)
Explanation :
 It allows the computer to evaluate the expression first and then, depending on whether the
value of the expression (relation or condition) is ‘true’ (or non-zero) or ‘false’ (zero), it
transfers the control to a particular statement.
 The if statement may be implemented in different forms depending on the complexity of
conditions to be tested. The different forms are:
Simple if statement
If..else statement
Nested if..else statement
Else if ladder
SIMPLE IF
Syntax : if (test expression)
{
statement-block;
}
statement-x;
Explanation :
 The statement-block may be a single statement or a group of statements.
 If the test expression is true, the statement-block will be executed; otherwise the
statement-block will be skipped and the execution will jump to the statement-x.

test

expressio
n
statement-block

statement_x

next statement
Sample Program:
# include <stdio.h>
# include <conio.h>
main()
{
int a;
printf("\n Enter a number ");
scanf("%d",&a);
if (a%2==0)
printf("\n\n\t\t\t\t\tEven Number");
getch();
return 0;
}

IF..ELSE
The if..else statement is an extension of the simple if statement.
Syntax : if (test expression)
{
true-block statement(s)
}
else
{
false-block statement(s)
}
statement-x
 If the test expression is true, then the true-block statement(s), immediately following the if
statements are executed; otherwise, the false-block statement(s) are executed.
 In either case, either true-block or false-block will be executed, not both.
# include <stdio.h>
# include <conio.h>
void main()
{int a,b,c;
clrscr();
printf("Enter Two Different Integer Numbers");
scanf("%d%d",&a,&b);
if (a>b)
{
printf("\n\t\t\tThe Largest Number is:\t%d",a);
printf("\n\t\t\tThe Smallest Number is:\t%d",b
}
else
{
printf("\n\t\t\tThe Largest Number is:\t%d",b );
printf("\n\t\t\tThe Smallest Number is:\t%d",a);
}
getch();
}
NESTING OF IF..ELSE
When a series of decisions are involved, we may have to use more than one if..else statement in
nested form as shown below:
if (test-condition-1)
{
if (test-condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
Explanation:
 If the condition-1 is false, the statement-3 will be executed; otherwise it continues to
perform the second test.
 If condition-2 is true, the statement-1 will be evaluated; otherwise the statement-2 will be
evaluated and then the control is transferred to the statement-x.

Sample Program
Program to display the Largest Number
# include <conio.h>
# include <stdio.h>
main()
{
int a,b,c;
clrscr();
printf("Enter any 3 Number \n");
scanf("%d%d%d",&a,&b,&c);
if (a>b)
{
if (a>c)
{
printf("\n\t\tA is greater: %d",a);
}
else
{
printf("\n\t\tC is greater: %d",c);
}
}
else
{
if (b>c)
{
printf("\n\t\tB is greater: %d",b);
}
else
{
printf("\n\t\tC is greater: %d",c);
}
}
getch();
}

ELSE IF LADDER
 There is another way of putting ifs together when multipath decisions are involved.
 A multipath decision is a chain of ifs in which the statement associated with each else is an
if.
 It takes the following general form:
if (condition 1)
statement-1;
else if (condition 2)
statement-2;
else if (condition 3)
statement-3;
else if (condition n)
statement-n;
else
default statement;
statement-x;

 This construct is known as the else if ladder.


 The conditions are evaluated from the top (of the ladder), as soon as a true condition is
found, the statement associated with it is executed and the control is transferred to the
statement –x (skipping the rest of the ladder).
 When all the n conditions become false, then the final else containing the default statement
will be executed.
Sample Code:
Program to display Largest Number
# include <conio.h>
# include <stdio.h>
main()
{
int a,b,c;
clrscr();
printf("Enter any 3 Number \n");
scanf("%d%d%d",&a,&b,&c);
if ((a>b) && (a>c))
printf("\n\t\tA is greater: %d",a);
else if (b>c)
printf("\n\t\tB is greater: %d",b);
else
printf("\n\t\tC is greater: %d",c);
getch();
}

Rules for Indentation


 Indent statement that are dependent on the previous statement; provide at least three spaces
of indentation
 Align vertically else clause with their matching if clause.
 Use braces on separate lines to identify a block of statements.
 Indent the statement in the block by at least three spaces to the right of the braces.
 Align the opening and closing braces.
 Use appropriate comments.
 Indent the nested statements as per the above rules.
 Code only one clause or statement on each line.
SWITCH STATEMENT
The general from of the switch statement is as shown below:

switch (expression)
{
case value-1:
break;
case value-2:
block-2
break;
……
……
default:
default-block
break;
}
statement-x;
Explanation:
 The expression is an integer expression or characters. value-1, value-2……are constants or
constant expression (evaluated to an integral constant) and are known as case labels.
 Each of these values should be unique within a switch statement.
 block-1, block-2……are statement lists and may contain zero more statements.
 Case labels end with a colon (:).
 When the switch is executed, the value of the expression is successfully compared against
the values value-1, value-2,…..
 If a case is found whose value matches with the value of the expression, then the block of
statements that follows the case are executed.
 The break statement at the end of each block signal the end of a particular case and causes
an exit from the switch statement, transferring the control to the statement-x following the
switch.
 The default is an optional case.
 When present, it will be executed if the value of the expression does not match with any of
the case values.
 If not present, no action takes place if all matches fail and the control goes to the statement-
x.
Rules for Switch Statement
 The switch expression must be an integral type.
 Case labels must be constants or constant expression.
 Case labels must be unique. No two labels can have the same value.
 The break statement transfers the control out of the switch statement.
 The break statement is optional. That is, two or more case labels may belong to the same
statements.
 The default statement is optional. If present, it will be executed when the expression does
not find a matching case label.
 There can be at most one default label.
 The default may be placed anywhere but usually placed at the end.
 It is permitted to nest switch statements.
No. The cases in a switch must either have integer constants or constant expressions.
a. switch is useful when we wish to check the value of a variable against a particular set of
values.
b. Switch is useful when we wish to check whether a value falls in different ranges.
c. Compiler implements a jump table for cases used in a switch
d. It is NOT necessary to use a break in every switch statement.
Output: a , c & d
Sample Program
# include <stdio.h>
void main()
{
int i=4;
switch(i)
{
default: printf(“welcome to AVS college”);
case 1: printf(“ \nthank you”);
break;
case 2: printf(“welcome to c”);
break;
}
}
 Avoid compound negative statements. Use positive statements wherever possible.
 Keep logical expressions simple.
 Try to code the normal/anticipated condition first.
 Use the most probable condition first.
 Use proper indentations.
 Use default clause in switch statements.
 Group the case labels that have similar actions.

THE?:OPERATOR
 The C language has an unusual operator, useful for making two-way decisions.
 This operator is a combination of ? and :, and takes three operands.
 This operator is popularly known as the conditional operator.
Syntax :conditional expression ? expression1 :expression2
 The conditional expression is evaluated first.
 If the result is nonzero, expression1 is evaluated and is returned as the value of the
conditional expression. Otherwise, expression2 is evaluated and its value is returned.
Program to display the Largest Number
# include <conio.h>
main()
{
int a,b,c;
clrscr();
printf("Enter any 2 Number \n");
scanf("%d%d",&a,&b);
c=a>b?a:b;
printf("\n\t\tThe Largest Number is %d",c);
getch();
}
GOTO STATEMENT
Rules:
 C supports the goto statement to branch unconditionally from one point to another in the
program.
 The goto requires a label in order to identify the place where the branch is to make.
 A label is any valid variable name, and must be followed by a colon.
 The label is placed immediately before the statement where the control is to be transferred.
 The general forms of goto and label statements are shown below:
 The label: can be anywhere in the program either before or after the goto label; statement.
 During running of a program when a statement like
 goto begin;
is met, the flow of control will jump to the statement immediately following the label begin:.
 This happens unconditionally.
 A goto breaks the normal sequential execution of the program.
 If the label: is before the statement goto label; a loop will be formed and some statements
will be executed repeatedly. Such a jump is known as a backward jump.
 On the other hand, if the label: is placed after the goto label; some statements will be
skipped and the jump is known as a forward jump.
 A goto is often used at the end of a program to direct the control to go to the input statement,
to read further data. Consider the following example:
main( )

double x,y;

read :

scanf(“%f”, &x);

 This program is written to evaluate the square root of a series of numbers read from the
terminal.
 The program uses two goto statements, one at the end, after printing the results to transfer
the control back to the input statement and the other to skip any further computation when
the number is negative.
 Due to the unconditional goto statement at the end, the control is always transferred back to
the input statement. In fact, this program puts the computer in a permanent loop known as an
infinitive loop.
 The computer goes round and round until we take some special steps to terminate the loops
can be eliminated.
DECISION MAKING AND LOOPING
INTRODUCTION: TYPES OF LOOPS
 In looping, a sequence of statements is executed until some conditions for termination of the
loop are satisfied.
 A program loop therefore consists of two segments, one known as the body of the loop and
the other known as the control statement
 The control statement tests certain conditions and then directs the repeated execution of the
statements contained in the body of the loop
 Depending on the position of the control statement in the loop, a control structure may be
classified either as the entry-controlled loop or as the exit-controlled loop.
 In the entry-controlled loop, the control conditions are tested before the start of the loop
execution.
 If the conditions are not satisfied, then the body of the loop will not be executed.
 In the case of an exit-controlled loop, the test is performed at the end of the body of the
loop and therefore the body is executed unconditionally for the first time.
 The entry controlled loop and exit-controlled loop are also known as pre-test and post-test
loops respectively.

Body of
Test
The loop
Conditi
on

Test
Body of
Conditio
The loop
n

a) Entry controlled loop (b)Exit controlled loop


A looping process consists of four steps
 Setting and initialization of a condition variable ?
 Execution of the statements in the loop
 Test for a specified value of the condition variable for execution of the loop
 Incrementing or updating the condition variable
 The test may be either to determine whether the loop has been repeated the specified number
of times or to determine whether a particular condition has been met.
The C language provides for three constructs for performing loop operations. They are
The while statement
The do statement
The for statement
Based on the nature of control variable and the kind of value assigned to it for testing the
control expression, the loops may be classified into two general categories
Counter controlled loops
Sentinel controlled loops
 When we know in advance exactly how many times the loop will be executed, we use a
counter-controlled loop.
 A control variable known as counter is used.
 The counter must be initialized, tested and updated properly for the desired loop operations.
 The number of times we want to execute the loop may be a constant or a variable that is
assigned a value.
 A counter controlled loop is sometimes called definite repetition loop
 In a sentinel-controlled loop, a special value called a sentinel value is used to change the
loop control expression from true to false.
 The control variable is called sentinel variable
 A sentinel-controlled loop is often called indefinite repetition loop because the number of
repetitions is not known before the loop begins executing
# include <conio.h>
main() # include <conio.h>
{ main()
int a; {
int a=5;
a=1;
while (a !=-1)
while (a<5) {
{ scanf("%d",&a);
printf("\n\t\t%d\t",a); printf("\n\t\t%d\t",a);
a++; }
}
getch();
}

WHILE STATEMENT
Syntax: while (test condition)
{
body of the loop
}
Explanation
 The while is an entry-controlled loop statement.
 The test-condition is evaluated and if the condition is true, then the body of the loop is
executed.
 After execution of the body, the test condition is once again evaluated and if it is true, the
body is executed once again.
 This process of repeated execution of the body continues until the test-condition finally
becomes false and the control is transferred out of the loop.
 On the exit, the program continues with the statement immediately after the body of the
loop.
 The body of the loop may have one or more statements.
 The braces are needed only if the body contains two or more statements.
Example Program:
# include <stdio.h>
# include <conio.h>
void main()
{
int i,count;
count=0;
i=1;
while (i<=5)
{
count=count+i;
i++;
}
printf("\n\n\n\tSum of Numbers:\t%d",count);
getch();
}
DO STATEMENT
 The while loop construct makes a test of condition before the loop is executed.
 The body of the loop may not be executed at all if the condition is not satisfied.
 To execute the body of the loop before the test is performed do construct is used.
Syntax : do
{
body of the loop
}
while (test-condition);
 On reaching the do statement, the program proceeds to evaluate the body of the loop first.
 At the end of the loop, the test-condition in the while statement is evaluated.
 If the condition is true, the program continues to evaluate the body of the loop once again.
 This process continues as long as the condition is true.
 When the condition becomes false, the loop will be terminated and the control goes to the
statement that appears immediately after the while statement.
 Since the test condition is evaluated at the bottom of the loop, the do.. while construct
provides an exit-controlled loop and therefore the body of the loop is always executed at least
once.
# include <conio.h>
main()
{
int i,n,res=0,cnt=1;
printf("\n Enter the Total Number \n");
scanf("%d",&n);

do
{
printf (" \n Enter the %d number",cnt);
scanf("%d",&i);
res=res+i;
FOR STATEMENT
cnt++;
}
The for loop is another entry-controlled loop that provides
while (cnt<=n);
printf("The Addition Result : \t%d",res);
}

Syntax:
for (initialization ; test-condition ; increment)
{
body of the loop }
Execution of for statement:
 Initialization of the control variables is done first, using assignment statements such as i =1
and count = 0.
 The variables i and count are known as loop-control variables.
 The value of the control variable is tested using the test-condition. The test condition is a
relational expression, such as i <5 that determines when the loop will exit.
 If the condition is true, the body of the loop is executed; otherwise the loop is terminated and
the execution continues with the statement that immediately follows the loop
 When the body of the loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop.
 The control variable is incremented using assignment statement
 The new value of the control variable is again tested to see whether it satisfies the loop
condition.
 If the condition is satisfied, the body of the loop is again executed.
 This process continues till the value of the control variable fails to satisfy the test-condition
Additional Features of For Loop:
The for loop in C has several capabilities that are not found in other loop constructs.
Multiple Arguments Initialization:
 More than one variable can be initialized at a time in the for statement
Ex: for (n=1,m=50;n<=m;n=n+1,m=m-1)
{
p=m/n;
printf(“%d%d%d\n”,n,m,p);
}
 The multiple arguments in the increment section are separated by commas.
Compound Relation in Test Condition:
 Test-condition may have any compound relation and the testing need not be limited only to
the loop control variable.
Example: sum=0;
for (i=1;i<20 && sum<100;++i)
{
sum=sum+i;
printf(“%d%d\n”,i,sum);
}
 The loop uses a compound test condition with the counter variable i and sentinel variable
sum.

Expressions in Assignment Statements:


 It is also permissible to use expressions in the assignment statements of initialization and
increment sections.
For example,
for (x=(m+n)/2;x>0;x=x/2)
Omission of Section:
 Another unique aspect of for loop is that one or more sections can be omitted, if necessary
Consider the following statements
m=5;
for (;m!=100;)
{
printf(“%d\n”,m);
m=m+5;
}
 Both the initialization and increment sections are omitted in the for statement.
 The initialization has been done before the for statement and the control variable is
incremented inside the loop.
 The sections are left “blank”.
 The semicolons separating the sections must remain.
 If the test-condition is not present, the for statement sets up an “infinite” loop.
Time Delay Loop:
 Time delay loops can be set using null statement as follows:
for (j=1000;j>0;j=j-1)
;
 This loop is executed 1000 times without producing any output; it simply causes a time
delay.
 The body of the loop contains only a semicolon, known as a null statement.

EX:
# include <conio.h>
main()
{
int i;
for( i=5;i>=1;i--)
{
printf("%d\t",i);
}
getch();
}
EX:
# include <conio.h>
main()
{
int i;
for( i=5;i>=1;i--)
{
printf("%d\t",i);
}
getch();
}
Nesting of For Loops
 Analyze the problem and see whether it required a pre-test loop.
 If it requires a post- loop, then we can use only one loop, do while.
 If it requires a pre-test loop, then we have two choices: for and while.
 Decide whether the loop termination requires counter-based control or sentinel-based
control.
 Use for loop if the counter-based control is necessary.
 Use while loop if the sentinel-based control is required.
 Both the counter-controlled and sentinel-controlled loops can be implemented by all the three
control structures
 Nesting of loops, that is, one for statement within another for statement is allowed in C.
 The nesting may continue up to any desired level.
 The loops should be properly indented so as to enable reader to easily determine which
statements are contained within each for statement.
JUMPS IN LOOPS
 Loops perform a set of operations repeatedly until the control variable fails to satisfy the test-
condition.
 The number of times a loop is repeated is decided in advance and the test condition is written
to achieve this.
 Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to leave
the loop as soon as a certain condition occurs.
 For example, consider the case of searching for a particular name in a list containing, say,
100 names. A program loop written for reading and testing the names 100 times must be
terminated as soon as the desired name is found. C permits a jump from one statement to
another within a loop as well as a jump out of a loop.
Jumping out of a loop:When a break statement is encountered inside a loop, the loop is
immediately exited and the program continues with the statement immediately following the
loop.
 When the loops are nested, the break would only exit from the loop containing it. That is, the
break will exit only a single loop.
 goto statement can transfer the control to any place in a program, it is useful to provide
branching within a loop.
 goto is used to exit from deeply nested loops when an error occurs.
Skipping a part of a loop:
 During the loop operations, it may be necessary to skip a part of the body of the loop under
certain conditions.
 C supports another similar statement called the continue statement.
 However, unlike the break which causes the loop to be terminated, the continue, as the name
implies, causes the loop to be continued with the next iteration after skipping any statement
in between.
 The continue statement tells the complier, “skip the following statement and continue with
the next iteration”.
 The format of the continue statement is simply.
Syntax: continue;

 In while and do loops, continue causes the control to go directly to the test-condition and the
then to continue the iteration process.
 In the case of for loop, the increment section of the loops is executed before the test-
conditions is evaluated.
while (test condition)

…………..

if (………….)

for (initialization;
continue; test condition; increment)
{
…………
if (………..)
continue;
………….
}
# include <conio.h>
main()
{
int i,n,res=0,cnt=1;
printf("\n Enter the Total Number \n");
scanf("%d",&n);

while (cnt<=n)
{
printf (" \n Enter the %d number",cnt);
scanf("%d",&i);
if (i<=20)
break;
res=res+i;
cnt++;
}
printf("The Addition Result : \t%d",res);
}

Jumping out of the program


 We can jump out of a program by using the library function exit( ). In case, due to some
reason, we wish to break out of a program and return to the operating system, we can use the
exit( ) function, as shown below:
Example: if (test –condition)
exit (0) ;
 The exit( ) function takes an integer value as its argument.
 Normally zero is used to indicate normal termination and a nonzero value to indicate
termination due to some error or abnormal condition.
 The use of exit( ) function requires the inclusion of the header file <stdlib.h>.

ARRAYS
DEFINITION AND DECLARATION
 An array is a fixed-size sequenced collection of elements of the same data type.
 An array provides a convenient structure for representing data.
 An array is one of the data structures in C.
 Arrays are referred to as structured data types because they can be used to represent data
values that have a structure of some sort.
 List of temperatures recorded every hour in a day, or a month, or a year
 List of employees in an organization
 List of products and their cost sold by a store
 Test scores of class students
 List of customers and their telephone numbers
 Table of daily rainfall data
Array, Lists, Stacks, Queues and Trees.
 The fundamental data types, namely char, int, float, double and variations of int and double
constrained by the fact that a variable of these types can store only one value at any given
time.
 Therefore, they can be used only to handle limited amounts of data.
 In many applications, however, we need to handle a large volume of data in terms of reading,
processing and printing.
 To process such large amounts of data, we need a powerful data type that would facilitate
efficient storing, accessing and manipulation of data items.
 C supports a derived data type known as array that can be used for such applications.
 One-dimensional arrays
 Two-dimensional arrays
 Multidimensional arrays.

ONE-DIMENSIONAL ARRAYS
 A list of items can be given one variable name using only one subscript and such a variable is
called a single-subscripted variable or a one-dimensional array.
 The subscripts of an array can be integer constants, integer variables like i, or expressions
that yield integers.
 C performs no bounds checking and, therefore, care should be exercised to ensure that the
array indices are within the declared limits.
Ex: int number[5];
 The values to the array elements can be assigned as follows:

number[0]=35;
number[1]=40;
number[2]=45;
number[3]=50;

DECLARATION OF ONE-DIMENSIONAL ARRAY


 Arrays must be declared before they are used so that the complier can allocate space for them
in memory.
Syntax: type variable-name[ size ];
 The type specifies the type of element that will be contained in the array, such as int, float, or
char.
 The size indicates the maximum number of elements that can be stored inside the array.
Ex: int age[20];
float height[30];
char name[40];
 Any reference to the arrays outside the declared limits would not necessarily causes an error.
Rather, it might result in unpredictable program results.
 The size should be either a numeric constant or a symbolic constant.
 The C language treats character strings simply as arrays of characters.
 The size in a character string represents the maximum number of characters that the string
can hold.
Ex: char name[10];
declares the name as character array (string) variable that can hold a maximum of 10 characters.
 When the compiler sees a character string, it terminates it with an additional null character.
 The name[10] holds the null character ‘\0’.
 When declaring character arrays, we must allow one extra element space for the null
terminator.

INITIALIZATION OF ONE-DIMENSIONAL ARRAY


 It is the process of arranging elements in the list according to their values, in ascending or
descending order.
 A sorted list is called an ordered list.
Ex: Bubble Sort, Selection Sort, Insertion Sort, Merge Sort and Quick Sort
 It is the process of finding the location of the specified element in a list.
 The specified element is often called the search key.
 If the process of searching is finds a match of the search key with a list element value, the
search said to be successful; otherwise, it is unsuccessful.
Ex: Sequential search, Binary search
An array can be initialized at either of the following stages:
At compile time
At run time
Compile time Initialization:
 The general form of initialization of array is:
type array-name[size] = { list of values };
 The values in the list are separated by commas. For example, the statement
int number [3] = { 0,0,0 };
will declare the variable number as an array of size 3 and will assign zero to each element.
 If the number of values in the list is less than the number of elements, then only that many
elements will be initialized.
 The remaining elements will be set to zero automatically. For instance,
float total [5] = {0.0,15.75.-10};
will initialize the first three elements to 0.0, 15.75, and -10.0 and the remaining two elements to
zero.
 If the type is of character NULL is initialized.
 The size may be omitted. In such cases, the complier allocates enough space for all initialized
elements. For example, the statements
int counter [ ] = {1,1,1,1};
will declare the counter array to contain four elements with initial values 1.
 Character arrays may be initialized in a similar manner. Thus, the statement
char name[ ] = {‘j’, ‘o’, ‘h’, ‘n’, ‘\o’};
declares the name to be an array of five characters, initialized with the string “john” ending with
the null character.
 Alternatively, we can assign the string literal directly as under:
char name [ ] = “john”;
 If we have more initializers than the declared size, the complier will produce an error. That
is, the statement
int number [3] = {10, 20, 30, 40};
will not work. It is illegal in C.

Run Time Initialization:


 An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays.
To sort n Numbers Using One Dimensional Array:
# include <stdio.h>
# include <conio.h>
void main()
{
int temp,a[20],i,j,n;
clrscr();
printf("Enter the Total Number of Elements\n");
scanf("%d",&n);
printf("Enter the Elements\n");
for (i=1;i<=n;i++)
scanf("%d",&a[i]);
for (i=1;i<=n-1;i++)
{
for (j=i+1;j<=n;j++)
{
if (a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}}

TWO-DIMENSIONAL ARRAYS
Syntax: type array_name [row_size] [column_size];
Two-dimensional arrays are stored in memory, as shown below.
Each dimension of the array is indexed from zero to its maximum size minus one.
The first index selects the row and the second index selects the column within that row.
Memory layout (Two-dimensional Array)
 The subscripts in the definition of a two-dimensional array represent rows and columns.
 This format maps the way that data elements are laid out in the memory.
 The elements of all arrays are stored contiguously in increasing memory location, essentially
in a single list.
 If we consider the memory as a row of bytes, with the lowest address on the left and the
highest address on the right, a simple array will be stored in memory with the first element at
the left and the last element at the right end.
 Similarly, a two-dimensional array is stored “row-wise, starting from the first row and ending
with the last row, treating each row like a simple array”.

Memory layout (Multi-dimensional Array)


For a multi-dimensional array, the order of storage is that the first element stored has 0 in all its
subscripts; the second has all of its subscripts, 0 except the far right which has a value of 1 and
so on.
The elements of a 2*3*3 array will be stored as under
1 2 3 4 5 6 7 8
9
000 001 002 010 011 012 020 021 022

10 11 12 13 14 15 16 17
18
100 101 102 110 111 112 120 121 122
INITIALIZING TWO-DIMENSIONAL ARRAYS
 Two-dimensional arrays may be initialized by following their declaration with a list of initial
values enclosed in braces. For example,
int table [2] [3] = {0,0,0,1,1,1};
 initializes the elements of the first row to zero and the second row to one. The initialization is
done row by row. The above statement can be equivalently written as
int table [2] [3] = {{0,0,0},{1,1,1}};
by surrounding the elements of the each row by braces.
 We can also initialize a two-dimensional array in the form of a matrix as shown below:
int table [2] [3] = {
{0,0,0},
{1,1,1}
};
 Commas are required after each brace that closes off a row, except in the case of the last row.
 When the array is completely initialized with all values, explicitly, we need not specify the
size of the first dimension. That is, the statement
int table [ ] [3] = {
{0,0,0}
{1,1,1}
};
is permitted.
 If the values are missing in an initializer, they are automatically set to zero. For instance, the
statement
int table[2] [3] = {
{1,1},
{2}
};
will initialize the first two elements of the first row to one, the first element of the second row to
two, and all other elements to zero.
 When all the elements are to be initialized to zero, the following short-cut method may be
used.
int m[3] [5] = {{0},{0},{0}};
 The first element of each row is explicitly initialized to zero while other elements are
automatically initialized to zero. The following statement will also achieve the same result:
int m [3] [5] = {0,0};
MULTI-DIMENSIONAL ARRAYS
 C allows arrays of three or more dimensions. The exact limit is determined by the complier.
The general form of a multi-dimensional array is
type array_name [s1] [s2][s3]……[sm];
where si is the size of the ith dimension. Some example are:
int survey [3][5][12];
float table [5][4][5][3];
During initialization of multi-dimensional arrays, it is an error to omit the array size for any
dimension other than the first.
Sample Code:
# include <conio.h>
main()
{
int a[6][6][6],i,j,k;
clrscr();
for (i=1;i<=2;i++)
for (j=1;j<=2;j++)
for (k=1;k<=2;k++)
scanf("%d",&a[i][j][k]);
printf("\n\t\t\t");
for (i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
for (k=1;k<=2;k++)
{
printf("%d\t",a[i][j][k]);
}
printf("\n\t\t\t");
}
}
getch();
}
DYNAMIC ARRAYS
 An array created at compile time by specifying size in the source code has a fixed size and
cannot be modified at run time.
 The process of allocating memory at compile time is known as static memory allocation
and the arrays that receive static memory allocation are called static arrays.
 This approach works fine as long as we know exactly what our data requirements are.
 Consider a situation where we want to use an array that can vary greatly in size.
 Modern language like C does not have this limitation.
 In C it is possible to allocate memory to arrays at run time.
 This feature is known as dynamic memory allocation and the arrays created at run time are
called dynamic arrays.
 Dynamic arrays are created using what are known as pointer variables and memory
management functions malloc, calloc and realloc.
 These functions are included in the header file <stdlib.h>.
 The program instructions and global and static variables are stored in a region known as
permanent storage area and the local variables are stored in another area called stack.
 The memory space that is located between these two regions is available for dynamic
allocation during execution of the program.
 This free memory region is called the heap.
 The size of the heap keeps changing when program is executed due to creation and death of
variables that are local to functions and blocks.

malloc:
 Allocates request size of bytes and returns a pointer to the first byte of the allocated space.
Syntax: ptr=(cast-type *) malloc (byte-size);
Example: x=(int*)malloc(100*sizeof(int));
 On successful execution of this statement, a memory space equivalent to “100 times the size
of an int” bytes reserved and the address of the first byte of the memory allocated is assigned
to the pointer x of type of int.
calloc:
 Allocates space for an array of elements, initializes them to zero and then returns a pointer to
the memory.
Syntax: ptr=(cast-type *) calloc(n, elem-size);
free:
 Frees previously allocated space.
Syntax: free(ptr);
realloc:
 Modifies the size of previously allocated space.
Example Program:
# include <stdio.h>
# include <conio.h>
void main()
{
int *ptr,n,i;
printf("Enter the Size of the array\n");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
for (i=1;i<=n;i++)
{
*ptr=i;
printf("%d",*ptr);
ptr++;
} getch();
}
CHARACTER ARRAYS AND STRINGS
INTRODUCTION
 A string is a sequence of characters that is treated as a single data item.
 Any group of characters (except double quote sign) defined between double quotations marks is a
string constant.
 If we want to include a double quote in the string to be printed, then we may use it with a back slash.
Example: printf(“\” well done !”\”);
will output the string “well done !”
The statement
printf(“Well Done !”);
will output the string Well Done!
 Character strings are often used to build meaningful and readable programs. The common operations
performed on character strings include:
Reading and writing strings.
Combining strings together.
Copying one string to another.
Comparing strings for equality.
Extracting a portion of a string.

DECLARING AND INITIALIZING STRING VARIABLES


 C does not support strings as a data type. C represents strings as character arrays.
Syntax: char string_name[size];
 The size determines the number of characters in the string_name.
Example: char city [10]
char name [30]
 When the compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of string.
 The size should be equal to the maximum number of characters in the string plus one.
 Character arrays may be initialized when they are declared.
 C permits a character array to be initialized in either of the following two forms:
char city [9] = “ new york “;
char city [9] = {‘n,’ ‘e’, ‘w’,’ ‘, ‘y’, ‘o’, ‘r’, ‘k’, ‘\0’};
 C also permits us to initialize a character array without specifying the number of elements.
 In such cases, the size of the array will be determined automatically, based on the number of elements
initialized.
Example: char string[ ]={‘g’,’o’,’o’,’d’,’\0’};
defines the array string as a five element array.
 We cannot separate the initialization from declaration.
 An array name cannot be used as the left operand of an assignment operator.

Terminating null character


 The string is a variable-length structure and is stored in a fixed-length array. The array size is not
always the size of the string and most often it is much larger than the string stored in it. Therefore, the
last element of the array need not represent the end of the string.
 The null character serves as the “end-of-string” marker.
EX:
# include <conio.h>
main()
{
char name1[5]={'r','a','j','a','\0'};
char name2[5]="ravi";
char name3[]="siva";
char name4[5];
clrscr();
scanf("%s",name4);
printf("\n\t\t\t%s",name1);
printf("\n\t\t\t%s",name2);
printf("\n\t\t\t%s",name3);
printf("\n\t\t\t%s",name4);
getch();
}
READING STRINGS FROM TERMINAL
Using scanf function
 The input function scanf can be used with %s format specification to read in a string of characters.
Example:
char name[10]
scanf (“%s”, name);
 The problem with the scanf function is that it terminates its input on the first white space it finds.
 A white space includes blanks, tabs, carriage returns, form feeds, and new lines.
 The scanf function automatically terminates the string that is read with a null character and therefore
the character array should be large enough to hold the input string plus the null character.
 The ampersand (&) is not required before the variable name.
 Field width can be specified using the form %ws in the scanf statement for reading a specified
number of characters from the input string.
Example: scanf (“ws”, name);
Here, two things may happen.
 The width w is equal to or greater than the number of characters typed in. The entire string will be
stored in the string variable.
 The width w is less than the number of characters in the string. The excess characters will be
truncated and left unread.
Consider the following statements:
char name [10];
scanf (“%5s”, name);
The input string RAM will be stored as

R A M \O ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9

The input string KRISHNA will be stored as


K R I S H \O ? ? ? ?
0 1 2 3 4 5 6 7 8 9

Reading a line of Text


 C supports a format specification known as the edit set conversion code % [. .] that can be used to
read a line containing a variety of characters, including white spaces. For example,
The program segment
char line [80];
scanf (“%[^\n]”, line);
printf (“%s”, line);
will read a line of input from the keyboard and display the same on the screen.
Using getchar and gets functions
 To read a single character from the terminal, getchar function can be used.
 We can use this function repeatedly to read successive single characters from the input and place
them into a character array.
 Thus, an entire line of text can be read and stored in an array.
 The reading is terminated when the new line character (‘\n’) is entered and the null character is then
inserted at the end of string.
Example: char ch;
ch =getchar( );
getchar function has no parameters.
EX:
# include <conio.h>
main()
{
char line[20],character;
int c;
c=0;
printf("\nEnter Text \n");
do
{
character=getchar();
line[c]=character;
c++;
}
while (character != '\n');
c=c-1;
line[c]='\0';
printf("\n\t\t%s",line);
getch();
}

Another and more convenient method of reading a string of text containing white spaces is to use the
library function gets available in the <stdio.h> header file.
Syntax: gets (str);
str is a string variable. It reads characters into str from the keyboard until a new-line character is
encountered and then appends a null character to the string.
Unlike scanf, it does not skip white spaces.
Example: char line [80]
gets (line);
printf (“%s”, line);
reads a line of text from the keyboard and displays it on the screen.
 C does not provide operators that work on strings directly.

Program to Copy one string into another.


# include <conio.h>
main()
{
char word1[20],word2[20];
int i;
clrscr();
printf("\nEnter Word \n");
scanf("%s",word1);
for (i=0;word1[i]!='\0';i++)
word2[i]=word1[i];
word2[i]='\0';
printf("\n\t\t The Word is : %s",word2);
getch();
}
WRITING STRING TO SCREEN
Using printf function
printf function with %s format are used to print strings to the screen.
 The format %s can be used to display an array of characters that is terminated by the null character.
Example: printf(“%s”, name);
can be used to display the entire contents of the array name.
 We can also specify the precision with which the array is displayed. For instance, the specification
%10.4
indicates that the first four characters are to be printed in a field width of 10 columns.
 If we include the minus sign in the specification ( %-10.4s), the string will be printed left-justified.
Features of %s specifications
 When the field width is less than the length of the string, the entire string is printed.
 The integer value on the right side of the decimal point specifies the number of characters will be
printed.
 When the number of characters to be printed is specified as zero, nothing is printed.
 The minus sign in the specification causes the string to be printed left-justified.
 The specification %.ns prints the first n characters of the string.
 C supports another character handling function putchar to output the values of character variables.
Example: char ch = ‘a’;
putchar (ch);
 The function putchar requires one parameter. This statement is equivalent to:
printf(“%c”, ch);
 We can use this function repeatedly to output a string of characters stored in an array using a loop.
Example:
char name[6] = “paris”
for (i=0, i<5; i++)
putchar (name[i]);
putchar(‘\n’);
 Another and more convenient way of printing string values is to use the function puts declared in the
header file <stdio.h>.
 This is a one parameter function and invoked as under:
puts (str);
where str is a string variable containing a string value. This prints the value of the string variable str and
then moves the cursor to the beginning of the next line on the screen. For example, the program segment
char line [80]
gets (line);
puts (line);
reads a line of text from the keyboard and displays it on the screen.
STRING HANDLING FUNCTIONS
String-handling functions
Function Action
strcat( ) concatenates two strings
strcmp( ) compares two strings
strcpy( ) copies one string over another
strlen( ) finds the length of a string
strcat( ) function:
 The strcat function joins two strings together. It takes the following from:
Syntax: strcat (string1,string2);
 string1 and string2 are character arrays. When the function strcat is executed, string2 is appended
to string1. It does so by removing the null character at the end of string1 and placing string2 from
there. The string at string2 remains unchanged. For, example, consider the following three strings:
0 1 2 3 4 5 6 7 8 9
0 1
V E R Y \0
Part1 =

0 1 2 3 4 5 6
G O O D \0 Part2 =

0 1 2 3 4 5 6
B A D \0 Part3 =

Execution of the statement


strcat (part1,part2);
will result in:
0 1 2 3 4 5 6 7 8 9 0 1 2
V E R Y G O O D \0
Part1 =

0 1 2 3 4 5 6

G O O D \0 Part2=

While the statement strcat(part1,part3)


will result in:
0 1 2 3 4 5 6 7 8 9 0
1 2
V E R Y B A D \0
part1=

0 1 2 3 4 5 6
B A D \0 part3=
 We must make sure that the size of string1 (to which string2 is appended) is large enough to
accommodate the final string.
strcat function may also append a string constant to a string variable. The following is valid
strcat (part1,”GOOD”);
 C permits nesting of strcat functions. For example, the statement
strcat(strcat(string1,string2), string3);

strcmp( ) function:
 The strcmp function compares two strings identified by the arguments and has a value 0 if they are
equal. If they are not, it has the numeric difference between the first nonmatching characters in the
strings.
Syntax: strcmp(string1, string2);
string1 and string2 may be string variables or string constants. Examples are:
strcmp (name1, name2);
strcmp (name1, “john”);
strcmp (“rom”, “ram”);
strcmp (“their”, “there”);
will return a value of -9 which is the numeric difference between ASCII “i” and ASCII “r” that is, “i”
minus “r” in ASCII code is-9. If the value is negative, string1 is alphabetically above string2.

strcpy ( ) function
 The strcpy function works almost like a string-assignment operator. It takes the form:
strcpy(string1,string2);
and assign the contents of string2 to string1. string2 may be a character array variable or a string
constant. For example, the statement
strcpy(city, “SALEM” );
will assign the string “SALEM”to the string variable city. Similarly, the statement
strcpy(city1, city2);
will assign the contents of the variable city2 to the string variable city1. The size of the array city1 should
be large enough to receive the contents of city2.
strlen( ) function:
 This function counts and returns the number of characters in a string. It takes the form
n = strlen(string);
where n is a integer variable, which receives the value of the length of the string. The argument may be a
string constant. The counting ends at the first null character.
Other String Functions
strncpy function:
 In addition to the function strcpy that copies one string to another, we have another function strncpy
that copies only the left-most n characters of the source string to the target string variable. This is a
three-parameter function and is invoked as follows:
strncpy(s1, s2, 5);
 This statement copies the first 5 character of the source string s2 into the target string s1. Since the 5
characters may not include the terminating null character, we have to place it explicitly in the 6 th
position of s2 as shown below:
s1[6] =’\0’;
Now, the string s1 contains a proper string.

strncmp function:
 A variation of the function strcmp is the function strncmp. This function has three parameters as
illustrated in the function call below:
strncmp (s1, s2, n);
 This compares the left-most n character of s1 to s2 and returns
0 if they are equal;
Negative number, if s1 sub-string is less than s2; and
Positive number, otherwise.
strncat function:
 This is another concatenation function that takes three parameters as shown below:
 strncat(s1,s2,n);
This call will concatenate the left-most n characters of s2 to the end of s1.
strstr function:
 It is a two-parameter function that can be used to locate a sub-string in a string. This takes the forms:
Syntax: strstr (s1, s2);
Example: strstr (s1, “ABC”);
 The function strstr searches the string s1 to see whether the string s2 is contained in s1.
 If yes, the function returns the position of the first occurrence of the sub-string. Otherwise, it returns a
NULL pointer.
Example:
 We also have functions to determine the existence of a character in a string. The function call
strchr(s1, ‘m’);
will locate the first occurrence of the character ‘m’ and the call
strrchr(s1, ‘m’);
will locate the last occurrence of the character ‘m’ in the string s1.
 When allocating space for a string during declaration, remember to count the terminating null
character.
 When creating an array to hold a copy of a string variable of unknown size, we can computer the size
required using the expression strlen (stringname)+1.
 When copying or concatenating one string to another, we must ensure that the target (destination)
string has enough space to hold the incoming characters.
 When we use strncpy to copy a specific number of characters from a source string, we must ensure to
append the null character to the target string, in case the number of characters is less than or equal to
the source string.
TABLE OF STRINGS
 A list of names can be treated as a table of strings and a two dimensional character array can be used
to store the entire list.
# include <stdio.h>
# include <string.h>
main()
{
char a[5][5],i,n;
clrscr();
printf("\n Enter the Total Employees \n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
printf("\n Enter a Employee Name \n");
scanf("%s",a[i]);
}
printf("\n\t\tEmployee List \n");
for (i=1;i<=n;i++)
printf("\n%s",a[i]);
getch();
}

You might also like