(Conditional Branching and Loops, Arrays, Strings)
UNIT – II
Conditional Branching and Loops: Writing and Evaluation of
Conditionals with If, If-Else, else-if ladder Switch-Case, goto,
Iteration with For, While, Do While Loops
Arrays: One-Two-Dimensional Arrays, Creating, Accessing and
Manipulating Elements of Arrays.
Strings: Introduction To Strings, Handling Strings as Array of
Characters, Basic String Functions available in C (Strlen, Strcat,
Strcpy, Strstr Etc.), Arrays of Strings.
1
Conditional Statements
• Conditional Statements/Decision-making statements are the
statements that are used to verify a given condition and decide
whether a block of statements gets executed or not based on the
condition result.
• In the c programming language, there are two decision-making
statements they are as follows.
1. if statement
2. switch statement
Conditional Statements
if statement in C
if statement is used to make decisions based on a condition. The if
statement verifies the given condition and decides whether a block of
statements are executed or not based on the condition result.
In c, if statement is classified into four types as follows...
• Simple if statement
• if-else statement
• Nested if statement
• if-else-if statement (if-else ladder)
Simple if statement
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Simple if statement- Example
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 10;
if (i > 15)
{
printf("10 is less than 15");
}
printf("I am Not in if");
}
If-else statement
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
If-else statement-Example
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 20;
if (i < 15)
printf("i is smaller than 15");
else
printf("i is greater than 15");
return 0;
}
Nested if-else statement
Syntax:
if( condition 1 )
{
if(condition 2 )
{
statement 1;
}
else
{
statement 2;
}
}
else
{
statement 3;
}
Nested if-else statement-Example
#include <stdio.h>
void main( ) else
{ {
int a, b, c; if(b > c)
printf("Enter 3 numbers..."); {
scanf("%d%d%d",&a, &b, &c); printf("b is the greatest");
if(a > b) }
{ else
if(a > c) {
{ printf("c is the greatest");
printf("a is the greatest"); }
} }
else }
{
printf("c is the greatest");
}
}
if-else-if ladder statement
Syntax:
if(Condition 1)
{
statement block1;
}
else if(Condition 2)
{
statement block2;
}
else if(Condition 3 )
{
statement block3;
}
….
else
default statement;
if-else-if ladder statement-Example
#include <stdio.h>
void main( )
{
else if(a%5 == 0)
int a;
{
printf("Enter a number...");
printf("Divisible by 5");
scanf("%d", &a);
}
if(a%5 == 0 && a%8 == 0)
else
{
{
printf("Divisible by both 5 and 8");
printf("Divisible by none");
}
}
else if(a%8 == 0)
}
{
printf("Divisible by 8");
}
Switch Statement
• Switch statement is a control statement that allows us to choose
only one choice among the many given choices.
• The expression in switch evaluates is compared to the values
present in different cases.
• It executes that block of code which matches the case value.
• If there is no match, then default block is executed(if present).
Switch Statement
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
Switch Statement Rules
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.
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.
Switch Statement Example
#include <stdio.h>
int main() case '*':
{ printf("%d * %d = %d",n1, n2, n1*n2);
char operator; break;
int n1, n2; case '/':
printf("Enter an operator (+, -, *, /): "); printf("%d / %d = %d",n1, n2, n1/n2);
scanf("%c", &operator); break;
printf("Enter two operands: "); default:
scanf("%d %d",&n1, &n2); printf("Error! operator is not correct");
switch(operator) }
{ return 0;
case '+': }
printf("%d + %d = %d",n1, n2, n1+n2);
break;
case '-':
printf("%d - %d = %d",n1, n2, n1-n2);
break;
Iterative Statements/ Loops
A loop is used to repeat a block of code until the specified condition
is met. Using loops we do not need to write the same code again and
again.
C programming has three types of loops:
• while loop
• do...while loop
• for loop
These loops controlled either at entry level or at exit level hence
loops can be controlled two ways:
1.Entry Controlled Loop
2.Exit Controlled Loop
Iterative Statements/ Loops
Entry Controlled Loop
Loop, where test condition is checked before entering the loop body,
known as Entry Controlled Loop. Example: while loop, for loop
Exit Controlled Loop
Loop, where test condition is checked after executing the loop body,
known as Exit Controlled Loop. Example: do while loop
While Loop
• The while loop is addressed as entry controlled loop/ pretest loop.
• The while loop evaluates the test expression inside the parenthesis
().
• If the test expression is true, statements inside the body of while
loop are executed. Then, the test expression is evaluated again.
• The process goes on until the test expression is evaluated to false.
• If the test expression is false, the loop terminates (ends).
While Loop
Syntax:
while (testExpression)
{
// body of the loop
}
While Loop-Example
// Print numbers from 1 to 5
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
do-while Loop
• The do...while loop is addressed as exit controlled loop/ post test
loop
• The body of do...while loop is executed at least once. Only then,
the test expression is evaluated.
• If the test expression is true, the body of the loop is executed again
and the test expression is evaluated.
• This process goes on until the test expression becomes false.
• If the test expression is false, the loop ends.
do-while Loop
Syntax:
do
{
//body of the loop
}
while (testExpression);
do-while Loop-Example
#include<stdio.h>
void main()
{
int i;
i = 1;
do
{
printf("%d\t", i);
i++;
} while(i <= 5);
}
for Loop
Syntax:
for (initializationStatement; testExpression; updateStatement)
{
// body of loop
}
for Loop
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is
evaluated to false, the for loop is terminated.
• However, if the test expression is evaluated to true, statements
inside the body of for loop are executed, and the update expression
is updated.
• Again the test expression is evaluated.
• This process goes on until the test expression is false. When the
test expression is false, the loop terminates.
for Loop-Example
#include <stdio.h>
int main() {
int i;
for (i = 1; i < =5; ++i)
{
printf("%d ", i);
}
return 0;
}
Break statement
The break statement ends the loop immediately when it is
encountered.
Syntax:
break;
The break statement is almost always used with if...else statement
inside the loop.
Break statement
Break statement- Example
// Program to calculate the sum of a maximum of 10 numbers
// If a negative number is entered, the loop terminates
# include <stdio.h>
void main()
{
int i;
int number, sum = 0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%d",&number);
if(number < 0)
break;
sum += number;
}
printf("Sum = %d,sum);
}
continue statement
The continue statement skips the current iteration of the loop and
continues with the next iteration.
Syntax:
continue;
The continue statement is almost always used with the if...else
statement.
continue statement
continue statement- Example
// Program to calculate the sum of a maximum of 10 numbers
// Negative numbers are skipped from the calculation
# include <stdio.h>
int main()
{
int i, number, sum = 0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%d",&number);
if(number < 0)
continue;
sum += number;
}
printf("Sum = %d",sum);
}
goto statement
The goto statement is known as jump statement in C.
The goto statement allows us to transfer control of the program to the
specified label.
Syntax :
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the goto statement is encountered, the
control of the program jumps to label: and starts executing the code.
goto statement- Example
//Program to display multiplication table
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
return 0;
}
“Arrays and Strings”
36
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.
Properties of Array
• Each element of an array is of same data type and carries the same
size, i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory locations
where the first element is stored at the smallest memory location.
• Elements of the array can be randomly accessed using base address
and the size of the data element.
Types of Arrays
1-D Array Declaration
An array which has only one subscript is known as one dimensional
array. Arrays must be declared before they are used. General form of
array declaration is,
data_type array_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 i.e first element of arr array
will be stored at arr[0] address and the last element will occupy
arr[9].
1-D Array Initialization
It is possible to initialize an array during declaration.
Syntax: datatype array_name[size] = { val1, val2, val3, ..... valN };
Example:
int mark[5] = {19, 10, 8, 17, 9};
You can also initialize an array like this:
int mark[] = {19, 10, 8, 17, 9};
Here, we haven't specified the size. However, the compiler knows its
size is 5 as we are initializing it with 5 elements.
Accessing 1-D Arrays
Elements of an array can be accessed by indices.
The first element is mark[0], the second element is mark[1] and so on.
Few keynotes:
• Arrays have 0 as the first index, not 1. In this example, mark[0] is
the first element.
• If the size of an array is n, to access the last element, the n-1 index
is used. In this example, mark[4]
• Suppose the starting address of mark[0] is 2120. Then, the address
of the mark[1] will be 2124. Similarly, the address of mark[2] will
be 2128 and so on.
• This is because the size of a float is 4 bytes.
1-D Arrays-Example
// Program to find the average of n numbers using arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
printf("Average = %d", sum/n);
return 0;
}
2-D Arrays
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.
Two-dimensional arrays are declared as
data-type array-name[row-size][column-size];
Example: int a[3][4];
2-D Arrays- Initialization
// Different ways to initialize two-dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
Addition of two Matrices
#include <stdio.h>
int main()
{ for (int i = 0; i < 2; ++i)
float a[2][2], b[2][2], result[2][2]; for (int j = 0; j < 2; ++j)
{
printf("Enter elements of 1st matrix\n");
result[i][j] = a[i][j] + b[i][j];
for (int i = 0; i < 2; ++i) }
for (int j = 0; j < 2; ++j) printf("\nSum Of Matrix:");
{ for (int i = 0; i < 2; ++i)
printf("Enter a%d%d: ", i + 1, j + 1); for (int j = 0; j < 2; ++j)
scanf("%f", &a[i][j]); {
} printf("%.1f\t", result[i][j]);
printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i) if (j == 1)
printf("\n");
for (int j = 0; j < 2; ++j)
}
{ return 0;
printf("Enter b%d%d: ", i + 1, j + 1); }
scanf("%f", &b[i][j]);
}
Strings
String is a sequence of characters that is treated as a single data item
and terminated by null character '\0’.
A string is actually one-dimensional array of characters in C language.
For example: The string "hello world" contains 12 characters
including '\0' character which is automatically added by the compiler
at the end of the string.
char str[10];
Strings-Declaring and Initializing
There are different ways to initialize a character array variable.
char name[6] = “MRECW"; // valid character array initialization
char name[10] = {'L','e','s','s','o','n','s','\0'}; // valid initialization
Remember that when you initialize a character array by listing all of
its characters separately then you must supply the '\0' character
explicitly.
Some examples of illegal initialization of character array are,
char ch[3] = "hell"; // Illegal
char str[4];
str = "hell"; // Illegal
Strings-Example Program
#include<stdio.h>
#include <string.h>
int main()
{
char name[50];
printf("Enter your name: ");
gets(name); // scanf(“%s”,name);
printf("Your name is: ");
puts(name); // printf(“%s”,name);
return 0;
}
String Handling Functions
C supports a large number of string handling functions in the standard
library "string.h".
Few commonly used string handling functions are :
Function Work of Function
strlen() computes string's length
strcpy() copies a string to another
strcat() concatenates(joins) two strings
strcmp() compares two strings
strlwr() converts string to lowercase
strupr() converts string to uppercase
Strlen() Example
The strlen() function takes a string as an argument and returns its
length.
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
printf("Length of string a = %ld \n",strlen(a));
printf("Length of string b = %ld \n",strlen(b));
return 0;
}
Output:
Length of string a = 7
Length of string b = 7
Strcpy() Example
The strcpy() function copies the string pointed by source to the
destination. The strcpy() function also returns the copied string.
Syntax: strcpy(destination, source);
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50], s2[50];
strcpy(s1, "Engineering");
strcpy(s2, s1);
printf("%s\n", s2);
return 0;
}
Output: Engineering
Strcat() Example
The strcat(first_string, second_string) function concatenates two
strings and result is returned to first_string.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100] = "This is ", str2[] = "Womens College";
strcat(str1, str2);
puts(str1);
puts(str2);
return 0;
}
Output:
This is Womens College
Womens College
Strcmp()
The strcmp() function takes two strings and returns an integer.
The strcmp() compares two strings character by character.
If the first character of two strings is equal, the next character of two
strings are compared. This continues until the corresponding
characters of two strings are different or a null character '\0' is
reached.
Return Value Remarks
0 if both strings are identical (equal)
if the ASCII value of the first unmatched
negative
character is less than second.
positive if the ASCII value of the first unmatched
integer character is greater than second.
Strcmp() Example
The strcmp(first_string, second_string) function compares two string and
returns 0 if both strings are equal.
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Strlwr() Example
The strlwr(string) function returns string characters in lowercase.
Example:
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
Output:
Enter string: MALLAreddy
String is: MALLAreddy
Lower String is: mallareddy
Strupr() Example
The strupr(string) function returns string characters in uppercase.
Example:
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Output:
Enter string: mallareddy
String is: mallareddy
Upper String is: MALLAREDDY
Strrev() Example
The strrev(string) function returns reverse of the given string.
Example:
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
Enter string: destiny
String is: destiny
Reverse String is: ynitsed