C Programming
C Programming
C PROGRAMMING
Unit III – Decision Making,
Looping & Arrays
• if statement
• switch statement
• conditional operator statement (? : operator)
• goto 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.
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.
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:
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 :
'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.
3) The case value can be used only inside the switch statement.
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
#include <stdio.h>
int main () {
return 0; }
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
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.
#include<stdio.h>
void main()
{
int a=1;
while(a<=10)
{
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;
----------
----------
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.
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 :
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 {
a = a + 1;
}while( a < 5 )
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 −
Flow Diagram
Example :
int a;
for( a = 1; a < 5; 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.
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
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.
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
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...
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];
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
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
1 strcpy(s1, s2);
Copies string s2 into string s1.
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>
#include <string.h>
int main () {
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************************