programmers
Testing with French AI
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
forloop as well as in theforstatement.
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
forloop, any or all the expressions can be omitted. In case all the expressions are omitted, then there must be two semicolons in theforstatement. - There must be no semicolon after a
forstatement. 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 i to 0 and increments its value. Since a semicolon is placed after the loop, it means that the loop does not contain any statement. So even if the condition is true, no statement is executed. The loop continues till i becomes 10 and the moment i == 10, the statement following the for loop is executed and the value of i (10) is printed on the screen.
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--)
; /* null statement: time delay */
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
forloop, 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
forstatement by using the comma operator. For example, theforstatement 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
forloop contains nothing but two semicolons, that is no initialization, condition testing, and updating of the loop control variable, then theforloop may become an infinite loop if no stopping condition is specified in the body of the loop. For example, the following code will infinitely printC Programmingon the computer screen.
Programming Tip: Although placing an arithmetic expression in the initialization and updating section of the
forloop 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, the 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 an entry-controlled loop, then the loop will never execute. However, in case of a post-test loop, 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 a for loop or a 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 a 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 a for loop, while and do-while loops offer a 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.
Pass 1- 1 2 3 4 5
Pass 2- 1 2 3 4 5
Pass 3- 1 2 3 4 5
Pass 4- 1 2 3 4 5
Pass 5- 1 2 3 4 5
#include <stdio.h>
int main()
{
int i, j;
for (i = 1; i <= 5; i++)
{
printf("\n Pass %d- ", i);
for (j = 1; j <= 5; j++)
printf(" %d", j);
}
return 0;
}
32. 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 = 4;
for (i = 1; i <= N; i++)
{
for (k = 1; k <= count; k++)
printf(" ");
for (j = 1; j <= i; j++)
printf("%d", i);
printf("\n");
count--;
}
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 of 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, i;
printf("\n Enter the number: ");
scanf("%d", &num);
if (num == 0)
fact = 1;
else
{
for (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>
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.283333
57. Write a program to sum the series 1/1² + 1/2² + ... + 1/n².
#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.463611
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.283333
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.000000
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.000000
2 25088.000000
3 28098.560000
4 31470.387200
5 35246.833664
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
breakstatement 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 the 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 a 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 the 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
continuestatement, 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 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 the 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
1 2 3 4 6 7 8 9 10
Programming Tip: As far as possible, try not to use
goto,break, andcontinuestatements as they violate the rules of structured programming.
(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 the 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.10 continue 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.
Forward jump
goto label; ----------+
...... |
...... |
label: <--------------+
statements
Backward jump
label: <--------------+
statements |
...... |
goto label; ----------+
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, the 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 the 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.
#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 the
gotostatement as it can always be eliminated by rearranging the code. - Using the
gotostatement violates the rules of structured programming. - It is a good programming style to use
break,continue, andreturnstatements in preference togotowhenever possible. gotostatements make the program code complicated and render the program unreadable.
Note: One must avoid the use of
break,continue, andgotostatements 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 the break statement. The second version replaces break by an 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 the 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 control 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-elsestatements, we often encounter a problem known as the dangling else problem. This problem is created when there is no matchingelsefor everyifstatement. In such cases, C always pairs anelsestatement with the most recent unpairedifstatement in the current block. switchcase statements are often used as an alternative to several longifstatements that compare a variable to several integral values.switchstatements are also used to handle the input given by a user.defaultis 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/forloops provide a mechanism to repeat one or more statements while a particular condition is true. In thedo-whileloop, the test condition is tested at the end of the loop while in case offorandwhileloops the test condition is tested before entering the loop. - The
breakstatement is used to terminate the execution of the nearest enclosing loop in which it appears. - The
continuestatement is used to transfer control to the loop-continuation part of the nearest enclosing loop. - The
gotostatement 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. The 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, the if block is executed and the else block is skipped. Otherwise, if the expression is false, the else block is executed and the 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 ------ there is no matching else for every if statement.
- The
switchcontrol expression must be of ________integral (पूर्णांक) type. - In a
do-whileloop, if the body of the loop is executed n times, the test condition is evaluated _______\ n_ times. उत्तर: n times. do-while में शर्त हर बार बॉडी चलने के बाद जाँची जाती है, इसलिए जितनी बार बॉडी चली, उतनी ही बार शर्त जाँची गई। (while लूप में यह n + 1 होता है।) - The ________ statement is used to skip statements in a loop. उत्तर: continue statement.
- A loop that always satisfies the test condition is known as a Infinite loop.
- In a counter-controlled loop, ________ variable is used to count the number of times the loop will execute. ---control
- ________ statements help to jump from one part of the program to another depending on whether a particular condition is satisfied or not. ---Conditional
- ________ statements are used to repeat the execution of a list of statements.------ Iterative
- In ________ loop, the entry is automatic and there is only a choice to continue it further or not. ----do-while
- When we do not know in advance the number of times the loop will be executed, we use a ________ loop. ----उत्तर: sentinel-controlled (प्रहरी-नियंत्रित)।
- The ________ statement is used to transfer control to a specified label. ---goto
- ________ statement violates the rules of structured programming. ---goto
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 -----------The correct answer is (a) conditional branching. - A statement block consists of how many statements?
(a) 0 (b) 1 (c) n (d) None of these उत्तर: (c) n (एक स्टेटमेंट ब्लॉक में एक या अधिक, यानी n स्टेटमेंट हो सकते हैं।) - Dangling else problem can arise in which of the following statement(s)?
(a) conditional branching (b) loops (c) iterative (d) None of these उत्तर: (a) conditional branching (dangling else समस्या nested if-else में आती है, जो सशर्त शाखन का हिस्सा है।) - Which among the following is a multi-way decision statement?
(a) if-else (b) if-else-if (c) switch (d) do-while loop उत्तर: (c) switch - Case labels must end with which token?
(a),(b):(c);(d)/--उत्तर: (b) : यानि कि कोलन - The default label can be placed at which position in the switch statement?
(a) beginning (b) end (c) middle (d) anywhere उत्तर: (d) anywhere (default लेबल switch के अंदर कहीं भी रखा जा सकता है।) - The statements in the statement block are encapsulated within a ________?
(a)()(b){}(c)[](d)<>उत्तर: (b) {} (स्टेटमेंट ब्लॉक curly braces { } के अंदर लिखा जाता है।) - 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 उत्तर: (a) break - When the ________ statement is encountered then the rest of the statements in the loop are skipped.
(a) break (b) continue (c) default (d) case ---उत्तर: (b) continue
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
ifstatement 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-elsestatement requires integral values in its expressions. - There can be only one default case in the
switch-casestatement. - The
do-whileloop checks the test expression and then executes the statements placed within its body. - In a
whileloop, 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
forloop, 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
forstatement. - 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
whileloop, 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-whileloop is a post-test loop. - The
forloop andwhileloop 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
switchstatement. - C does not permit nested
switchstatements. - When we place a semicolon after the
forstatement, the compiler will generate an error message.
Review Questions
- What are decision control statements? Explain in detail.
- Compare the use of
if-elseconstruct with that of the conditional operator. - Explain the importance of a
switchcase statement. In which situations is a switch case desirable? Also give its limitations. - How is the comma operator useful in a
forloop? Explain with the help of relevant examples. - Write a short note on the
gotostatement. As a programmer would you prefer to use this statement? Justify your answer. - With the help of an example explain the dangling
if-elseproblem. - Why should floating point numbers not be used for equality in expressions?
- Explain the usefulness of the
defaultstatement in aswitchcase statement. - Give the points of similarity and differences between a
whileloop and ado-whileloop. - Distinguish between the
breakand thecontinuestatements. - Write a short note on iterative statements that the 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
remand their quotient to a floating point numberquo. - When will you prefer to work with a
switchstatement? - What is a
nullstatement? How can it be useful in our programs? - In what situation will you prefer to use
for,while, anddo-whileloops? - Can we use a
forloop 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
forloop into awhileloop. Also convert theforloop into ado-whileloop.
int i;
for (i = 10; i > 0; i--)
printf("%d", i);
- Change the following
do-whileloop into aforloop. Also rewrite the code by changing thedo-whileloop into awhileloop.
int num, x;
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
whileloop into ado-whileloop. Also convert thewhileloop into aforloop.
int num, x;
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
forloops 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
switchcase 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
forloop. - Write a program which demonstrates the use of
goto,break, andcontinuestatements. - 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 the 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 the 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 the 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.
1, 8, 27, 64,...
-5, -2, 0, 3, 6, 9, 12, ...
-2, -4, -6, -8, -10, -12, ...
1, 4, 7, 10, ...
- 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.
-x + x² - x³ + x⁴ +...
1 + (1+2) + (1+2+3) +...
1 - x + x²/2! - x³/3! +...
- Write a program to print the following pattern.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
- Write a program to print the following pattern.
1
2 1 2
3 2 1 2 3
- 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", num > 100);
}
#include <stdio.h>
void main()
{
printf("HELLO");
if (-1)
printf("WORLD");
}
#include <stdio.h>
void main()
{
int a = 3;
if (a < 10)
printf("\n LESS");
if (a < 20)
printf("\n LESS");
if (a < 30)
printf("\n LESS");
}
#include <stdio.h>
void main()
{
int a = 10, b = 20, c = 30, d = 40;
if (c < d)
if (c < b)
printf("\n c");
else if (a < c)
printf("\n a");
if (a > b)
printf("\n b");
else
printf("\n d");
}
#include <stdio.h>
void main()
{
char ch = 'Y';
switch (ch)
{
default:
printf("\n YES OR NO");
case 'Y':
printf("YES");
break;
case 'N':
printf("NO");
break;
}
}
#include <stdio.h>
int main()
{
int num = 10;
for (num++; num++; num++)
printf("%d", num);
return 0;
}
#include <stdio.h>
int main()
{
int num = 10;
for (; --num;)
printf(" %d", num);
return 0;
}
#include <stdio.h>
int main()
{
int num = 10;
for (; !num; num++)
printf(" %d", num);
return 0;
}
#include <stdio.h>
int main()
{
float PI = 3.14, area;
int r = 7;
while (r >= 0)
{
area = PI * r * r;
printf("\n Area = %f", area);
}
return 0;
}
#include <stdio.h>
void main()
{
int i = 0, n = 10;
while (i == 0)
{
if (n < 10)
break;
n--;
}
printf("\n i=%d and n=%d", i, n);
}
#include <stdio.h>
void main()
{
int i = 0;
do
{
printf("\n %d", i);
i++;
} while (i <= 0);
printf("\n STOP");
}
#include <stdio.h>
void main()
{
int i, j;
for (i = 0; i <= 10; i++)
{
printf("\n");
for (j = 0; j <= i; j++)
printf(" ");
printf("\n %d", j);
}
}
#include <stdio.h>
void main()
{
int num = 10;
printf("\n %d", num > 10);
}
#include <stdio.h>
void main()
{
printf("HELLO");
if (1)
printf("WORLD");
}
#include <stdio.h>
void main()
{
int x = -1;
unsigned int y = 1;
if (x < y)
printf("\n SMALL");
else
printf("\n LARGE");
}
#include <stdio.h>
void main()
{
char ch = -63;
int num = -36;
unsigned int unum = -18;
if (ch > num)
{
printf("A");
if (ch > unum)
printf("B");
else
printf("C");
}
else
{
printf("D");
if (num < unum)
printf("E");
else
printf("F");
}
}
#include <stdio.h>
int main()
{
int num = 10;
for (; ++num; num -= 2)
printf(" %d", num);
return 0;
}
#include <stdio.h>
int main()
{
int num = 10;
for (;;)
printf("HI!!!");
return 0;
}
#include <stdio.h>
int main()
{
int num = 10;
for (num++; num <= 100; num = 100)
printf("%d", num);
return 0;
}
#include <stdio.h>
int main()
{
while (1)
printf("Hi");
return 0;
}
#include <stdio.h>
int main()
{
int i = 0;
char c = '0';
while (i < 10)
{
printf("%c", c + i);
i++;
}
return 0;
}
#include <stdio.h>
void main()
{
int i = 0;
do
{
if (i > 10)
continue;
i++;
} while (i < 20);
printf("\n i=%d", i);
}
#include <stdio.h>
void main()
{
int i = 1;
for (; i <= 1; i++)
{
printf("\n %d", i);
printf("\n STOP");
}
}
#include <stdio.h>
void main()
{
int i, j;
for (i = 10; i >= 0; i--)
{
printf("\n");
for (j = i; j >= 0; j--)
printf("%d", j);
}
}
Find errors in the following codes.
(a)
#include <stdio.h>
void main()
{
int i = 1;
while (i <= 10)
{
i = 1;
printf("%d", i);
i++;
}
}
(b)
#include <stdio.h>
void main()
{
int i;
for (i = 0; i <= 10; i++)
printf("%d", i);
}
(c)
#include <stdio.h>
void main()
{
int i = 1;
do
{
printf("%d", i);
i++;
} while (i = 10);
}
(d)
#include <stdio.h>
void main()
{
int i, j;
for (i = 1, j = 0; i + j <= 10; i++)
printf("%d", i);
j += 2;
}
Give the functionality of the following loops.
(a)
int i = 1, sum = 0;
while (i != 10)
{
sum += i;
i = i + 2;
}
(b)
int i, sum = 0;
for (i = 1; i <= 10;)
sum += i;
(c)
int i;
for (i = 1; i <= 10; i++)
i--;
(d)
int i = 10;
do
{
printf("%d", i);
} while (i > 0);
(e)
int i = 10;
do
{
printf("%d", i);
} while (i < 5);
(f)
int i = 1, n = 10, sum = 0;
while (i <= n)
{
sum += i;
i++;
}
(g)
int i, sum = 0;
for (i = 1;; i++)
sum += i;
(h)
int i = 10;
while (i-- > 0)
printf("%d", i);
(i)
int i;
for (i = 10; i > 5; i -= 2)
printf("%d", i);
(j)
int i;
for (i = 10; i > 5;)
printf("%d", i);
