सी, पायथन, जावास्क्रिप्ट, गो, रस्ट, सॉलिडिटी जैसी भाषाओं और कंप्यूटर साइंस के बुनियादी और गणित के उन्नत सिद्धांतों को हिंदी में पढ़ने के लिए संपर्क करें। हम वेबसाइट और सॉफ्टवेयर भी बनाते हैं।
# 3 Decision Control and Looping Statements | हमारा मोर्चा
programmers
# 3 Decision Control and Looping Statements
4
3 Decision Control and Looping Statements
Takeaways
Decision control statements
for, while, do-while loops
Conditional branching statements
Nested loops
Iterative statements
break, continue, and goto statements
3.1 INTRODUCTION TO DECISION CONTROL STATEMENTS
Till now we know that the code in a C program is executed sequentially from the first line of the program to its last line, i.e., the second statement is executed after the first, the third statement is executed after the second, and so on.
Although this is true, but in some cases we want only selected statements to be executed. Such type of conditional processing extends the usefulness of programs. It allows the programmers to build programs that determine which statements of the code should be executed and which should be ignored.
C supports two types of decision control statements that can alter the flow of a sequence of instructions. These include conditional type branching and unconditional type branching. Figure 3.1 shows the categorization of decision control statements in C language.
Selection/branching statement
|
+------------+-------------+
| |
Conditional type Unconditional type
|
+-----+--------+------------+----------+
| | | |
if if-else if-else-if switch
Figure 3.1 Decision control statements
3.2 CONDITIONAL BRANCHING STATEMENTS
The conditional branching statements help to jump from one part of the program to another depending on whether a particular condition is satisfied or not. These decision control statements include:
if statement
if-else statement
if–else–if statement
switch statement
3.2.1 If Statement
The if statement is the simplest form of decision control statements that is frequently used in decision making. The general form of a simple if statement is shown in Figure 3.2.
The if block may include one statement or n statements enclosed within curly brackets. First the test expression is evaluated. If the test expression is true, the statement of block (statement to ) are executed otherwise these statements will be skipped and the execution will jump to statement x.
if
1
n
SYNTAX OF if STATEMENT
if (test expression)
{
statement 1;
..........
statement n;
}
statement x;
|
v
/-----------\
/ Test \
< Expression >------ FALSE ------+
\ / |
\-----------/ |
| TRUE |
v |
+--------------------+ |
| Statement Block 1 | |
+--------------------+ |
| |
+<----------------------------+
|
v
+--------------------+
| Statement x |
+--------------------+
Figure 3.2 if statement construct
The statement in an if block is any valid C language statement and the test expression is any valid C language expression that may include logical operators. Note that there is no semicolon after the test expression. This is because the condition and statement should be put together as a single statement.
Programming Tip: Properly indent the statements that are dependent on the previous statements.
#include <stdio.h>
int main()
{
int x=10; // Initialize the value of x
if ( x>0) // Test the value of x
x++; // Increment x if it is > 0
printf("\n x = %d", x);
// Print the value of x
return 0;
}
Output
x = 11
In the above code, we take a variable x and initialize it to 10. In the test expression we check if the value of x is greater than 0. If the test expression evaluates to true then the value of x is incremented and is printed on the screen. The output of this program is
x = 11
Observe that the printf statement will be executed even if the test expression is false.
Write a program to determine whether a person is eligible to vote.
#include <stdio.h>
int main()
{
int age;
printf("\n Enter the age: ");
scanf("%d", &age);
if(age >= 18)
printf("\n You are eligible to vote");
return 0;
}
Output
Enter the age: 28
You are eligible to vote
Note: In case the statement block contains only one statement, putting curly brackets becomes optional. If there is more than 1 statement in the statement block, putting curly brackets becomes mandatory.
Write a program to determine the character entered by the user.
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
printf("\n Press any key: ");
scanf("%c", &ch);
if(isalpha(ch)>0)
printf("\n The user has entered a character");
if(isdigit(ch)>0)
printf("\n The user has entered a digit");
if(isprint(ch)>0)
printf("\n The user has entered a printable character");
if(ispunct(ch)>0)
printf("\n The user has entered a punctuation mark");
if(isspace(ch)>0)
printf("\n The user has entered a white space character");
return 0;
}
Output
Press any key: 3
The user has entered a digit
Now let us write a program to detect errors during data input. But before doing this we must remember that when the scanf() function completes its action, it returns the number of items that are successfully read. We can use this returned value to test if any error has occurred during data input. For example, consider the following function:
scanf("%d %f %c", &a, &b, &c);
If the user enters:
1 1.2 A
then the scanf() function will return 3, since three values have been successfully read. But had the user entered,
1 abc A
then the scanf() function will immediately terminate when it encounters abc as it was expecting a floating point value and print an error message. So after understanding this concept, let us write a program code to detect an error in data input.
#include <stdio.h>
main()
{
int num;
char ch;
printf("\n Enter an int and a char value: ");
// Check the return value of scanf()
if (scanf("%d %c", &num, &ch)==2)
printf("\n Data read successfully");
else
printf("\n Error in data input");
}
Output
Enter an int and a char value: 2 A
Data read successfully
3.2.2 if–else Statement
We have studied that the if statement plays a vital role in conditional branching. Its usage is very simple, the test expression is evaluated, if the result is true, the statement(s) followed by the expression is executed else if the expression is false, the statement is skipped by the compiler. But what if you want a separate set of statements to be executed if the expression returns a zero value? In such cases we use an if-else statement rather than using simple if statement. The general form of a simple if-else statement is shown in Figure 3.3.
Programming Tip: Align the matching if-else clauses vertically.
In the syntax shown, we have one written statement block. A statement block may include one or more statements. According to the if-else construct, first the test expression is evaluated. If the expression is true, statement block 1 is executed and statement block 2 is skipped. Otherwise, if the expression is false, statement block 2 is executed and statement block 1 is ignored. Now in any case after the statement block 1 or 2 gets executed the control will pass to statement x. Therefore, statement x is executed in every case.
SYNTAX OF if-else STATEMENT
if (test expression)
{
statement block 1;
}
else
{
statement block 2;
}
statement x;
|
v
/-------------\
/ Test \
< Expression > -- FALSE --+
\ / |
\-------------/ |
| TRUE |
v v
+------------------+ +------------------+
| Statement Block 1| | Statement Block 2|
+------------------+ +------------------+
| |
+---------+----------+
|
v
+-------------+
| Statement x |
+-------------+
Figure 3.3 if-else statement construct
Write a program to find whether the given number is even or odd.
#include <stdio.h>
int main()
{
int num;
printf("\n Enter any number: ");
scanf("%d",&num);
if(num%2 == 0)
printf("\n %d is an even number", num);
else
printf("\n %d is an odd number", num);
return 0;
}
Output
Enter any number: 11
11 is an odd number
Write a program to enter any character. If the entered character is in lower case then convert it into upper case and if it is a lower case character then convert it into upper case.
#include <stdio.h>
int main()
{
char ch;
printf("\n Enter any character: ");
scanf("%c", &ch);
if(ch >='A' && ch<='Z')
printf("\n The entered character was
in upper case. In lower case it is:
%c", (ch+32));
else
printf("\n The entered character was
in lower case. In upper case it is:
%c", (ch-32));
return 0;
}
Output
Enter any character: a
The entered character was in lower case. In
upper case it is: A
Write a program to enter a character and then determine whether it is a vowel or not.
#include <stdio.h>
int main()
{
char ch;
printf("\n Enter any character: ");
scanf("%c", &ch);
if(ch =='a' ||ch =='e' ||ch=='i' ||ch=='o'
||ch=='u' || ch=='A' ||ch=='E'
||ch=='I' ||ch=='O' ||ch=='U' )
printf("\n %c is a VOWEL", ch);
else
printf("\n %c is not a vowel", ch);
return 0;
}
Output
Enter any character: v
v is not a vowel
Write a program to find whether a given year is a leap year or not.
#include <stdio.h>
int main()
{
int year;
printf("\n Enter any year: ");
scanf("%d",&year);
if((year%4 == 0) && ((year%100 !=0) ||
(year%400 == 0)))
printf("\n Leap Year");
else
printf("\n Not A Leap Year");
return 0;
}
Output
Enter any year: 1996
Leap Year
Pitfall A very common pitfall while using if statements is to use assignment operator (=) instead of comparison operator (==). For example, consider the statement
if(a = 10)
printf("%d", a);
Here, the statement does not test whether a is equal to 10 or not. Rather the value 10 is assigned to a and then the value is returned to the if construct for testing. Since the value of a is non-zero, the if construct returns a 1.
Programming Tip: Do not use floating point numbers for checking for equality in the test expression.
The compiler cannot detect such kinds of errors and thus the programmer should carefully use the operators. The program code given below shows the outcome of mishandling the assignment and the comparison operators.
#include <stdio.h>
main()
{
int x = 2, y = 3;
if(x = y)
printf("\n EQUAL");
else
printf("\n NOT EQUAL");
}
Output
EQUAL
#include <stdio.h>
main()
{
int x = 2, y = 3;
if(x == y)
printf("\n EQUAL");
else
printf("\n NOT EQUAL");
}
Output
NOT EQUAL
3.2.3 if–else–if Statement
C language supports if-else-if statements to test additional conditions apart from the initial test expression.
The if-else-if construct works in the same way as a normal if statement. If-else-if construct is also known as nested if construct. Its construct is given in Figure 3.4.
Programming Tip: Braces must be placed on separate lines so that the block of statements can be easily identified.
It is not necessary that every if statement should have an else block as C supports simple if statements. After the first test expression or the first if branch, the programmer can have as many else-if branches as he wants depending on the expressions that have to be tested. For example, the following code tests whether a number entered by the user is negative, positive, or equal to zero.
Write a program to demonstrate the use of nested if structure.
#include <stdio.h>
int main()
{
int x, y;
printf("\n Enter two numbers: ");
scanf("%d %d", &x, &y);
if(x == y)
printf("\n The two numbers are equal");
else if(x > y)
printf("\n %d is greater than %d", x, y);
else
printf("\n %d is smaller than %d", x, y);
return 0;
}
Output
Enter two numbers: 12 23
12 is smaller than 23
SYNTAX OF if-else-if STATEMENT
if ( test expression 1)
{
statement block 1;
}
else if ( test expression 2)
{
statement block 2;
}
..................
else
{
statement block x;
}
Statement y;
|
v
/-------------\
/ Test \
< Expression 1 >----- FALSE -----+
\ / |
\-------------/ |
| TRUE |
v v
+------------------+ /-------------\
| Statement Block 1| / Test \
+------------------+ < Expression 2 >- - - FALSE - - -+
| \ / |
| \-------------/ |
| | TRUE |
| v v
| +------------------+ +------------------+
| | Statement Block 2| | Statement Block x|
| +------------------+ +------------------+
| | |
+--------------------------+--------------------------+
|
v
+-------------+
| Statement y |
+-------------+