सी, पायथन, जावास्क्रिप्ट, गो, रस्ट, सॉलिडिटी जैसी भाषाओं और कंप्यूटर साइंस के बुनियादी और गणित के उन्नत सिद्धांतों को हिंदी में पढ़ने के लिए संपर्क करें। हम वेबसाइट और सॉफ्टवेयर भी बनाते हैं।
Decision Control and Looping Statements-Part ii | हमारा मोर्चा
programmers
Decision Control and Looping Statements-Part ii
5
for Loop (जारी)
Note that every section of the for loop is separated from the other with a semicolon. It is possible that one of the sections may be empty, though the semicolons still have to be there. However, if the condition is empty, it is evaluated as true and the loop will repeat until something else stops it.
The for loop is widely used to execute a single or a group of statements a limited number of times. Another point to consider is that in a for loop, condition is tested before the statements contained in the body are executed. So if the condition does not hold true, then the body of the for loop is not executed.
Look at the following code which prints the first n numbers using a for loop.
#include <stdio.h>
int main()
{
int i, n;
printf("\n Enter the value of n :");
scanf("%d", &n);
for(i=1;i<=n;i++)
printf("\n %d", i);
return 0;
}
Programming Tip: It is a logical error to update the loop control variable in the body of the for loop as well as in the for statement.
In the code, i is the loop variable. Initially, it is initialized with value 1. Suppose the user enters 10 as the value for n. Then the condition is checked, since the condition is true as i is less than n, the statement in the for loop is executed and the value of i is printed. After every iteration, the value of i is incremented. When i=n, the control jumps to the return 0 statement.
Points to Remember About for Loop
In a for loop, any or all the expressions can be omitted. In case all the expressions are omitted, then there must be two semicolons in the for statement.
There must be no semicolon after a for statement. If you do that, then you are sure to get some unexpected results. Consider the following code.
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++);
printf(" %d", i);
return 0;
}
In this code, the loop initializes to 0 and increments its value. Since a semicolon is placed after the loop, it means that loop does not contain any statement. So even if the condition is true, no statement is executed. The loop continues till becomes 10 and the moment , the statement following the loop is executed and the value of (10) is printed on the screen.
i
i
i=10
for
i
When we place a semicolon after the for statement, then the compiler will not generate any error message. Rather it will treat the statement as a null statement. Usually such type of null statement is used to generate time delays. For example, the following code produces no output and simply delays further processing.
#include <stdio.h>
int main()
{
int i;
for(i=10000;i>0;i--);
printf(" %d", i);
return 0;
}
Multiple initializations must be separated with a comma operator as shown in the following code segment.
#include <stdio.h>
int main()
{
int i, sum;
for(i=0, sum=0;i<10;i++)
sum += i;
printf(" %d", sum);
return 0;
}
If there is no initialization to be done, then the initialization statement can be skipped by giving only a semicolon. This is shown in the following code.
Programming Tip: Although we can place the initialization, testing and updating the loop control variable outside the for loop, we must try to avoid it as much as possible.
#include <stdio.h>
int main()
{
int i=0;
for(;i<10;i++)
printf("%d", i);
return 0;
}
Multiple conditions in the test expression can be tested by using logical operators (&& or ||).
If the loop controlling variable is updated within the statement block, then the third part can be skipped. This is shown in the code given below.
#include <stdio.h>
int main()
{
int i=0;
for(;i<10;)
{
printf(" %d", i);
i = i + 1;
}
return 0;
}
Multiple statements can be included in the third part of the for statement by using the comma operator. For example, the for statement given below is valid in C.
for(i=0, j=10;i<j; i++, j--)
The controlling variable can also be incremented/decremented by values other than 1. This is shown in the code below which prints all odd numbers from 0 to 10.
#include <stdio.h>
int main()
{
int i;
for(i=1;i<=10;i+=2)
printf(" %d", i);
return 0;
}
If the for loop contains nothing but two semicolons, that is no initialization, condition testing, and updating of the loop control variable then the for loop may become an infinite loop if no stopping condition is specified in the body of the loop. For example, the following code will infinitely print C Programming on the computer screen.
Programming Tip: Although placing an arithmetic expression in initialization and updating section of the for loop is permissible, try to avoid them as they may cause some round-off and/or truncation errors.
#include <stdio.h>
int main()
{
for(;;)
printf(" C Programming");
return 0;
}
Never use a floating point variable as the loop control variable. This is because floating point values are just approximations and therefore may result in imprecise values and thus inaccurate test for termination. For example, the following code will result in an infinite loop because of inaccuracies of floating point numbers.
#include <stdio.h>
int main()
{
float i;
for(i=100;i>=10;)
{
printf(" %f", i);
i = (float)i/10;
}
return 0;
}
Selecting an appropriate loop Loops can be entry-controlled (also known as pre-test) or exit-controlled (also known as post-test). While in an entry-controlled loop, condition is tested before the loop starts, an exit-controlled loop, on the other hand, tests the condition after the loop is executed. If the condition is not met in entry-controlled loop, then the loop will never execute. However, in case of post-test, the body of the loop is executed unconditionally for the first time.
If your requirement is to have a pre-test loop, then choose either for loop or while loop. In case you need to have a post-test loop then choose a do-while loop.
Look at Table 3.2 which shows a comparison between a pre-test loop and a post-test loop.
Table 3.2 Comparison of pre-test and post-test loops
Feature
Pre-test loop
Post-test loop
Initialization
1
1
Number of tests
N+1
N
Statements executed
N
N
Loop control variable update
N
N
Minimum iterations
0
1
When we know in advance the number of times the loop should be executed, we use a counter-controlled loop. The counter is a variable that must be initialized, tested, and updated for performing the loop operations. Such a counter-controlled loop in which the counter is assigned a constant or a value is also known as a definite repetition loop.
When we do not know in advance the number of times the loop will be executed, we use a sentinel-controlled loop. In such a loop, a special value called the sentinel value is used to change the loop control expression from true to false. For example, when data is read from the user, the user may be notified that when they want the execution to stop, they may enter -1. This value is called a sentinel value. A sentinel-controlled loop is often useful for indefinite repetition loops.
If your requirement is to have a counter-controlled loop, then choose for loop, else if you need to have a sentinel-controlled loop, then go for either a while loop or a do-while loop. Although a sentinel-controlled loop can be implemented using for loop, while and do-while loops offer better option.
3.4 NESTED LOOPS
C allows its users to have nested loops, i.e., loops that can be placed inside other loops. Although this feature will work with any loop like while, do-while, and for, it is most commonly used with the for loop, because this is easiest to control. A for loop can be used to control the number of times that a particular set of statements will be executed. Another outer loop could be used to control the number of times that a whole loop is repeated.
In C, loops can be nested to any desired level. However, loops should be properly indented in order to enable the reader to easily determine which statements are contained within each for statement. To see the benefit of nesting loops, we will see some programs that exhibit the use of nested loops.
31. Write a program to print the following pattern.
#include <stdio.h>
int main()
{
int i, j;
for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=10;j++)
printf("*");
}
return 0;
}
33. Write a program to print the following pattern.
*
**
***
****
*****
#include <stdio.h>
int main()
{
int i, j;
for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
printf("*");
}
return 0;
}
34. Write a program to print the following pattern.
1
12
123
1234
12345
#include <stdio.h>
int main()
{
int i, j;
for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
printf("%d", j);
}
return 0;
}
35. Write a program to print the following pattern.
1
22
333
4444
55555
#include <stdio.h>
int main()
{
int i, j;
for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
printf("%d", i);
}
return 0;
}
36. Write a program to print the following pattern.
0
12
345
6789
#include <stdio.h>
int main()
{
int i, j, count=0;
for(i=1;i<=4;i++)
{
printf("\n");
for(j=1;j<=i;j++)
printf("%d", count++);
}
return 0;
}
37. Write a program to print the following pattern.
A
AB
ABC
ABCD
ABCDE
ABCDEF
#include <stdio.h>
int main()
{
char i, j;
for(i=65;i<=70;i++)
{
printf("\n");
for(j=65;j<=i;j++)
printf("%c", j);
}
return 0;
}
38. Write a program to print the following pattern.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include <stdio.h>
#define N 5
int main()
{
int i, j, k;
for(i=1;i<=N;i++)
{
for(k=N;k>=i;k--)
printf(" ");
for(j=1;j<=i;j++)
printf("%d", j);
printf("\n");
}
return 0;
}
39. Write a program to print the following pattern.
1
121
12321
1234321
123454321
#include <stdio.h>
#define N 5
int main()
{
int i, j, k, l;
for(i=1;i<=N;i++)
{
for(k=N;k>=i;k--)
printf(" ");
for(j=1;j<=i;j++)
printf("%d", j);
for(l=j-2;l>0;l--)
printf("%d", l);
printf("\n");
}
return 0;
}
40. Write a program to print the following pattern.
1
22
333
4444
55555
#include <stdio.h>
#define N 5
int main()
{
int i, j, k, count=5, c;
for(i=1;i<=N;i++)
{
for(k=1;k<=count;k++)
printf(" ");
for(j=1;j<=i;j++)
printf("%2d", i);
printf("\n");
c--;
}
return 0;
}
41. Write a program to print the multiplication table of n, where n is entered by the user.
#include <stdio.h>
int main()
{
int n, i;
printf("\n Enter any number: ");
scanf("%d", &n);
printf("\n Multiplication table of %d", n);
printf("\n ***************************");
for(i=0;i<=20;i++)
printf("\n %d X %d = %d", n, i, (n * i));
return 0;
}
Output
Enter any number: 2
Multiplication table of 2
***************************
2 X 0 = 0
2 X 1 = 2
....
2 X 20 = 40
42. Write a program using for loop to print all the numbers from m to n, thereby classifying them as even or odd
#include <stdio.h>
int main()
{
int i, m, n;
printf("\n Enter the value of m: ");
scanf("%d", &m);
printf("\n Enter the value n: ");
scanf("%d", &n);
for(i=m;i<=n;i++)
{
if(i%2 == 0)
printf("\n %d is even",i);
else
printf("\n %d is odd", i);
}
return 0;
}
Output
Enter the value of m: 5
Enter the value of n: 7
5 is odd
6 is even
7 is odd
43. Write a program using for loop to calculate the average of first n natural numbers.
#include <stdio.h>
int main()
{
int n, i, sum =0;
float avg = 0.0;
printf("\n Enter the value of n: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
sum = sum + i;
avg = (float) sum/n;
printf("\n The sum of first n natural numbers = %d", sum);
printf("\n The average of first n natural numbers = %.2f", avg);
return 0;
}
Output
Enter the value of n: 10
The sum of first n natural numbers = 55
The average of first n natural numbers = 5.50
44. Write a program using for loop to calculate factorial of a number.
#include <stdio.h>
int main()
{
int fact = 1, num;
printf("\n Enter the number: ");
scanf("%d",&num);
if(num == 0)
fact = 1;
else
{
for(int i=1; i<=num;i++)
fact = fact * i;
}
printf("\n Factorial of %d is: %d ", num, fact);
return 0;
}
Output
Enter the number: 5
Factorial of 5 is: 120
45. Write a program to classify a given number as prime or composite.
#include <stdio.h>
int main()
{
int flag = 0, i, num;
printf("\n Enter any number: ");
scanf("%d", &num);
for(i=2; i<num/2;i++)
{
if(num%i == 0)
{
flag =1;
break;
}
}
if(flag == 1)
printf("\n %d is a composite number", num);
else
printf("\n %d is a prime number", num);
return 0;
}
Output
Enter the number: 5
5 is a prime number
46. Write a program using do-while loop to read the numbers until -1 is encountered. Also count the number of prime numbers and composite numbers entered by the user
#include <stdio.h>
int main()
{
int num, i;
int primes=0, composites=0, flag=0;
printf("\n Enter -1 to exit");
printf("\n\n Enter any number:");
scanf("%d",&num);
do
{
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
flag=1;
break;
}
}
if(flag==0)
primes++;
else
composites++;
flag=0;
printf("\n\n Enter any number: ");
scanf("%d",&num);
} while(num != -1);
printf("\n Count of prime numbers entered = %d", primes);
printf("\n Count of composite numbers entered = %d", composites);
return 0;
}
Output
Enter -1 to exit
Enter any number: 5
Enter any number: 10
Enter any number: 7
Enter any number: -1
Count of prime numbers entered = 2
Count of composite numbers entered = 1
47. Write a program to calculate pow(x,n) i.e., to calculate x^n
#include <stdio.h>
#include <math.h>
int main()
{
int i, num, n;
long int result =1;
printf("\n Enter the number: ");
scanf("%d", &num);
printf("\n Till which power to calculate: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
result = result * num;
printf("\n pow(%d, %d) = %ld", num, n, result);
return 0;
}
Output
Enter the number: 2
Till which power to calculate: 5
pow(2, 5) = 32
48. Write a program to print the reverse of a number.
#include <stdio.h>
int main()
{
int num, temp;
printf("\n Enter the number: ");
scanf("%d", &num);
printf("\n The reversed number is: ");
while(num != 0)
{
temp = num%10;
printf("%d",temp);
num = num/10;
}
return 0;
}
Output
Enter the number: 123
The reversed number is: 321
49. Write a program to enter a number and then calculate the sum of its digits.
#include <stdio.h>
int main()
{
int num, temp, sumofdigits = 0;
printf("\n Enter the number: ");
scanf("%d", &num);
while(num != 0)
{
temp = num%10;
sumofdigits += temp;
num = num/10;
}
printf("\n The sum of digits = %d",
sumofdigits);
return 0;
}
Output
Enter the number: 123
The sum of digits = 6
50. Write a program to enter a decimal number. Calculate and display the binary equivalent of this number.
#include <stdio.h>
#include <math.h>
int main()
{
int decimal_num, remainder, binary_num = 0,
i = 0;
printf("\n Enter the decimal number: ");
scanf("%d", &decimal_num);
while(decimal_num != 0)
{
remainder = decimal_num%2;
binary_num += remainder*pow(10,i);
decimal_num = decimal_num/2;
i++;
}
printf("\n The binary equivalent = %d",
binary_num);
return 0;
}
Output
Enter the decimal number: 7
The binary equivalent = 111
51. Write a program to enter a decimal number. Calculate and display the octal equivalent of this number
#include <stdio.h>
#include <math.h>
int main()
{
int decimal_num, remainder, octal_num = 0,
i = 0;
printf("\n Enter the decimal number: ");
scanf("%d", &decimal_num);
while(decimal_num != 0)
{
remainder = decimal_num%8;
octal_num += remainder*pow(10,i);
decimal_num = decimal_num/8;
i++;
}
printf("\n The octal equivalent = %d",
octal_num);
return 0;
}
Output
Enter the decimal number: 18
The octal equivalent = 22
52. Write a program to enter a binary number. Calculate and display the decimal equivalent of this number.
#include <stdio.h>
#include <math.h>
int main()
{
int decimal_num = 0, remainder, binary_num,
i = 0;
printf("\n Enter the binary number: ");
scanf("%d", &binary_num);
while(binary_num != 0)
{
remainder = binary_num%10;
decimal_num += remainder*pow(2,i);
binary_num = binary_num/10;
i++;
}
printf("\n The decimal equivalent = %d",
decimal_num);
return 0;
}
Output
Enter the binary number : 111
The decimal equivalent = 7
53. Write a program to enter an octal number. Calculate and display the decimal equivalent of this number.
#include <stdio.h>
#include <math.h>
int main()
{
int decimal_num= 0, remainder, octal_num,
i = 0;
printf("\n Enter the octal number: ");
scanf("%d", &octal_num);
while(octal_num != 0)
{
remainder = octal_num%10;
decimal_num += remainder*pow(8,i);
octal_num = octal_num/10;
i++;
}
printf("\n The decimal equivalent = %d",
decimal_num);
return 0;
}
Output
Enter the octal number: 22
The decimal equivalent = 18
54. Write a program to enter a hexadecimal number. Calculate and display the decimal equivalent of this number.
#include <stdio.h>
#include <math.h>
int main()
{
int decimal_num= 0, remainder, hex_num, i
=0;
printf("\n Enter the hexadecimal number: ");
scanf("%d", &hex_num);
while(hex_num != 0)
{
remainder = hex_num%10;
decimal_num += remainder*pow(16,i);
hex_num = hex_num/10;
i++;
}
printf("\n The decimal equivalent = %d",
decimal_num);
return 0;
}
Output
Enter the hexadecimal number: 39
The decimal equivalent = 57
55. Write a program to calculate GCD of two numbers.
#include <stdio.h>
int main()
{
int num1, num2, temp;
int dividend, divisor, remainder;
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
if(num1>num2)
{
dividend = num1;
divisor = num2;
}
else
{
dividend = num2;
divisor = num1;
}
while(divisor)
{
remainder = dividend%divisor;
dividend = divisor;
divisor = remainder;
}
printf("\n GCD of %d and %d is = %d", num1,
num2, dividend);
return 0;
}
Output
Enter the first number: 64
Enter the second number: 14
GCD of 64 and 14 is = 2
56. Write a program to sum the series 1 + 1/2 + 1/3 + ... + 1/n.
#include <stdio.h>
int main()
{
int n;
float sum=0.0, a, i;
printf("\n Enter the value of n: ");
scanf("%d", &n);
for(i=1.0;i<=n;i++)
{ a=1/i;
sum = sum +a;
}
printf("\n The sum of series 1/1 + 1/2 +
.... + 1/%d = %f",n, sum);
return 0;
}
Output
Enter the value of n: 5
The sum of series 1/1 + 1/2 + .... + 1/5 = 2.2838
57. Write a program to sum the series 1/1² + 1/2² + ... + 1/3².
#include <stdio.h>
#include <math.h>
int main()
{
int n;
float sum=0.0, a, i;
printf("\n Enter the value of n: ");
scanf("%d", &n);
for(i=1.0;i<=n;i++)
{ a=1/pow(i,2);
sum = sum +a;
}
printf("\n The sum of series 1/1² + 1/ 2² +
.... 1/%d² = %f",n, sum);
return 0;
}
Output
Enter the value of n: 5
The sum of series 1/1² + 1/ 2² + .... 1/5² = 1.4636
58. Write a program to sum the series 1/2 + 2/3 + ... + n/(n+1).
#include <stdio.h>
int main()
{
int n;
float sum=0.0, a, i;
printf("\n Enter the value of n: ");
scanf("%d", &n);
for(i=1.0;i<=n;i++)
{ a= i/(i+1);
sum = sum +a;
}
printf("\n The sum of series 1/2 + 2/3 +
....%d/%d = %f",n,n+1,sum);
return 0;
}
Output
Enter the value of n :5
The sum of series 1/2 + 2/3 + ....5/6 =
2.681+E
59. Write a program to sum the series 1/1 + 2²/2 + 3³/3 + ...
#include <stdio.h>
#include <math.h>
int main()
{
int n, NUM;
float i,sum=0.0;
printf("\n Enter the value of n: ");
scanf("%d", &n);
for(i=1.0;i<=n;i++)
{
NUM = pow(i,i);
sum += (float)NUM/i;
}
printf("\n 1/1 + 4/2 + 27/3 + .... = %f",
sum);
return 0;
}
Output
Enter the value of n:5
1/1 + 4/2 + 27/3 + .... = 701.000
60. Write a program to calculate sum of cubes of first n numbers.
Programming Tip: It is a logical error to skip the updating of loop control variable in the while/do-while loop. Without an update statement, the loop will become an infinite loop.
#include <stdio.h>
#include <math.h>
int main()
{
int i, n;
int term, sum = 0;
printf("\n Enter the
value of n: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
term = pow(i,3);
sum += term;
}
printf("\n 1³ + 2³ + 3³ + ... = %d", sum);
return 0;
}
Output
Enter the value of n:5
1³ + 2³ + 3³ + ... = 225
61. Write a program to calculate sum of squares of first n even numbers.
#include <stdio.h>
#include <math.h>
int main()
{
int i, n;
int term, sum = 0;
printf("\n Enter the value of n: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
if(i%2 == 0)
{ term = pow(i,2);
sum += term;
}
}
printf("\n 2² + 4² + 6² + ...... = %d", sum);
return 0;
}
Output
Enter the value of n: 5
2² + 4² + 6² + ...... = 20
62. Write a program to find whether the given number is an armstrong number or not.
#include <stdio.h>
#include <math.h>
int main()
{
int num, sum=0, r, n;
printf("\n Enter the number: ");
scanf("%d", &num);
n=num;
while(n>0)
{
r=n%10;
sum += pow(r,3);
n=n/10;
}
if(sum==num)
printf("\n %d is an armstrong number", num);
else
printf("\n %d is not an armstrong number",
num);
return 0;
}
Output
Enter the number : 432
432 is not an armstrong number
63. Write a program using for loop to calculate the value of an investment, given the initial value of investment and the annual interest. Calculate the value of investment over a period of time.
#include <stdio.h>
int main()
{
double initVal, futureVal, ROI;
int yrs, i;
printf("\n Enter the investment value: ");
scanf("%lf", &initVal);
printf("\n Enter the rate of interest: ");
scanf("%lf", &ROI);
printf("\n Enter the number of years for
which investment has to be done: ");
scanf("%d", &yrs);
futureVal=initVal;
printf("\n YEAR \t\t VALUE");
printf("\n ____________________________");
for(i=1;i<=yrs;i++)
{
futureVal = futureVal * (1 + ROI/100.0);
printf("\n %d \t %lf", i, futureVal);
}
return 0;
}
Output
Enter the investment value: 20000
Enter the rate of interest: 12
Enter the number of years for which
investment has to be done: 5
YEAR VALUE
____________________________
1 22400.00
2 25088.00
3 28098.56
4 31470.38
5 35246.83
64. Write a program to generate calendar of a month given the start day of the week and the number of days in that month.
#include <stdio.h>
int main()
{
int i, j, startDay, num_of_days;
printf("\n Enter the starting day of the
week (1 to 7): ");
scanf("%d", &startDay);
printf("\n ENter the number of days in
that month: ");
scanf("%d", &num_of_days);
printf(" Sun Mon Tue Wed Thurs Fri Sat\n");
printf("\n ____________________________");
for(i=0;i<startDay-1;i++)
printf(" ");
for(j=1;j<=num_of_days;j++)
{
if(i>6)
{
printf("\n");
i=1;
}
else
i++;
printf("%2d ", j);
}
return 0;
}
Output
Enter the starting day of the week (1 to 7): 5
Enter the number of days in that month : 31
Sun Mon Tue Wed Thurs Fri Sat
1 2 3 4 5 6 7
3.5 THE break AND continue STATEMENTS
3.5.1 break Statement
In C, the break statement is used to terminate the execution of the nearest enclosing loop in which it appears.
Programming Tip: The break statement is used to terminate the execution of the nearest enclosing loop in which it appears.
We have already seen its usage in the switch statement. The break statement is widely used with for loop, while loop, and do-while loop. When compiler encounters a break statement, the control passes to the statement that follows the loop in which the break statement appears. Its syntax is quite simple, just type keyword break followed with a semicolon.
break;
In switch statement if the break statement is missing then every case from the matched case label till the end of the switch, including the default, is executed. This example given below shows the manner in which break statement is used to terminate the statement in which it is embedded.
#include <stdio.h>
int main()
{
int i = 1;
while(i<=10)
{
if (i==5)
break;
printf("\n %d", i);
i = i + 1;
}
return 0;
}
Note that the code is meant to print first 10 numbers using a while loop, but it will actually print only numbers from 1 to 4. As soon as i becomes equal to 5, the break statement is executed and the control jumps to the statement following the while loop.
Hence, the break statement is used to exit a loop from any point within its body, bypassing its normal termination expression. When the break statement is encountered inside a loop, the loop is immediately terminated, and program control is passed to the next statement following the loop. Figure 3.9 shows the transfer of control when the break statement is encountered.
while(...) do
{ {
...... ......
if(condition) if(condition)
break; ---------+ break; ---------+
...... | ...... |
} | }while(...); |
...... <-------------+ ...... <--------------+
Transfers control out of Transfers control out of
the while loop the do-while loop
for(...) for(...)
{ {
...... ......
if(condition) for(...)
break; ---------+ {
...... | ......
} | if(condition)
...... <-------------+ break; -----+
...... |
Transfers control out } |
of the for loop ...... <----------+
}
Transfers control out of
inner for loop
Figure 3.9 The break statement
3.5.2 continue Statement
Like the break statement, the continue statement can only appear in the body of a loop. When the compiler encounters a continue statement then the rest of the statements in the loop are skipped and the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing loop. Its syntax is quite simple, just type keyword continue followed with a semicolon.
Programming Tip: When the compiler encounters a continue statement, then rest of the statements in the loop are skipped and the control is unconditionally transferred to the loop-continuation portion of the nearest loop.
continue;
Again like the break statement, the continue statement cannot be used without an enclosing for, while, or do-while statement. When the continue statement is encountered in the while and do-while loops, the control is transferred to the code that tests the controlling expression. However, if placed within a for loop, the continue statement causes a branch to the code that updates the loop variable. For example, look at the following code.
#include <stdio.h>
int main()
{
int i;
for(i=1; i<= 10; i++)
{
if (i==5)
continue;
printf("\t %d", i);
}
return 0;
}
The code given here is meant to print numbers from 1 to 10. But as soon as i becomes equal to 5, the continue statement is encountered, so rest of the statements in the for loop are skipped and the control passes to the expression that increments the value of i. The output of this program would thus be
Programming Tip: As far as possible, try not to use goto, break, and continue statements as they violate the rules of structured programming.
1 2 3 4 6 7 8 9 10
(Note that there is no 5 in the series. It could not be printed, as continue caused early incrementation of i and skipping of the statement that printed the value of i on screen).
Figure 3.10 illustrates the use of continue statement in loops.
+-------------+ do
| v {
| while(...) ......
| { if(condition)
| ...... continue; --------+
| if(condition) ...... |
+-------------------- continue; }while(...); <---------+
......
} (Transfers control to the condition
expression of the do-while loop)
(Transfers control to the condition
expression of the while loop)
+-------------+ +-------------+
| v | v
| for(...) | for(...)
| { | {
| ...... | ......
| if(condition) | for(...) <------+
+-------------------- continue; | { |
...... | ...... |
} | if(condition)|
| continue; +
(Transfers control to the | }
condition expression of the | ......
for loop) | }
|
(Transfers control to the condition
expression of the inner for loop)
Figure 3.10continue statement
Hence, we conclude that the continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. The continue statement is usually used to restart a statement sequence when an error occurs. Look at the program given below that demonstrates the use of break and continue statements.
#include <stdio.h>
#include <math.h>
int main()
{
int num;
do
{
printf("\n Enter any number. Enter 999 to stop: ");
scanf("%d", &num);
if(num == 999)
break; // quit the loop
if(num < 0)
{
printf("\n Square root of negative numbers is not defined");
continue; // skip the following statements
}
printf("\n The square root of %d is %f", num, sqrt(num));
}while(1);
return 0;
}
## 3.6 goto STATEMENT
The `goto` statement is used to transfer control to a specified `label`. However, the `label` must reside in the same function and can appear only before one statement in the same function. The syntax of `goto` is shown in Figure 3.11.
**Figure 3.11** `goto` statement
Here, `label` is an identifier that specifies the place where the branch is to be made. `Label` can be any valid variable name that is followed by a colon (`:`). The `label` is placed immediately before the statement where the control has to be transferred.
The `label` can be placed anywhere in the program either before or after the `goto` statement. Whenever the `goto` statement is encountered the control is immediately transferred to the statements following the `label`. Therefore, `goto` statement breaks the normal sequential execution of the program. If the `label` is placed after the `goto` statement, then it is called a *forward jump* and in case it is located before the `goto` statement, it is said to be a *backward jump*.
The `goto` statement is often combined with the `if` statement to cause a conditional transfer of control.
IF condition THEN goto label
In this book, we will not use the `goto` statement because computer scientists usually avoid using this statement in favour of the 'structured programming' paradigm. Some scientists think that the `goto` statement should be abolished from higher-level languages because they complicate the task of analysing and verifying the correctness of programs (particularly those involving loops).
Moreover, structured program theory proves that the availability of the `goto` statement is not necessary to write programs, as combination of sequence, selection, and repetition constructs is sufficient to perform any computation. The code given below demonstrates the use of a `goto` statement. The program calculates the sum of all positive numbers entered by the user.
> **Programming Tip:** Follow proper indentation for better clarity, readability, and understanding of the loops.
```c
#include <stdio.h>
int main()
{
int num, sum=0;
read: // label for goto statement
printf("\n Enter the number. Enter 999 to
end: ");
scanf("%d", &num);
if (num != 999)
{
if (num < 0)
goto read; // jump to label- read
sum += num;
goto read; // jump to label- read
}
printf("\n Sum of the numbers entered by the
user is = %d", sum);
return 0;
}
Conclusion
It is not necessary to use goto statement as it can always be eliminated by rearranging the code.
Using the goto statement violates the rules of structured programming.
It is a good programming style to use break, continue, and return statements in preference to goto whenever possible.
goto statements make the program code complicated and renders the program unreadable.
Note: One must avoid the use of break, continue, and goto statements as much as possible as they are techniques used in unstructured programming.
In structured programming, you must prefer to use if and if-else constructs to avoid such statements. For example, look at the following code which calculates the sum of numbers entered by the user. The first version uses break statement. The second version replaces break by if-else construct.
// Uses break statement
#include <stdio.h>
int main()
{
int num, sum=0;
while(1)
{
printf("\n Enter any number. Enter 999 to
stop: ");
scanf("%d", &num);
if(num==999)
break; // quit the loop
sum+=num;
}
printf("\n SUM = %d", sum);
return 0;
}
// Same program without using break
// statement
#include <stdio.h>
int main()
{
int num, sum=0, flag=1;
// flag will be used to exit from the loop
while(flag==1) // loop control variable
{
printf("\n Enter any number. Enter 999 to
stop: ");
scanf("%d", &num);
if(num!=999)
sum+=num;
else
flag=0; // to quit the loop
}
printf("\n SUM = %d", sum);
return 0;
}
Now let us see how we can eliminate continue statement from our programs. Let us first write a program that calculates the average of all non-zero numbers entered by the user using the continue statement. The second program will do the same job but without using continue.
#include <stdio.h>
int main()
{
int num, sum=0, flag=1, count=0;
float avg;
// flag will be used to exit from the loop
while(flag==1)
{
printf("\n Enter any number. Enter 999 to
stop: ");
scanf("%d", &num);
if(num==0)
continue; // skip the following statements
if(num!=999)
{
sum+=num;
count++;
}
else
flag=0;
// set loop cntl var to jump out of loop
}
printf("\n SUM = %d", sum);
avg = (float) sum/count;
printf("\n Average = %f", avg);
return 0;
}
// Same program without using continue statement
#include <stdio.h>
int main()
{
int num, sum=0, flag=1, count=0;
float avg;
// flag will be used to exit from the loop
while(flag==1)
{
printf("\n Enter any number. Enter 999 to
stop: ");
scanf("%d", &num);
if(num!=0)
{
if(num!=999)
{
sum+=num;
count++;
}
else
flag=0;
}
}
printf("\n SUM = %d", sum);
avg = (float) sum/count;
printf("\n Average = %f", avg);
return 0;
}
POINTS TO REMEMBER
C supports conditional type branching and unconditional type branching. 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.
With nesting of if-else statements, we often encounter a problem known as dangling else problem. This problem is created when there is no matching else for every if statement. In such cases, C always pairs an else statement with the most recent unpaired if statement in the current block.
Switch case statements are often used as an alternative to several long if statements that compare a variable to several integral values. Switch statements are also used to handle the input given by a user.
Default is a case that is executed when the value of the variable does not match with any of the values of case statements.
Iterative statements are used to repeat the execution of a list of statements, depending on the value of an integer expression.
The while/do-while/for loops provide a mechanism to repeat one or more statements while a particular condition is true. In the do-while loop, the test condition is tested at the end of the loop while in case of for and while loops the test condition is tested before entering the loop.
The break statement is used to terminate the execution of the nearest enclosing loop in which it appears.
The continue statement is used to transfer control to the loop-continuation part of the nearest enclosing loop.
The goto statement is used to transfer control to a specified label. However, the label must reside in the same function and can appear before only one statement in the same function.
GLOSSARY
Conditional branching Conditional branching statements are used to jump from one part of the program to another depending on whether a particular condition is satisfied or not.
Continue statement When the compiler encounters a continue statement then the rest of the statements in the loop are skipped and the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing loop.
Dangling else problem Problem encountered with nesting of if-else statements which is created when there is no matching else for every if statement.
do-while loop A form of iterative statement in which the test condition is evaluated at the end of the loop.
for loop The mechanism used to repeat a task until a particular condition is true. For loop is usually known as a deterministic or definite loop because the programmer knows exactly how many times the loop will repeat.
goto statement It is used to transfer control to a specified label. However, the label must reside in the same function and can appear only before one statement in the same function.
if statement Simplest form of decision control statement that is frequently used in decision making.
if-else-if statement Decision control statement that works in the same way as a normal if statement. It is also known as nested if construct.
if-else statement Decision control statement in which first the test expression is evaluated. If the expression is true, if block is executed and else block is skipped. Otherwise, if the expression is false, else block is executed and if block is ignored.
Iterative statement Statement used to repeat the execution of a list of statements, depending on the value of an integer expression.
Nested loop Loops placed inside other loops.
switch case statement A switch case statement is a multi-way decision statement that is a simplified version of an if-else block that evaluates only one variable.
while loop The mechanism used to repeat one or more statements while a particular condition is true.
EXERCISES
Fill in the Blanks
Dangling else problem occurs when ________.
The switch control expression must be of ________ type.
In a do-while loop, if the body of the loop is executed n times, the test condition is evaluated ________ times.
The ________ statement is used to skip statements in a loop.
A loop that always satisfies the test condition is known as a ________ loop.
In a counter-controlled loop, ________ variable is used to count the number of times the loop will execute.
________ statements help to jump from one part of the program to another depending on whether a particular condition is satisfied or not.
________ statements are used to repeat the execution of a list of statements.
In ________ loop, the entry is automatic and there is only a choice to continue it further or not.
When we do not know in advance the number of times the loop will be executed, we use a ________ loop.
The ________ statement is used to transfer control to a specified label.
________ statement violates the rules of structured programming.
Multiple Choice Questions
Which type of statement helps to jump from one part of the program to another depending on whether a particular condition is satisfied or not?
(a) conditional branching (b) loops (c) iterative (d) None of these
A statement block consists of how many statements?
(a) 0 (b) 1 (c) n (d) None of these
Dangling else problem can arise in which of the following statement(s)?
(a) conditional branching (b) loops (c) iterative (d) None of these
Which among the following is a multi-way decision statement?
(a) if-else (b) if-else-if (c) switch (d) do-while loop
Case labels must end with which token?
(a) , (b) : (c) ; (d) /
The default label can be placed at which position in the switch statement?
(a) beginning (b) end (c) middle (d) anywhere
The statements in the statement block are encapsulated within a ________?
(a) () (b) {} (c) [] (d) <>
Which statement is used to terminate the execution of the nearest enclosing loop in which it appears?
(a) break (b) continue (c) default (d) case
When the ________ statement is encountered then the rest of the statements in the loop are skipped.
(a) break (b) continue (c) default (d) case
State True or False
Decision control statements are used to repeat the execution of a list of statements.
The expression in a selection statement can have no side effects.
An expression in an if statement must be enclosed within parentheses.
No two case labels can have the same value.
The case labelled constant can be a constant or a variable.
The if-else statement requires integral values in its expressions.
There can be only one default case in the switch-case statement.
The do-while loop checks the test expression and then executes the statements placed within its body.
In a while loop, if the body is executed n times, then the test expression is executed (n + 1) times.
The number of times the loop control variable is updated is equal to the number of times the loop iterates.
In the for loop, the value of the loop control variable must be less than that of its ending value.
It is necessary to have initialization, testing, and updating expressions within the for statement.
In a pre-test loop, the test condition is checked after the body of the loop.
Post-test loops get executed at least for one time.
In a while loop, the loop control variable is initialized in the body of the loop.
The loop control variable may be updated before or after the loop iterates.
Counter-controlled loop must be designed as pre-test loops.
The do-while loop is a post-test loop.
The for loop and while loop are pre-test loops.
Every case label must evaluate to a unique constant expression value.
Two case labels may have the same set of actions associated with them.
The default label can be placed anywhere in the switch statement.
C does not permit nested switch statements.
When we place a semicolon after the for statement, the compiler will generate an error message.
Review Questions
What are decision control statements? Explain in detail.
Compare the use of if-else construct with that of conditional operator.
Explain the importance of a switch case statement. In which situations is a switch case desirable? Also give its limitations.
How is comma operator useful in a for loop? Explain with the help of relevant examples.
Write a short note on goto statement. As a programmer would you prefer to use this statement? Justify your answer.
With the help of an example explain the dangling if-else problem.
Why floating point numbers should not be used for equality in expressions?
Explain the usefulness of default statement in switch case statement.
Give the points of similarity and differences between a while loop and a do-while loop.
Distinguish between the break and the continue statements.
Write a short note on iterative statements that C language supports.
Enter two integers as dividend and divisor. If the divisor is greater than zero then divide the dividend by the divisor. Assign their result to an integer variable rem and their quotient to a floating point number quo.
When will you prefer to work with a switch statement?
What is a null statement? How can it be useful in our programs?
In what situation will you prefer to use for, while, and do while loops?
Can we use a for loop when the number of iterations is not known in advance? If yes, give a program that illustrates how this can be done.
Change the following for loop into a while loop. Also convert the for loop into a do-while loop.
int i;
for(i=10;i>0;i--)
printf("%d", i);
Change the following do-while loop into a for loop. Also rewrite the code by changing the do-while loop into a while loop.
int num;
printf("\n Enter any number. Enter 999 to
stop : ");
scanf("%d", &num);
do
{
printf("%d", x);
printf("\n Enter any number. Enter 999 to
stop : ");
scanf("%d", &num);
}while(num != 999);
Change the following while loop into a do-while loop. Also convert the while loop into a for loop.
int num;
printf("\n Enter any number. Enter 999 to
stop : ");
scanf("%d", &num);
while(num != 999)
{
printf("%d", x);
printf("\n Enter any number. Enter 999 to
stop : ");
scanf("%d", &num);
}
The following for loops are written to print numbers from 1 to 10. Are these loops correct? Justify your answer.
(a)
int i;
for(i=0;i<10;i++)
printf("%d", i);
(b)
int i, num;
for(i=0;i<10;i++)
{
num = i+1;
printf("%d", num);
}
(c)
int i;
for(i=1;i<=10;i++)
{
printf("%d", i);
i++;
}
Programming Exercises
Write a program to read a floating point number and an integer. If the value of the floating point number is greater than 3.14 then add 10 to the integer.
Write a program to print the prime factors of a number.
Write a program to test if a given number is a power of 2.
Hint: A number x is a power of 2 if x != 0 and (x & (x - 1)) == 0
Write a program to print the Floyd's triangle.
Write a program to read two numbers. Then find out whether the first number is a multiple of the second number.
Write a program using switch case to display a menu that offers 5 options: read three numbers, calculate total, calculate average, display the smallest, and display the largest value.
Write a program to display the sin(x) value where x ranges from 0 to 360 in steps of 15.
Write a program to display the cos(x) and tan(x) values where x ranges from 0 to 360 in steps of 15.
Write a program to calculate electricity bill based on the following information:
Consumption unit
Rate of charge
0 – 150
Rs 3 per unit
151 – 350
Rs 100 plus Rs 3.75 per unit exceeding 150 units
351 – 450
Rs 250 plus Rs 4 per unit exceeding 350 units
451 – 600
Rs 300 plus Rs 4.25 per unit exceeding 450 units
Above 600
Rs 400 plus Rs 5 per unit exceeding 600 units
Write a program to read an angle from the user and then display its quadrant.
Write a program that accepts the current date and the date of birth of the user. Then calculate the age of the user and display it on the screen. Note that the date should be displayed in the format specified as dd/mm/yy.
A class has 50 students. Every student is supposed to give three examinations. Write a program to read the marks obtained by each student in all three examinations. Calculate and display the total marks and average of each student in the class.
Write a program in which the control variable is updated in the statements of the for loop.
Write a program which demonstrates the use of goto, break, and continue statements.
Write a program that displays all the numbers from 1 to 100 that are not divisible by 2 as well as by 3.
Write a program to calculate parking charges of a vehicle. Enter the type of vehicle as a character (like c for car, b for bus, etc.) and number of hours then calculate charges as given below:
Truck/Bus – 20 Rs per hour
Car – 10 Rs per hour
Scooter/ Cycle/ Motor cycle – 5 Rs per hour
Modify the above program to calculate the parking charges. Read the hours and minutes when the vehicle enters the parking lot. When the vehicle is leaving, enter its leaving time. Calculate the difference between the two timings to calculate the number of hours and minutes for which the vehicle was parked. Finally calculate the charges based on following rules and then display the result on the screen.
Vehicle name
Rate till 3 hours
Rate after 3 hours
Truck/Bus
20
30
Car
10
20
Cycle/ Motor cycle/ Scooter
5
10
Write a program to read month of the year as an integer. Then display the name of the month.
Write a program to print the sum of all odd numbers from 1 to 100.
Write an interactive program to read an integer. If it is positive then display the corresponding binary representation of that number. The user must enter number 999 to stop. In case the user enters a negative number then ignore that input and ask the user to re-enter any different number.
Write a program to print 20 asterisks.
Write a program that accepts any number and prints the number of digits in that number.
Write a program to generate the following pattern:
* * * * *
* *
* *
* *
* * * * *
Write a program to generate the following pattern:
$ * * * *
* $ *
* $ *
* $ *
* * * * $
Write a program to generate the following pattern:
$ * * * $
* $ $ *
* $ *
* $ $ *
$ * * * $
Write programs to implement the following sequence of numbers.
Write a program that reads integers until the user wants to stop. When the user stops entering numbers, display the largest of all the numbers entered.
Write a program to print the sum of the following series.
Write a program to read a 5 digit number and then display the number in the following format. For example if the user entered 12345, the result should be
12345 1
2345 12
345 123
45 1234
5 12345
Find the output of the following codes.
#include <stdio.h>
int main()
{
int a = 2, b = 3, c = 4;
if( c!= 100)
a = 10;
else
b = 10;
if(a + b > 10)
c = 12;
a = 20;
b = ++c;
printf(" \n a = %d \t b = %d \t c = %d", a,
b, c);
return 0;
}
#include <stdio.h>
int main()
{
int a = 2, b = 3, c = 4;
if(b==2)
a=10;
else
c=10;
printf("\n a = %d \t b = %d \t c = %d", a, b,
c);
return 0;
}
#include <stdio.h>
int main()
{
int a = 2, b = 3, c = 4;
if(a&&b)
c=10;
else
c=20;
printf("\n a = %d \t b = %d \t c = %d" , a,
b, c);
return 0;
}
#include <stdio.h>
int main()
{
int a = 2, b = 3, c = 4;
if(a || b || c)
c=10;
else
c=20;
printf("\n a = %d \t b = %d \t c = %d", a,
b, c);
return 0;
}
#include <stdio.h>
int main()
{
int a = 2, b = 3, c = 4;
if(a)
if(b)
c=10;
else
c=20;
printf("\n a = %d \t b = %d \t c = %d", a,
b, c);
return 0;
}
#include <stdio.h>
int main()
{
int a = 2, b = 3, c = 4;
if(a == 0 || b >= c && c > 0)
if(a && b)
c=10;
else
c=20;
printf("\n a = %d \t b = %d \t c = %d", a,
b, c);
return 0;
}
#include <stdio.h>
int main()
{
int a = 2, b = 3, c = 4;
if( a= b)
c++;
printf(" \n a = %d \t b = %d \t c = %d" , a,
b, c);
return 0;
}
#include <stdio.h>
int main()
{
int a = 2, b = 3, c = 4;
if( a= b < c)
{
c++;
a--;
}
++b;
printf(" \n a = %d \t b = %d \t c = %d", a,
b, c);
return 0;
}
switch(ch)
{
case 'a':
case 'A':
printf("\n A");
case 'b':
case 'B':
printf("\n B");
default:
printf("\n DEFAULT");
}
switch(ch)
{
case 'a':
case 'A':
printf("\n A");
case 'b':
case 'B':
printf("\n B");
break;
default:
printf("\n DEFAULT");
}
switch(ch)
{
case 'a':
case 'A':
printf("\n A");
break;
case 'b':
case 'B':
printf("\n B");
break;
default:
printf("\n DEFAULT");
}
#include <stdio.h>
void main()
{
int num = 10;
printf("\n %d", a>100);
}
#include <stdio.h>
void main()
{
printf("HELLO");
if (-1)
printf("WORLD");
}