0% found this document useful (0 votes)
8 views

C Program Unit II Complete Notes_231103_110902 (1)

This document covers decision-making statements in C programming, including if, if-else, nested if-else, else-if ladder, and switch case statements. It explains their structures, uses, and provides examples for each type of statement. Additionally, it introduces looping concepts, differentiating between entry-controlled and exit-controlled loops, with explanations and flowcharts for clarity.

Uploaded by

Bindudhar T R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C Program Unit II Complete Notes_231103_110902 (1)

This document covers decision-making statements in C programming, including if, if-else, nested if-else, else-if ladder, and switch case statements. It explains their structures, uses, and provides examples for each type of statement. Additionally, it introduces looping concepts, differentiating between entry-controlled and exit-controlled loops, with explanations and flowcharts for clarity.

Uploaded by

Bindudhar T R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Unit II „C‟ Programming

Decision making:
Decision making statements allow you to deciding the order of execution of statements
based on certain conditions in program.

Decision making statements are:

1. if statement
2. if-else statement
3. nesting if-else statement
4. else-if ladder statement
5. switch case statement

Since these statement controls the flow of execution, they are also known as control statements.

Description of decision making:

 if statement: if statement is used to control the flow of execution of statements. It


allows evaluate the condition or expression first and then, depending on whether the
value of the expression is true or false.
 if-else statement: if-else statement is used to carry out a logical test and then take
one of two possible actions depending on the result of the test.
 Nesting if-else statement: nesting if-else statements are used, when a series of
decisions are concerned, we may have to employ more than one if-else statement.
 else-if ladder statements: else-if ladder statements are used, when multipath
decisions are concerned. A multipath decision is a chain of ifs in which the
statement associated with each else is an if.
 switch case statement: switch statement checks the value of a given expression
against a list of case values and when a match is found a block of statements
associated with the case is executed.

SIMPLE IF STATEMENT
The simple if statement is an influential decision making statement. It is used to
control the flow of execution of statements. On other hand, it is also a two-way decision
making statement. It is also used to evaluate the expression or condition first and then,
depending on whether the value of the expression is true or false.
The general structure of a simple if statement is as follows:
if ( Condition/expression )
{
Statement-block;
………………….
}
Statement-n;

Priya M R, NIE 1
Unit II „C‟ Programming

Here, statement-block can be single or a group of statements. If condition/expression is


true then, the statement-block will be executed, otherwise the statement-block will be omitted
and the execution will jump to the statement-n.
In this situation, it is remembered that, when the condition is true both the statement-
block and statement-n are executed in sequence.
The general flow chart of if statement is shown in below:

Figure(if): Flowchart of simple if control statement

Example:
main()
{
…………………………….
……………………………
if( N= =100)
{ N=N+5
0;
}
printf(“%d”, N);
. ……………………
……………………..
}
In the above program segment, the program checks the value of N. If the value of
N is 100 then extra 50 are added with N before printed, otherwise the value of N will be
printed.

Priya M R, NIE 2
Unit II „C‟ Programming

Example program: Program to display a number if user enters negative number. If user
enters positive number, that number won't be displayed.
#include<stdio.h>
void main()
{
int num;
printf("Enter Integer Number:");
scanf("%d",&num);
if(num < 0)
{
printf("You entered %d. \n", num);
}
printf("Have a nice Day!!");
}

SIMPLE IF-ELSE STATEMENT


The if-else statement is an extension of the simple if statement. This type of
statement is used to carry out a logical test and then take one of the two possible actions
depending on the result of the test. The general structure of if-else statement is as follows:
if (test condition/expression)
{
True statements-block;
}
else
{
False statements-block;
}
statement- n;

The if-else statement executes some code if the test condition or expression is true and
some other code if the test expression or condition is false.
Here, if the test condition or expression is true (non-zero) then true statements-block is
executed otherwise false (zero) statements-block is executed. It is remembered that, in if-else
statement, either true statements-block or false statements-block will be executed, not both. In
both cases the control is transferred subsequently to statement-n.

Priya M R, NIE 3
Unit II „C‟ Programming

The general flow chart of if-else statement is shown in below:

Figure(ie): flowchart of if-else control statement

Consider the following program segment:


void main()
{
................
................
if(test = = 1)
{
scanf("%f",&radious);
Area=3.14159*radious*radious;
printf("Area of Circle is:= %f\n",Area);
}
else
{
scanf("%f %f",&base,&height);
Area=0.5*base*height;
printf("Area of traingle is:= %f\n",Area);
}
}

In the above example, if the variable test value is only 1 then true statement block
of if will be executed and print the area of circle, otherwise false statement block of else will
be executed and print the area of triangle.

Priya M R, NIE 4
Unit II „C‟ Programming

Example:
void main()
{
int age;
printf(" Enter your real
age:"); scanf("%d",&age);
if(age >= 18)
{
printf("you are eligible for voting.");
}
else
{
printf("you are not eligible for voting.");
}
}

In the above example, user enter his or her age from keyboard, if the variable age
value is greater than or equal 18 years then, true statement block of if will be executed and
print „you are eligible for voting’, otherwise false statement block of else will be executed
and print „you are not eligible for voting’.

NESTING OF IF-ELSE STATEMENTS


The if-else statement executes only two different codes depending upon whether the test
expression/condition is true or false. However, in practical, sometimes, a choice has to be
made from more than two possibilities.
When sequences of decisions are concerned, we may have to apply more than one
if-else statement in nested form. Nested if-else statement is similar to if-else statement, where
new block of if-else statement is defined in existing if or else block statement. The nested if-
else statement allows us to verify for multiple test expressions and execute different codes for
more than two conditions.
The general structure of nesting of if-else statement is as follows:
if(test expression-1)
{
if(test expression-2)
{
block of statement-1;
}
else
{
block of statement-2;

Priya M R, NIE 5
Unit II „C‟ Programming

}
else
{
block of statement-3;
}
statement-n;

The logic execution flow chart is demonstrated in figure(nie).

Figure(nie): flowchart of nested if-else statements

From the flowchart, we can say that, if the test expression-1 is false the block
statement-3 will be executed; otherwise it continues to perform the second test expression. If
the test expression-2 is true the block statement-1 will be executed; otherwise the block
statement-2 will executed and then the control goes to the statement-n and so on.

Example: Program to check username and password for login using nested if-else
statements.
#include <stdio.h>
main()
{
char username;
int password;
printf("Enter Your Username:");

Priya M R, NIE 6
Unit II „C‟ Programming

scanf("%c",&username);
printf("Enter Your Password:");
scanf("%d",&password);
if(username = ='a')
{
if(password = =12345)
{
printf("Login successful");
}
else
{
printf("Password is incorrect, Try again!!!");
}
}
else
{
printf("Username is incorrect, Try again!!!");
}
}

ELSE-IF LADDER STATEMENTS


When we need to test different conditions with different statements, where
multipath decisions are involved, this is called else-if ladder. Actually multipath decision is
a sequence of ifs in which the statements related with each else is an if. If-else ladder
statement is used to test set of conditions in sequence that is if we have different test
conditions with different statements then we need else-if ladder statements.

The general syntax of if-else ladder is as follows:


if (test_condition-1)
{
statement-1;
}
else if(test_condition-2)
{
statement-2;
}
else if(test_condition-3)
{
statement-3;
}
else if(test_condition-4)
{
statement-4;
}
………………
else if(test_condition-n)

Priya M R, NIE 7
Unit II „C‟ Programming

{
statement-n;
}
else
{
default-statement;
}
Statement-X;

The above construction is known as if-else ladder. Here, the conditions are evaluated
from top to bottom. As soon as when a test condition is true, then the statement(s)
associated with it is executed and the programming control is transferred to the statement-
X. When all conditions are failed or false then the final else containing the default-
statement will be executed. The flowchart of if-else ladder is shown in bellow:

Figure(ieladder): Flowchart of if-else ladder

Priya M R, NIE 8
Unit II „C‟ Programming

Example program: Program to find largest of three number using else-if ladder.
#include <stdio.h>
main()
{
int n1, n2, n3;

printf("Enter three different numbers: ");


scanf("%d %d %d", &n1, &n2, &n3);

if (n1 >= n2 && n1 >= n3)


printf("%d is the largest number.", n1);

else if (n2 >= n3)


printf("%d is the largest number.", n2);

else
printf("%d is the largest number.", n3);

SWITCH CASE STATEMENT


C has built-in multi-way decision statement known as switch statement. A switch
statement tests the value of a given variable or expression against a list of case values. In
this statement, when case is matched or found then block of statements associated with that
case is executed. This type of statement is mostly used when we have number of options or
choices or cases and we may need to perform a different task for each choice or case. The
general syntax of switch case statement is as follows:
switch (variable or expression)
{
case Constant-1:
block-code-1;
break;
case Constant-2:
block-code-2;
break;
case Constant-3:
block-code-3;
break;
……………………………
……………………………
case Constant-n:
block-code-n;
break;
default:
default block;

Priya M R, NIE 9
Unit II „C‟ Programming

break;
}
Statement-X;

In the above syntax, the expression is an integer expression or characters. Constant-1,


Constant-2, Constant-3…. Constant-n are known as case labels. Here, each of these values
must be unique within switch statement and bock-code-1, bock-code-2, bock-code-3…
bock-code-n are statement lists.
When switch is executed the variable or value of the expression is successively compared
against the cases. If a case is found or matched with the value of the expression, then the
associated block code or statement(s) are executed.
The break statement at the end of the each block code means the end of specific case and
causes an exit from the switch statement, and for that reason, transfers program control to
statement-X. If the break statement is missed from any case, then program executes all
statements until get break statement from another case. The default is optional. When
variable or value of expression does not match with any of the case values then default
statement(s) are executed.

Figure(s): Flowchart of switch case statement

Example: Simple switch program


#include<stdio.h>
void main()
{
int a;
printf(“\n Enter any number
:”); scanf(“%d”, &a);
switch(a)
{
case 1 :
printf(“\n a is 1”);
break;

Priya M R, NIE 1
Unit II „C‟ Programming

case 2 :
printf(“\n a is 2”);
break;
default :
printf(“\n Number other than 1 and 2”);
break;
}
}

Example: Grading the marks of the students.


#include<stdio.h>
void main()
{
int marks, value;
printf("Enter the marks: ");
scanf("%d",&marks);
value =marks/10;
switch(value)
{
case 10:
case 9:
case 8:
printf("Well done Your grade is A+");break;
case 7:
printf("Well done Your grade is A-");break;
case 6:
printf("Well done Your grade is
B");break; case 5:
printf("Well done Your grade is C");
break; case 4:
printf("Well done Your grade is D");break;
default:
printf("Sorry Your grade is F!!");
}
}

Rules for switch statement


 The switch expression must be an integral type.
 Case labels must be constants or constant expressions.
 Case labels must be unique. No two labels can have the same value.
 Case labels must end with colon.
 The default label is optional. If present, it will be executed when the expression does not
find a matching case labels.
 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.

Priya M R, NIE 1
Unit II „C‟ Programming

Looping:
“When sequences of statements are executed repeatedly up to some condition then it is
known as Program Loop.”

A loop consists mainly two parts:


Body of loop
This part contains the sequences of statements, which are to be executed repeatedly.

Control statement:
This part contains certain conditions, which indicates how many times we have to
execute the body of loop. The control statement should be writing carefully otherwise it may
possible your loop is executed infinite times which is known as Infinite Loop. Loop contains
one or more variable, which control the execution of loop that is known as the Loop Counter.
Loop is executed basically in following steps:
1. Setting and initialization of Loop Counter.
2. Test the condition.
3. Executing the body of loop.
4. Incrementing or decrementing the Loop Counter value.

In above steps, 2nd and 3rd steps may be executed interchangeably that means either we
can perform step 2 first or step 3 first.

In general there are two types of loops: Entry Controlled loop and Exit controlled loop.

Entry-controlled loop
In entry-controlled loop we first check the condition and then the body of loop is
executed. If at first time condition is false then the body of loop and not executed any time.
It is also called as pre-test loop. In C programming language while loop and for loop is
example of entry-controlled loop. Fig(ec) shown the flow chart of Entry-controlled loop.

Fig(ec): Entry-controlled loop

Exit-controlled loop
In exit-controlled loop we first execute the body of the loop and then check the condition
and if condition is true then next again executed the body of the loop otherwise not. In exit
controlled loop it is sure the body of loop is executed once. It is also called as post-test loop.

Priya M R, NIE 1
Unit II „C‟ Programming

In C programming language do-while loop is example of the exit-controlled loop. Fig(exc)


show the flow chart of Exit-controlled loop.

Fig(exc): Exit-controlled loop

Differentiate Entry and Exit controlled loop:

Entry Controlled Loop Exit Controlled Loop


Test condition is checked first, and then Loop body will be executed first, and
loop body will be executed. then condition is checked.
If Test condition is false, loop body will If Test condition is false, loop body will
not be executed. be executed once.
It is also called as pre-test loop. It is also called as post-test loop.
for loop and while loop are the examples do while loop is the example of Exit
of Entry Controlled Loop. controlled loop.
Entry Controlled Loops are used when Exit Controlled Loop is used when
checking of test condition is mandatory checking of test condition is mandatory
before executing loop body. after executing the loop body.

In „C‟ language we have three loops format:


 while loop
 for loop
 do-while loop

Priya M R, NIE 1
Unit II „C‟ Programming

While Loop:
While loop is entry-controlled loop, in which first condition is evaluated and if
condition is true the body of loop is executed. After executing the body of loop the test
condition is again evaluated and if it is true then again body of loop is executed. This
process is going to continue up to your test condition is true. If the test condition is false
on initial stage then body of loop is never executed.

The format of while loop is:


while(test condition)
{
body of loop
}

Body of loop has one or more statements. Here the curly bracket is not necessary if body
of loop contains only one statement.

Fig(w): Flow chart of while loop

Example: Program to print 10 numbers start from 1.


void main( )
{
int i;
i=1; // Initialization of Loop Counter
while(i <= 10)
{ // Test condition
printf(“I = %d\n”,i); // Body of loop
i++; // Increment of Loop counter
}
}

Priya M R, NIE 1
Unit II „C‟ Programming

Here above program print the number from 1-10. First loop counter „i‟ is 1. Out test
condition is „i <=10‟ that means the value of „i‟ is less than or equal to 10. If test condition is
true then we are getting the value of „i‟. After printing the „i‟ value the value of „i‟ is
incremented by 1 and again check the test condition. This process is continuing till test
condition is true.

do…while loop:
In somecases we have such a condition in which it is mandatory to execute the body of
loop once whether test condition is true or false. At that time we have to use do-while loop.
do-while loop is exit-controlled loop, in which first condition body of loop is executed
first and then the test condition is evaluated and if the test condition is true then again body of
loop is executed. This process is repeated continuously till test condition is true. Here the
body of loop must be executed at least once.

The format of do-while loop is:


do
{
body of loop
} while (test condition);

Body of loop has one or more statements. Here the curly bracket is not necessary if body
of loop contains only one statement.

Fig(dw): Flow chart of do-while loop

Priya M R, NIE 1
Unit II „C‟ Programming

Example: we have to read the data till the number is less than 100 and if number is greater
than 100 then we have to terminate the loop.
void main( )
{
int number;
do
{
printf(“Enter any number :
“); scanf(“%d”, &number);
printf(“You have Entered %d\n”,number)
} while(number <=100) ;
}

Here first body of loop is executed mean we are reading number and then test
condition is evaluated (number is less than or equal to 100) if it is true then again we reading
another number otherwise the loop is terminated.

Difference between while and do-while loop:

While Do While
It checks the condition first and then This loop will execute the statement(s) at
executes statement(s) least once, then the condition is checked.
While loop allows initialization of Do while loop allows initialization of
counter variables before starting the body counter variables before and after starting
of a loop. the body of a loop.
It is an entry controlled loop. It is an exit controlled loop.
We do not need to add a semicolon at the We need to add a semicolon at the end of
end of a while condition. the while condition.
In case of a single statement, we do need Brackets are always needed.
to add brackets.
In this loop, the condition is mentioned at The loop condition is specified after the
the starting of the loop. block is executed.
Statement(s) can be executed zero times Statement is executed at least once.
if the condition is false.
Generally while loop is written as: Generally do while loop is written as:
while (condition) { do{
Statements; // loop body Statements; //loop body
} } while (condition);

Priya M R, NIE 1
Unit II „C‟ Programming

for loop
for loop is entry-controlled loop, in which first condition is evaluated and if condition
is true the body of loop is executed. After executing the body of loop the test condition is
again evaluated and if it is true then again body of loop is executed. This process is going
to continue up to your test condition is true. If the test condition is false on initial stage
then body of loop is never executed.

The format of for loop is:


for (initialization ; test-condition ; increment/decrement)
{
body of loop
}

In above format the first line contain initialization, test-condition, and increment-
decrement portion that means in „for‟ loop initialization, condition and
increment/decrement is done in only one line. First the loop counter is initialized. After
initialization the test condition is evaluated and if it true then body of loop is executed
and after execution of body of loop increment or decrement of loop counter is done.
Again the test condition is evaluated and it is true then the same process is done again.
This is continuing till the test condition is true. The flow chart of the for loop can be
drawn in Fig.(for).

Fig(for): Flowchart of for loop

Example: Determining the factorial of given number.


void main( )
{
int fact=1, n, i;
n=5; // Let assume we are determining the factorial of 5
for ( i = 1 ; i < = n ; i++ )
{
fact = fact * i;
}
printf(“The factorial = %d\n”, fact);
}

Priya M R, NIE 1
Unit II „C‟ Programming

Here the loop counter „i‟ is initialized by 1 at first time. Then test condition (The value of
„i‟ is less than or equal to „n‟) is evaluated and if it is true then „fact‟ is multiplied with
„i‟ and again assign to „fact‟. After executing the body of loop the value of „i‟ is
incremented by 1. Next again test condition is evaluated and if it is true then we are
proceeding in same way.

Additional features of for loop:


1. More than one variable can be initialized at a time in the for statement.
Ex:– for(p=1, n=0; n<10;++n )

2. The increment section may also have more than one part.
Ex:–for(n=1, m=50; n<=m;n=n+1, m =m–1)

The multiple arguments in initialization section & in the increment section are separated
by commas.

3. The test–condition may have any compound relation & the testing need not be limited
only to the loop control variable.
Ex:– for(i=1; i<10&&sum<100;i++)

4. It is also possible to use expressions in the assignment statements of initialization &


increment sections.
Ex:– for(x=(m+n)/2; x>0;x=x/2)

5. Another unique aspect of for loop is that one or more sections can be omitted, if
necessary.
Ex:–
m=5;
For(;m!=100;)
{
printf(“%d\n”,m);
m=m+5;
}

6. We can set uptime delay loops using the null statement as follows.
Ex:– for (i=1000;j>0;j=j–1);

This loop is executed 1000 times without producing any output. It simply causes a time
delay.

Priya M R, NIE 1
Unit II „C‟ Programming

6. Infinite loop
Ex- for(;;)
{
……………
……………
}

NESTED for LOOP


When we put loop inside the loop it is known as the nested loop. The nesting is
allowed up to 15 levels in ANSI C but many compilers allow more. Consider the example
of nested loop. In which the we are using two loops one is outer loop and another is inner
loop which is used to read marks and calculate the total of 4 student
for( i = 1 ; i<=4 ; i+ Outer loop
+)
{
t= 0;
for(j=1; j< =6 ;j++)
Inner loop
{
printf(“Enter the marks for %d subject : “,i);
scanf(“%d”, & m);
t= t + m;
}
}

Here the outer loop is having the loop counter „i‟ and inner loop has loop counter
„j‟. First outer loop is counter „i‟ is initialized by 1 and if test condition (i< = 4) is true
then next inner loop is executed in which the loop counter „j‟ is initialized by 1 and if test
condition (j <=6 ) is true then the marks of students are read and total is calculated, then
the loop counter „j‟ is incremented. This is continuing till the condition for the inner loop
is true. When condition for inner loop is false the loop counter „i‟ for outer loop is
incremented and again same process is done.

Jump Statement:
Jump statements make the control jump to another section of the program unconditionally
when encountered. It is usually used to terminate the loop or switch-case instantly. It is also
used to escape the execution of a section of the program.

Jump statements offered by C Programming Language:

 Break
 Continue
 Goto

Priya M R, NIE 1
Unit II „C‟ Programming

Break Statement:
A break statement is used exit from the loop/Jumping from the loop.
or
A break statement is used to terminate the execution of the rest of the block
where it is present and takes the control out of the block to the next statement.
Its syntax is:
break;

It is mostly used in loops and switch-case to bypass the rest of the statement and
take the control to the end of the loop.
The break statement, when used in nested loops only terminates the inner loop where
it is used and not any of the outer loops.

Figure(b): Break statement used in while, do-while, and for.

Example : how break statement works in C language.

#include <stdio.h>
main()
{
int i;
for (i = 1; i <= 15; i++)
{
printf("%d\n", i);
if (i == 10)
break;
}

Priya M R, NIE 2
Unit II „C‟ Programming

}
Output:-
1
2
3
4
5
6
7
8
9
10
In this program, we see that as soon as the condition if(i==10) becomes true the control
flows out of the loop and the program ends.

Continue:
The continue statement skips the current iteration of the loop and continues with
the next iteration.
Or
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

Its syntax is:


continue;

Example : how continue statement works in C language.


#include <stdio.h>
main()
{
int i, j;
for (j = 1; j < 5; j++)
{
if (j == 2)
continue;
printf("%d\n", j);
}
}

Output:-
1
3
4

Priya M R, NIE 2
Unit II „C‟ Programming

In this program, we see that the printf() instruction for the condition j=2 is
skipped each time during the execution because of continue.

Figure(c): Continue statement used in while, do-while and for loop.

When we use continue statement with while and do-while statements the execution control directly j

goto Statement:
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 be
made. 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:

Priya M R, NIE 2
Unit II „C‟ Programming

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;

The flow of control will jump to the statement immediately following the label
begin:. This happens unconditionally.

Example: how goto statement works.


#include <stdio.h>
main()
{
int i, j;
for (i = 1; i < 5; i++)
{
if (i == 2)
goto there;
printf("%d\n", i);
}
there:
printf("Two");

Output:-
1
Two

In this program, we see that when the control goes to the goto there; statement
when i becomes equal to 2 then the control next goes out of the loop to the label(there: )
and prints Two.

Priya M R, NIE 2
Unit II „C‟ Programming

Priya M R, NIE 2
Unit II „C‟ Programming

Arrays
 An array is defined as the collection of similar type of data items stored at
contiguous memory locations.
 Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc.
 It also has the capability to store the collection of derived data types, such as
pointers, structure, etc.
 The array is the simplest data structure where each data element can be randomly
accessed by using its index number.

Advantage of C Array
 Code Optimization: Less code to the access the data.
 Ease of traversing: By using the for loop, we can retrieve the elements of an
array easily.
 Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
 Random Access: We can access any element randomly using the array.

Different types of Arrays:


 One-dimensional arrays
 Two-dimensional arrays
 Multidimensional arrays

One-dimensional arrays:
An array is a group of related items that store with a common name.

Declaration of Array:
Syntax:
data_type array_name[array_size];

Here, type specifies the type of element that will be contained in the array, Such as int.
float, or char and the size indicates the maximum number of elements that can be stored inside.

Example:
int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Priya M R, NIE 2
Unit II „C‟ Programming

Initialization of One-dimensional array:

Array can initialized at either of the following stages:

 At compile time
 At run time

Compile Time Initialization:

We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared. The general form of initialization of arrays is:

type array-name[size] = { list of values} ;

where,
type, can be any basic type.
Size, maximum number of elements
The values in the list are separated by commas.

 Example-1:
int number[3] = { 0,0,0 };

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.

 Example-2:

float total [5] = {0.0,15.75,-10};

Initialize the first three elements to 0.0, 15.75, and -10.0 and the remaining two elements
to zero.

 The size may be omitted. In such cases, the compiler allocates enough space for all initialized
elements.

int counter[ ] = {1,1,1,1};

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', '\0'};

Priya M R, NIE 2
Unit II „C‟ Programming

Declares the name to be an array of five characters, initialized with the string
"John" ending with the null. Alternatively, we can also assign the string literal as
char name[ ] = "John";

 The number of initializers may be less than the declared size. In such case, the
remaining elements are initialized to zero.
int number [5] = {10, 20};

Will initialize the first two elements to 10 and 20 respectively, and the
remaining elements to 0.

 Example:
Char city[5]={„B‟};

Will initialize the first element to 'B' and the remaining four to NULL.

 If we have more initializers than the declared size, the compiler will produce an

error. int number [3] = {10, 20, 30, 40};

That is, the statement will not work. It is illegal in C.

Run Time Initialization


At array can be explicitly initialized at run time. This approach is usually applied
for initializing large arrays.
Example:
………..
………..
for(i=0;i<100;i++)
{
if i<50
sum[i]=0.0; /*assignment statement*/
else
sum[i]=1.0;
}

The first 50 elements of the array sum are initialized to zero while the remaining 50
elements are initialized to 1.0 at run time

Priya M R, NIE 2
Unit II „C‟ Programming

We can also use a read function such as scanf to initialize an array. For example,
the statements
int x[3];
sanf(“%d%d%d”, &x[0], &x[1], &x[2]);

Memory allocation:
Example:

int Number[N];

Base Address 10000 Number[0]


10004 Number[1]
10008 Number[2]
. .
. .
. .
xxxxxx Number[N-1]

Fig(ma): One-dimensional array

Fifure(ma) shows how memory is allocated to an integer array of N elements. Its base
address – address of its first element is 10000. Since it is an integer array, each of its element
will occupy 4 bytes of space. Hence first element occupies memory from 10000 to 10003.
Second element of the array occupies immediate next memory address in the memory, i.e.;
10004 which requires another 4 bytes of space. Hence it occupies from 10004 to 10007. In this
way all the N elements of the array occupies the memory space.

If the array is a character array, then its elements will occupy 1 byte of memory each. If it
is a float array then its elements will occupy 4/8 bytes of memory each. Total size or memories
allocated for the array are the sizes of individual elements in the array. Calculation of total size
of the array, multiply the number of elements with the size of individual element.

Total memory allocated to an Array = Number of elements * size of one element

Accessing Array Elements:


We can access any array element using array name and subscript/index written inside pair
of square brackets [].

Example:

int marks[5] = {5,2,9,1,1};


Priya M R, NIE 2
Unit II „C‟ Programming

We can access elements of array marks using subscript followed by array name.
marks[0] = First element of array marks = 5
marks[1] = Second element of array marks = 2
marks[2] = Third element of array marks = 9
marks[3] = Fourth element of array marks = 1
marks[4] = Last element of array marks = 1

Note: Array indexing starts from 0. Nth element in array is at index N-1.

Example program:
// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array

#include <stdio.h>

int main()
{
int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i)
{
printf("%d\n", values[i]);
}
return 0;
}

Priya M R, NIE 2
Unit II „C‟ Programming

Two-dimensional (2D) Array:


The two-dimensional array can be defined as an array of arrays. The 2D array is
organized as matrices which can be represented as the collection of rows and columns.

Declaration of two dimensional Arrays:


data_type array_name[rows][columns];

Example:
int twodimen[4][3];

Here, twodimen is an 2D array of int type. 4 is the number of rows, and 3 is the
number of columns.

Initializing Two-dimensional Arrays:


data_type array_name[rows][columns]={values};

Where,
values, initializes the elements row by row enclosed in braces and values
are separated by comma.

Examples:
 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.

Priya M R, NIE 3
Unit II „C‟ Programming

 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}
};

 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 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 elements are to be initialized 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};

Access the Elements of a 2D Array


To access an element of a two-dimensional array, you must specify the index
number of both the row and column.
Example:-
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf("%d", matrix[0][2]); // Outputs 2

This statement accesses the value of the element in the first row (0) and third
column (2) of the matrix array.

Priya M R, NIE 3
Unit II „C‟ Programming

Memory allocation:
The elements assigned to the memory location depend on the two different
methods: Row Major Order and Column Major Oder.

Example:
int arr[3][3];

Figure(2d) shows the memory allocation of 2D Array arr of integer type which
take four byte to store each element. Figure(2d) shows memory allocation row
major order of 3 rows and 3 columns. Let's assume the starting address of the
above 2D array as 1000.

Base Address

Figure(2d): 2D memory allocation

Calculation of 2D memory allocation:


Total memory allocated to 2D Array = Number of elements * size of one element
= Number of Rows * Number of Columns *
Size of one element

Example:
Total memory allocated of arr[3][3] = 3 * 3 * 4 = 24

Priya M R, NIE 3
Unit II „C‟ Programming

Example program:
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements.....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}

Priya M R, NIE 3
Unit II „C‟ Programming

String:
A string is a sequence of characters terminated with a null character „\0‟.

Declaration of the string:


C does not support strings as a data type. It allows us to represent strings as
character arrays.
Syntax:
char Variable_name[size];

Where,
Char, data type.
Variable_name, any valid variable_name.
Size, the number of characters in the Variable_name.

Example:
char city[10];

where,
city is a variable_name of a character array. It consists of 10 elements of type
charater.
Initialization of string:
Character arrays may be initialized when they are declared.

Syntax: char variable_name[size]="sequence of characters";

String variable is initialized within double quotes. The C compiler automatically


places the '\0' at the end of the string when it initializes the array.

Example:
1. char c[] = "abcd";
2. char c[50] = "abcd";
3. char c[] = {'a', 'b', 'c', 'd', '\0'};
4. char c[5] = {'a', 'b', 'c', 'd', '\0'};

First example, we can initialize a character array without specifying the


number of elements. The size of the array will be determined automatically,
based on the number of elements initialized.
Fourth and third example, defines the array of „c‟ as a five element array.
Figure(s1) shows the array of string represents.

Priya M R, NIE 3
Unit II „C‟ Programming

Fig(s1): String Initialization in C

READING STRINGS FROM TERMINAL:


The input function scanf can be used with %s format specification to read in a string of
characters.
Example: char address [10];
scanf("%s", address);

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.
Therefore, if the following line of text is typed in at the terminal:
NEW YORK

then only the string "NEW" will be read into the array address, since the blank space after
the word NEW will terminate the reading of string.

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. In the case of character arrays, the ampersand (&) is not required before the variable
name.

getchar and gets function:


getchar(): used to read a single character from the terminal. It repeatedly to read successive
single characters from the input and place them into a character array. The reading is terminated when
the newline character ('\n') is entered and the null character is then inserted at the end of the string.
Getchar() has no parameters.

Example:
char ch;
ch = getchar();

gets(): is used to read string. It has one parameter which is of string type.
Syntax: get(Str);

str is a string variable declaration. It reads characters into str from the keyboard until a
new-line encountered and then appends a null character to the string.

Priya M R, NIE 3
Unit II „C‟ Programming

Example:
char 1ine [80];
gets (1ine);
printf ("&s", line);

reads a line of text from the keyboard and displays it on the screen.

WRITING STRINGS To SCREEN


Using printf function with %s format 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) ;

Above example can be used to display the entire contents of the array name.

putchar() and puts() function:


putchar(): It is a character handling function, to output the values of character
Example:
char ch = 'A';
putchar (ch);

putchar requires one parameter. This statement is equivalent to printf("%c", ch);.

puts(): used to print string values. This is a one parameter function.


puts ( str );

where, str 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.
Example:
char line [80];
gets (line);
puts (line);

reads a line of text from the keyboard and displays it on the screen.

Priya M R, NIE 3
Unit II „C‟ Programming

STRING-HANDLING FUNCTIONS
String-handling functions that can be used to carry out string manipulations.
<string.h> header file should be included in program when we are using string handling
functions. Following are the most commonly used string-handing 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():
The strcat() function joins two strings together. It takes the following
form:
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. After
concatenation the result stored in string1. The string at string2 remains
unchanged.
Example:
string1="Good";
string2="Bye";
strcat(string1,string2); //Now string1 is "GOOD Bye"

 strcmp():
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. It takes the form:
strcmp(string1, string2);

string1 and string2 may be string variables or string constants.


Examples
1. name1="ABC";
name2="abc";
strcmp(name1, name2)
;

In this example, name1 and name2 are string type, After execution
of strcmp, it return a value of -32 which is the numeric difference between
ASCII "A" is 65 and ASCII "a" is 97, 65-97=-32. If the value is negative,
string1 is alphabetically above string2, strings are not equal.

Priya M R, NIE 3
Unit II „C‟ Programming

2. name1="John";
strcmp(name1, "John");

In this example, string name1 and second string constant value are same,
it returns 0.

3. strcmp("Rom", "Ram");

In the above example, both string constants are different. it return a


value of 14 which is the numeric difference between second letter ASCII "0"
is 111 and ASCII "a" is 97, 111-97=14. If the value is positive, string1 is
alphabetically below string2, strings are not equal.

 strcpy():
The strcpy function works almost like a string-assignmént operator. It takes
the following form:
strcpy(string1, string2);

In strcpy() function, assigns the contents of string2 to string1. string2 may


be a character array variable or a string constant.

Example: strcpy(city, "DELHI"); //city is DELHI

Above example will assign the string "DELHI" to the string variable city.
Similarly, the statement
city2="Hello";
strcpy(city1, city2); //Now city1 is Hello

will assign the contents of the string variable city2 to the string variable
city1. The size of the array city should be large enough to receive the
contents of city2.

 strlen():
This function counts and returns the number of characters in a string. It
takes the form:
n=strlen(string);

Where n is an 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.

Priya M R, NIE 3
Unit II „C‟ Programming

Example: int n;
char str[10]="Good Bye";
n=strlen(str);

In above example, function strlen() returns 8, which is number of


character in string str including space.

CHARACTER HANDLING FUNCTION:


Character handling library functions are the standard library functions that are
used for character processing in C. “ctype.h” header file should be included in program
when any of the following character handling function used.

1. toascii
2. toupper
3. tolower
4. isalpha
5. isdigit

1. toascii() : isascii in c checks the passed value is ascii character or not.

This function is defined in ctype.h header file.


This function returns non-zero digit if passed value is ascii character otherwise
zero.
Syntax:
int isascii(int a);

Parmeter:
This function takes character as input parameter and converts it into ASCII value.

Return value:
This function returns non-zero value if passed value is ascii character otherwise
zero.

Example program for isascii function in c

#include<stdio.h>
#include<ctype.h>
int main()
{
char val='a';

Priya M R, NIE 3
Unit II „C‟ Programming

if(isascii(val))
printf("This is ascii character \n");
else
printf("This is not ascii character \n");
return 0;
}

2. tolower(): This function takes an uppercase alphabet and convert it to a lowercase


character.
If the arguments passed to the tolower() function is other than an uppercase
alphabet, it returns the same character that is passed to the function.

It is defined in ctype.h header file.

Syntax:
int tolower(int argument);

The character is stored in integer form in C programming. When a character is


passed as an argument, corresponding ASCII value (integer) of the character is passed
instead of that character itself.

Example: How tolower() function works?

#include <stdio.h>
#include <ctype.h>
int main()
{
char c, result;

c = 'M';
result = tolower(c);
printf("tolower(%c) = %c\n", c, result);

c = 'm';
result = tolower(c);
printf("tolower(%c) = %c\n", c, result);

return 0;
}
Output
tolower(M) = m
tolower(m) = m

Priya M R, NIE 4
Unit II „C‟ Programming

3. toupper(): This function converts a lowercase alphabet to an uppercase


alphabet. The toupper() function is defined in the <ctype.h> header file.

Syntax:
int toupper(int ch);

This function takes a single argument. ch is a character.

Return value from toupper():

If an argument passed to toupper() is

a lowercase character, the function returns its corresponding uppercase character

an uppercase character or a non-alphabetic character, the function the character


itself.

Example: C toupper() function

#include <stdio.h>
#include <ctype.h>
int main()
{

char c;

c = 'm';
printf("%c -> %c", c, toupper(c));

c = 'D';
printf("\n%c -> %c", c, toupper(c));

c = '9';
printf("\n%c -> %c", c, toupper(c));
return 0;
}

Output:
m -> M
D -> D
9 -> 9

Priya M R, NIE 4
Unit II „C‟ Programming

4. isalpha(): This function checks whether a character is an alphabet or not.


In C programming, isalpha() function checks whether a character is an alphabet
(a to z and A-Z) or not.
If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not
it returns 0.
The isalpha() function is defined in <ctype.h> header file.

Syntax:
int isalpha(int argument);

Function isalpha() takes a single argument in the form of an integer and returns an
integer value. Even though, isalpha() takes integer as an argument, character is
passed to isalpha() function. Internally, the character is converted into the integer
value corresponding to its ASCII value when passed.

Isalpha() Return Value:


Return Value Remarks
Zero (0) If the parameter isn't an alphabet.
Non zero number If the parameter is an alphabet.

Example: C isalpha() function


#include <stdio.h>
#include <ctype.h>
int main()
{
char c;
c = 'Q';
printf("\nResult when uppercase alphabet is passed: %d", isalpha(c));

c = 'q';
printf("\nResult when lowercase alphabet is passed: %d", isalpha(c));

c='+';
printf("\nResult when non-alphabetic character is passed: %d", isalpha(c));

return 0;
}
Output
Result when uppercase alphabet is passed: 1
Result when lowercase alphabet is passed: 2
Result when non-alphabetic character is passed: 0

Priya M R, NIE 4
Unit II „C‟ Programming

5. isdigit(): This function checks whether a character is numeric character (0-9) or not.
Syntax:
int isdigit( int arg );

Function isdigit() takes a single argument in the form of an integer and returns the
value of type int.
Even though, isdigit() takes integer as an argument, character is passed to the
function. Internally, the character is converted to its ASCII value for the check.
It is defined in <ctype.h> header file.

C isdigit() Return value:


Return Value Remarks
Non-zero integer ( x > 0 ) Argument is a numeric character.
Zero (0) Argument is not a numeric
character.

Example: C isdigit() function


#include <stdio.h>
#include <ctype.h>

int main()
{
char c;
c='5';
printf("Result when numeric character is passed: %d", isdigit(c));

c='+';
printf("\nResult when non-numeric character is passed: %d", isdigit(c));

return 0;
}

Output
Result when numeric character is passed: 1
Result when non-numeric character is passed: 0

Priya M R, NIE 4

You might also like