Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Page|1

C PROGRAMMING
Unit III – Decision Making,
Looping & Arrays

I BSC DA UNIT III - C NEETHU DS - SNGC


Page|2

Decision Making and Branching


Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C language handles
decision-making by supporting the following statements,

• if statement
• switch statement
• conditional operator statement (? : operator)
• goto statement

Decision making with if statement

The if statement may be implemented in different forms depending on the complexity of conditions
to be tested. The different forms are,

1. Simple if statement
2. if-else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)

Simple if statement

Simple if statement is used to verify the given condition and executes the block of statements based
on the condition result. The simple if statement evaluates specified condition. If it is TRUE, it
executes the next statement or block of statements. If the condition is FALSE, it skips the execution
of the next statement or block of statements. The general syntax and execution flow of the simple
if statement is as follows.

I BSC DA UNIT III - C NEETHU DS - SNGC


Page|3

EXAMPLE

#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}

Output :

x is greater than y

if-else statement

The if-else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is FALSE,
it executes another block of statements (False block). The general syntax and execution flow of
the if-else statement is as follows.

I BSC DA UNIT III - C NEETHU DS - SNGC


Page|4

#include <stdio.h> void


main( )
{
int x, y;
x = 15; y
= 18; if (x
>y)
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
Output :
y is greater than x

Nested if....else statement


The general form of a nested if...else statement is,

I BSC DA UNIT III - C NEETHU DS - SNGC


Page|5

if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
} } else {
statement block3;
}

if expression is false then statement-block3 will be executed, otherwise the execution continues
and enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed.

Example:

I BSC DA UNIT III - C NEETHU DS - SNGC


Page|6

#include <stdio.h> void


main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
} }
else if ladder
The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;

I BSC DA UNIT III - C NEETHU DS - SNGC


Page|7

The expression is tested from the top(of the ladder) downwards. As soon as a true condition is
found, the statement associated with it is executed.
Example :

#include <stdio.h> void


main( )
{
int a; printf("Enter a
number..."); scanf("%d",
&a); if(a%5 == 0 && a%8
== 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{ printf("Divisible by
8");
}
else if(a%5 == 0)
{ printf("Divisible by
5");
}
else
{ printf("Divisible by
none");
}
}

I BSC DA UNIT III - C NEETHU DS - SNGC


Page|8

'switch' statement in C

Switch statement in C tests the value of a variable and compares it with multiple cases. Once the
case match is found, a block of statements associated with that particular case is executed.

Each case in a block of a switch has a different name/number which is referred to as an identifier.
The value provided by the user is compared with all the cases inside the switch block until the
match is found.

If a case match is NOT found, then the default statement is executed, and the control goes out of
the switch block.

A general syntax of how switch-case is implemented in a 'C' program is as follows:


switch( eexpression
)
{
case value-1:
Block-1;
Break;
case value-2:
Block-2;
Break;
case value-n:
Block-n;
Break;
default:
Block-1;
Break;
}
Statement-x;
Rules for switch statement in C language

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

I BSC DA UNIT III - C NEETHU DS - SNGC


Page|9

4) The break statement in switch case is not must. It is optional. If there is no break
statement found in the case, all the cases will be executed present after the matched case. It is
known as fall through the state of C switch statement.

Example

I BSC DA UNIT III - C NEETHU DS - SNGC


P a g e | 10

#include <stdio.h>

int main () {

/* local variable definition */


char grade = 'B';

switch(grade) { case 'A'


: printf("Excellent!\n"
);
break; case 'B' :
case 'C' : printf("Well
done\n" );
break; case 'D' :
printf("You passed\n" );
break; case 'F' :
printf("Better try again\n" );
break; default :
printf("Invalid grade\n" );

printf("Your grade is %c\n", grade );

return 0; }
When the above code is compiled and executed, it produces the following result −

Well done
Your grade is B

Jumping Out of Loops


While executing any loop, it becomes necessary to skip a part of the loop or to leave the loop as
soon as certain condition becomes true, that is called jumping out of loop. C language allows
jumping from one statement to another within a loop as well as jumping out of the loop.
There Are two keyword in C language to Jumping Out, or Breack Loop.
• break statement
• continue statement

I BSC DA UNIT III - C NEETHU DS - SNGC


P a g e | 11

break statement
When break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.

Example of break statement

#include<stdio.h>
void main()
{
int a=1;
while(a<=10)
{

I BSC DA UNIT III - C NEETHU DS - SNGC


P a g e | 12

if(a==5)
break;
printf("\nStatement %d.",a);
a++;
}
printf("\nEnd of Program.");
}
Output :
Statement 1.
Statement 2.
Statement 3.
Statement 4.
End of Program.

continue statement
It causes the control to go directly to the test-condition and then continue the loop process. On
encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.

#include<stdio.h>

void main()
{
int a=0;
P a g e | 13

while(a<10)
{
a++;
if(a==5)
continue;

printf("\nStatement %d.",a);

}
printf("\nEnd of Program.");
}
Output :

Statement 1.
Statement 2.
Statemnet 3.
Statement 4.
Statement 6.
Statement 7.
Statement 8.
Statement 9.
Statement 10.
End of Program.

goto statement
The goto statement is a jump statement which jumps from one point to another point within a
function.
Syntax of goto statement

goto label;
----------

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 14

----------
label:
----------
----------

In the above syntax, label is an identifier. When, the control of program reaches to goto
statement, the control of the program will jump to the label: and executes the code after it.
Example of goto statement
#include<stdio.h>
void main()
{
printf("\nStatement 1.");
printf("\nStatement 2.");
printf("\nStatement 3.");
Output :
goto last;
printf("\nStatement 4.");
Statement 1.
printf("\nStatement 5."); Statement 2.

last: Statement3.

printf("\nEnd of Program."); End of Program.


}

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 15

Loops
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do a
task tens of thousands of times.
A loop statement allows us to execute a statement or group of statements multiple times. Given
below is the general form of a loop statement in most of the programming languages while loop
A while loop in C programming repeatedly executes a target statement as long as a given
condition is true.
Syntax
The syntax of a while loop in C programming language is −

while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following
the loop.
Flow Diagram

Example :

int a = 1;

while( a< 5 )

printf(a);

a = a+1;}

Output :

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 16

1 2 3 4

do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while
loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least
one time.
Syntax
The syntax of a do...while loop in C programming language is −

do {
statement(s);
}
while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
executes again. This process repeats until the given condition becomes false.
Flow Diagram

int a = 1;

do {

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 5 )

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 17

Output :
1 2 3 4

for loop in C
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is −

for ( init; condition; increment )


{
statement(s);
}

Here is the flow of control in a 'for' loop −


• The init step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop does not execute and the flow of control jumps to the next statement
just after the 'for' loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the condition.
• The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the 'for' loop terminates.

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 18

Flow Diagram

Example :

int a;
for( a = 1; a < 5; a + + )

printf("value of a: %d\n", a);

Output :

1234

Array
In C language, arrays are reffered to as structured data types. An array is defined as finite ordered
collection of homogenous data, stored in contiguous memory locations.
Here the words,
• finite means data range must be defined.
• ordered means data must be stored in continuous memory addresses.
• homogenous means data must be of similar data type.

C programming language provides a concept called "Array".

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 19

An array is a special type of variable used to store multiple values of same data type at a
time.
An array can also be defined as follows...
An array is a collection of similar data items stored in continuous memory locations
with single name.
Example where arrays are used,
• to store list of Employee or Student names,
• to store marks of students,
• or to store list of numbers or characters etc.

In c programming language, arrays are classified into two types. They are as follows...
1. Single Dimensional Array / One Dimensional Array
2. Multi Dimensional Array

Single Dimensional Array


In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array, data is stored in linear form. Single dimensional arrays are also called as
onedimensional arrays, Linear Arrays or simply 1-D Arrays.
Array Declaration
Like any other variable, arrays must be declared before they are used. General form of array
declaration is, Syntax:

data-type variable-name[size];

Example:
int arr[10];

Here int is the data type, arr is the name of the array and 10 is the size of array.
It means array arr can only contain 10 elements of int type.

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 20

Index of an array starts from 0 to size-1 For Example, first element of arr array will be stored at
arr[0] address and last element will occupy arr[9]. Graphical representation of above example is
given below

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75; Example:
#include<stdio.h>
#include<conio.h> void main()
{
int i;
int arr[]={2, 3, 4}; //Compile time array initialization
for(i=0; i<3; i++)
{
printf("%d ",arr[i]);
}
getch();
}
Output:
Command Prompt
234

Multi Dimensional Array

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 21

An array of arrays is called as multi dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi dimensional array. Multi dimensional array can
be of two dimensional array or three dimensional array or four dimensional array or more...
Most popular and commonly used multi dimensional array is two dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create mathematical
matrices.
Declaration of Two Dimensional Array
We use the following general syntax for declaring a two dimensional array...

datatype arrayName [ rowSize ] [ columnSize ] ;

Example :
int a[3][4];
Initializing Two-Dimensional Arrays
Multidimensional arrays may
be initialized by specifying
bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example −
int val = a[2][3];

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 22

Example :
#include <stdio.h>
int main () {
/* an array with 5 rows and 2 columns*/ int
a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int
i, j;
/* output each array element's value
*/ for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}

Output :
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

String and Character Array


String is a sequence of characters that is treated as a single data item and terminated by null
character '\0'. Remember that C language does not support strings as a data type. A string is
actually one-dimensional array of characters in C language.
C Programming – Unit III I B.Sc DA NEETHU DS -SNGC
P a g e | 23

The following declaration and initialization create a string consisting of the word "Hello". To hold
the null character at the end of the array, the size of the character array containing the string is one
more than the number of characters in the word "Hello." char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
the above mentioned string −

Example :
#include <stdio.h>
int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting
message: %s\n", greeting ); return 0;
}

When the above code is compiled and executed, it produces the following result −
Greeting message: Hello

C supports a wide range of functions that manipulate null-terminated strings −


Sr.No. Function & Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 24

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

Example
#include <stdio.h>

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC


P a g e | 25

#include <string.h>

int main () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */ strcpy(str3,


str1); printf("strcpy( str3, str1) : %s\n",
str3 );

/* concatenates str1 and str2 */ strcat(


str1, str2); printf("strcat( str1, str2):
%s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1); printf("strlen(str1) :
%d\n", len );

return 0;
}

When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10

*******************END************************

C Programming – Unit III I B.Sc DA NEETHU DS -SNGC

You might also like