6 Loop Control – Programming in C, 3/e, 3rd Edition

CHAPTER 6

Loop Control

Chapter Outline
6.1  INTRODUCTION

In our life, we need to perform tasks which are repetitive in nature in numerous applications. It is a tedious process to perform such kind of tasks repeatedly with pen/pencil and paper. But with computer programming languages and packages, the task becomes easy, accurate and fast. For example, salary of labours of a factory can be calculated simply by a formula (number of hours work carried × wage rate per hour). The accounts department of every organization does this calculation every month/week. Such a type of repetitive deeds can easily be done using a loop in a program.

6.1.1  What is a Loop?

A loop is defined as a block of statements, which are repeatedly executed for a certain number of times.

The loops are of two types.

  1. Counter-controlled repetition: This is also called the definite repetition action, because the number of iterations to be performed is defined in advance in the program itself. The steps for performing counter-controlled repetitions are as follows.

    Steps in Loop

    Loop variable: It is a variable used in the loop.

    Initialization: It is the first step in which starting and final values are assigned to the loop variable. Each time the updated value is checked by the loop itself.

    Incrimination/decrimination: It is the numerical value added or subtracted to the variable in each round of the loop. The updated value is compared with the final value and if it is found less than the final value the steps in the loop are executed.

    The above steps are implemented in numerous programs in this chapter.

  2. Sentinel-controlled repetition : This is also called the indefinite repetition. One cannot estimate how many iterations are to be performed. In this type, loop termination happens on the basis of certain conditions using the decision-making statement.

    The C language supports three types of loop control statements and their syntaxes are described in Table 6.1 (also see Figures 6.1 and 6.2).

Table 6.1  Loops in C

for

while

do-while

for(expression −1;

expression −1;

Expression −1; do

expression−2;

while(expression −2)

{

expression−3)

{

statement;

statement;

statement;

expression−3;

 

expression −3;

}

 

}

while(expression−2);

Figure 6.1  The while statement

Figure 6.2  The do-while statement

The for loop statement comprises three actions. These actions are placed in the for statement itself. The three actions are initialize counter, test condition and Re-evaluation parameters, which are included in one statement. The expressions are separated by semi-colons (;). This leads the programmer to visualize the parameters easily. The for statement is equivalent to while and do-while statements. The only difference between for and while is that in the latter case logical condition is tested and then the body of the loop gets executed. However, in the for statement, test is always performed at the beginning of the loop. The body of the loop may not be executed at all times if the condition fails at the beginning.

for (a=10;a<10;a−−)

printf(“%d”, a);

For example, in the above two-line program will never execute because the test condition is not proper at the beginning, hence statement following to for loop does not execute.

The do-while loop executes the body of the loop at least once regardless of the logical condition.

6.2  THE for LOOP

The for loop allows to execute a set of instructions until a certain condition is satisfied. Condition may be predefined or open-ended. The general syntax of the for loop will be as given in Table 6.2 (see also Figures 6.3 and 6.4).

Explanation:

The for statement contains three expressions which are separated by semi-colons. Following actions are to be performed in the three expressions.

Table 6.2  Syntax of for loop

for(initialize counter; test condition; re-evaluation parameter)

{

statement1;

statement2;

}

Figure 6.3  The for loop

Figure 6.4  Execution of the for loop

  1. The initialize counter sets to an initial value. This statement is executed only once.
  2. The test condition is a relational expression, that determines the number of iterations desired or determines when to exit from the loop. The ‘for’ loop continues to execute as long as conditional test is satisfied. When the condition becomes false the control of the program exits from the body of the ‘for’ loop and executes next statement after the body of the loop.
  3. The re-evaluation parameter decides how to make changes in the loop (increment or decrement operations are to be used quite often). The body of the loop may contain either a single statement or multiple statements. In case, there is only one statement after the for loop, braces may not be necessary. In such a case, only one statement is executed till the condition is satisfied. It is good practice to use braces even for single statement following the for loop.

The syntax of the ‘for’ loop with only one statement is shown in the third row of Table 6.3.

The for loop can be specified by different ways and it is as per Table 6.3.

Table 6.3  Various formats of ‘for’ Loop

Syntax

Output

Remarks

1. for(; 😉

Infinite loop

No arguments

2. for(a=0; a<=20;)

Infinite loop

a’ is neither incremented nor decremented.

for(a =0;a<=10; a++) printf(“%d”, a);

Displays value from 0 to 10

a’ is incremented from 0 to 10. Curly braces are not necessary. Default scope of the for loop is one statement after the for loop.

for(a =10;a>=0;a−−) printf(“%d”, a)

Displays value from 10 to 0

a’ is decremented from 10 to 0.

6.1  Print the first five numbers starting from 1 together with their squares.

 

void main()

{

int i;

clrscr();

for(i=1;i<=5;i++)

printf(“\n Number: %5d it’s Square: %5d”,i,i*i);

}

OUTPUT:

Number: 1 it’s Square: 1

Number: 2 it’s Square: 4

Number: 3 it’s Square: 9

Number: 4 it’s Square: 16

Number: 5 it’s Square: 25

Explanation:

Let us now examine how the program executes.

  1. The value of i sets to one for the first time when the program execution starts in the for loop.
  2. The condition i ≤ 5 is specified and tested in each iteration. Initially, the condition is true since the value of i is 1. The statements following the for loop gets executed.
  3. Upon execution of the printf() statement, compiler sends control back to the for loop where the value of i is incremented by one. This is repeated till the value of ‘i’ is less than or equal to 5.
  4. If the new updated value of i exceeds 5, the control exits from the loop.
  5. The printf() statement executes as long as the value of i reaches 5.

The for loop can be used by different ways. Various examples using for loops are given below.

6.2  Display numbers from 1 to 15 using for loop. Use i ++.

 

void main()

{

int i;

clrscr();

for(i=1;i<=15;i++)

printf(“%5d”,i);

getche()

}

OUTPUT:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Explanation:

In the above program counter is initialized with a variable i = 1. Testing and incrementation of counter value are done in the for statement itself. Instead of i++ we can also use i = i + 1. Here, we are illustrating a program using i = i +1.

6.3  Display numbers from 1 to 15 using for loop. Use i = i +1.

 

void main()

{

int i;

clrscr();

for(i=1;i<=15;i=i+1)

printf(“%5d”,i);

getche();

}

OUTPUT:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Explanation:

In the above program also, the value of counter is incremented at each time in the for statement itself. Instead of i ++, i = i +1 is used in the for statement. The same result can be observed as found in the previous example. The incrementation of a counter can be done anywhere in the body of for loop and for infinite times. An example is stated below where in the counter value is incremented in the body of the loop and not in the for statement.

6.4  Write a program to display numbers from 1 to 16. Use incrementation operation in the body of the loop for more than one time.

 

void main()

{

int i,c=0;

clrscr();

for(i=0;i<=15;)

{

  i++;

  printf(“%5d”,i);

  i=i+1;

  printf(“%5d”,i);

  c++;

}

printf(“\n\n The Body of the loop is executed for %d times.”,c);

}

OUTPUT:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

The Body of the loop is executed for 8 times.

Explanation:

The body of the loop is executed for eight times. Incrementation operation is done following the for statement. Hence, the counter which is initialized in the for statement is incremented first, i.e. the value of i after incrementation is one and the same is displayed with the first printf() statement. After this operation, once again in the loop i is incremented by 1 and the values are displayed using the second printf() statement. The body of the loop is executed till i=15 and for eight times. In the example given below, the declaration of counter is done before the for statement.

6.5  Write a program to display even numbers from 0 to 14. Declare the initial counter value before the for loop statement.

 

void main()

{

int i=0;

clrscr();

for(;i<=15;)

{

  printf(“%5d”,i);

  i+=2;

}

}

OUTPUT:

0 2 4 6 8 10 12 14

Explanation:

In this program, the for statement contains only test condition. The semi-colon (;) is essential before and after the condition. The for statement must contain two semi-colons even though no parameters are provided.

6.6  Write a program to display the numbers in ascending (1 to 10) and descending (10 to 1) orders.

 

void main()

{

int i=0;

clrscr();

printf(“Numbers in Ascending Order :”);

for(;++i<=10;)

printf(“%3d”,i);

printf(“\n\n”);

printf(“Numbers in Descending Order :”);

for(;i−−gt;1;)

printf(“%3d”,i);

}

OUTPUT:

Numbers in Ascending Order : 1 2 3 4 5 6 7 8 9 10

Numbers in Descending Order: 10 9 8 7 6 5 4 3 2 1

Explanation:

In the above example, incrementation and comparison are done in the first for loop. The decrementation operation is in the second for loop. With ++i<=10, firstly, i is incremented and comparison is made and result is displayed through the printf() statement. With i−−>1, (counter) value is compared first. After satisfying decrementation operation is performed and the value is displayed.

6.7  Write a program to display letters from a to j using infinite for loop. Use goto statement to exit from the loop.

 

void main()

{

char i=97;

clrscr();

for(; 😉

{

  printf(“%5c”,i++);

  if(i==107)

  goto stop;

}

stop:;

getche();

}

OUTPUT:

a b c d e f g h i j

Explanation:

The for(; 😉 statement is used in the above program. This statement allows the execution of the body of the loop infinite times. To exit from the infinite for loop, goto statement is used. After satisfying the test condition, goto statement is executed which terminates the program. The output is displayed in alphabets from a to j.

6.8  Write a program to count numbers between 1 to 100 not divisible by 2, 3 and 5.

 

void main()

{

int x,c=0;

clrscr();

printf(“\n Numbers from 1 to 100 not divisible by 2,3 & 5\n\n”);

for(x=0 ;x<=100;x++)

{

  if(x%2!=0 && x%3!=0 && x%5!=0)

  {

    printf(“%d\t”,x);

    c++;

  }

}

printf(“\nTotal Numbers : %d”,c);

}

OUTPUT:

Explanation:

In the above program, for loop executes from 1 to 100. Each time mod operation is performed with 2, 3 and 5 with the value of the loop variable. If the remainder is non-zero then the counter ‘c’ is incremented. Thus, 1 to 100 numbers are checked. At the end, the variable ‘c’ displays the total number.

6.9  Write a program to display the numbers in increasing and decreasing order using the infinite for loop.

 

void main()

{

int n,a,b;

clrscr();

printf(“Enter a number :”);

scanf(“%d”,&n);

a=b=n;

printf(“(++) (−−)\n”);

printf(“============”);

for(; ; (a++,b−−))

{

  printf(“\n%d\t%d”,a,b);

  if(b==0)

  break;

}

}

OUTPUT:

Enter a number : 5

(++) (−−)

==========

5

5

6

4

7

3

8

2

9

1

10

0

Explanation:

The infinite for loop can also be specified as shown in the above program. The initial counter value, which is set to a given number, can be continuously incremented or decremented. In order to terminate from the infinite for loop, a condition (b==0) is tested. After satisfying break statement allows to exit from the loop.

6.10  Create an infinite for loop. Check each value of the for loop. If the value is even, display it otherwise continue with iterations. Print even numbers from 1 to 21. Use break statement to terminate the program.

void main()

{

int i=1;

clrscr();

printf(“\n\t\t Table of Even numbers from 1 to 20”);

printf(“\n\t\t ===== == ==== ======= ==== = == ==\n”);

for(; 😉

{

  if(i==21)

  break;

  else if(i%2==0)

  {

    printf(“%d\t”,i);

    i++;

    continue;

  }

  else

  {

    i++;

    continue;

  }

}

getche();

}

OUTPUT:

Table of Even numbers from 1 to 20

==== == ==== ======= === = == ==

2 4 6 8 10 12 14 16 18

Explanation:

In the above program, both break and continue statements are in use. The program displays only even numbers from 1 to 21. An infinite loop is created and in the loop variable ‘i’ is incremented. The value of ‘i’ is checked every time. If it is even, it is printed otherwise continue statement is executed, which passes control at the beginning of the for loop. When the value of ‘i’ reaches to 21, the break statement is executed and it terminates the loop.

6.11  Write a program to display numbers from 1 to 9 and their square roots.

 

# include <math.h>

void main()

{

int i;

float a;

clrscr();

for(i=1;i<=9;i++)

printf(“\n\t %d %.2f “,i,a=sqrt(i));

getche();

}

OUTPUT:

1 1.00

2 1.41

3 1.73

4 2.00

5 2.24

6 2.45

7 2.65

8 2.83

9 3.00

Explanation:

In the above program, the for loop executes nine times from 1 to 9. The sqrt() functions return square root of a number. Each time value of variable ‘i’ is passed to sqrt() and it returns square root of that number. The header file math.h is essential.

6.12 Write a program to find the number in between 7 and 100 which is exactly divisible by 4 and if divided by 5 and 6 remainders obtained should be 4.

 

# include <process.h>

void main()

{

int x;

clrscr();

for(x=7;x<100;x++)

{

  if(x%4==0 && x%5==4 && x%6==4)

  {

    printf(“\n Number : %d”,x);

  }

}

getche();

}

OUTPUT:

Number : 64

Explanation:

In the above program, the for loop is initialized from 7 to 100. The if statement is used for dividing with modular division operations by 4, 5 and 6. The remainders obtained are checked. If they are 0, 4 and 4 respectively, then the number is displayed.

6.13  Write a program to evaluate the series given in comments.

/* x=1/1+1/4+1/9...1/n2 */

/* y=1/1+1/8+1/27...1/n3 */

# include <math.h>

void main()

{

int i,n;

float x=0,y=0;

clrscr();

printf(“Enter Value of n:”);

scanf(“%d”,&n);

for(i=1;i<=n;i++)

{

  x=x+(1/pow(i,2));

  y=y+(1/pow(i,3));

}

printf(“Value of x = %f”,x);

printf(“\nValue of y = %f”,y);

getche();

}

OUTPUT:

Enter Value of n: 2

Value of x = 1.2500

Value of Y = 1.12500

Explanation:

Initially, it is assumed that the sum of the two series 1 and 2 is zero. So, the variables ‘x’ and ‘y’ are set to zero. The denominators of the first and second equations are squares and cubes of numbers from 1 to ‘n’ respectively. The user enters the value of ‘n’, which determines how long the series should be continued. Every time in the loop square and cube of variable ‘i’ are calculated using the library function pow(). They are added to variables ‘x’ and ‘y’, respectively.

6.14  Write a program to generate the triangular number.

Note: Triangular number is nothing but summation of 1 to given number.

For example, when entered number is 5, its triangular number would be (1+2+3+4+5)=15.

 

void main()

{

int n,j,tri_num=0;

clrscr();

printf(“What Triangular number do you want :”);

scanf(“%d”,&n);

for(j=1;j<=n;++j)

tri_num=tri_num+j;

printf(“Triangular number of 5 is %d”,tri_num);

}

OUTPUT:

What Triangular number do you want? : 5

Triangular number of 5 is 15

Explanation:

In the above program, a number is entered whose triangular number is to be calculated. The for loop is initialized from 1 to ‘n’. In each iteration of for loop, the value of ‘j’ is added to the ‘tri_num’ variable. When the loop terminates the ‘tri_num’ contains triangular number of the entered number.

6.15  Write a program to find the sum of the following series.

/* 1. 1+2+3+..n */

/* 2. 12+22+32+..n2 */

void main()

{

int sum=0,ssum=0,i,j;

clrscr();

printf(“Enter Number :”);

scanf(“%d”, &j);

clrscr();

printf(“ Numbers:”);

for(i=1;i<=j;i++)

printf(“%5d”,i);

printf(“\n\nSquares:”);

for(i=1;i<=j;i++)

{

  printf(“%5d”,i*i);

  sum=sum+i;

  ssum=ssum+i*i;

}

printf(“\n\nSum of Numbers from 1 to %d :%d”,j,sum);

printf(“\nSum of Squares of 1 to %d Numbers :%d”,j,ssum);

}

OUTPUT:

Enter Number: 5

Numbers: 1 2 3 4 5

Squares: 1 4 9 16 25

Sum of Numbers from 1 to 5: 15

Sum of Squares of 1 to 5 Numbers: 55

Explanation:

In the above program, sum and square of sum are assumed to be zero. The first for loop prints number from 1 to the entered number. The second for loop does sum and squares of the numbers from 1 to the entered number. The variable ‘sum’ and ‘ssum’ are used for displaying the final results.

6.16  Write a program to find the perfect squares from 1 to 500.

#include <math.h>

void main()

{

int i,count,x;

float c;

clrscr();

printf(“\n\n”);

printf(“ Perfect squares from 1 to 500\n”);

count=0;

for(i=1;i<=500;i++)

{

  c=sqrt(i);

  x=floor(c);    /* For rounding up floor() is used. */

  if(c==x)

  {

    printf(“\t%5d”,i);

    count++;

  }

}

printf(“\n\n Total Perfect Squares =%d\n”,count);

getch();

}

OUTPUT:

Explanation:

Numbers like 2, 4, 9, 25, . . . are perfect squares. In the above program a for loop is used from 1 to 500. We can use the sqrt() function for finding the square root of numbers. The square root obtained is stored in variable ‘c’, and it is rounded off and stored in another variable ‘x’. The value of ‘c’ remains unchanged. Now the comparison between ‘x’ and ‘c’ is made. If both of them are the same, then the number becomes a perfect square root. Perfect square roots are only integers and not floats. Hence, floor() function does not affect the integer values.

6.17  Write a program to detect the largest number out of five numbers and display it.

 

#include <process.h>

void main( )

exit(0);

{

int a,b,c,d,e,sum=0,i;

clrscr();

printf(“\nEnter Five numbers :”);

scanf(“%d %d %d %d %d”,&a,&b,&c,&d,&e);

sum=a+b+c+d+e;

for(i=sum; i<=sum;i−−)

{

  if(i==a || i==b || i==c || i==d || i==e)

  {

    printf(“The Largest Number : %d”,i);

    exit(0);

  }

}

}

OUTPUT:

Enter Five numbers : 5 2 3 7 3

The Largest Number : 7

Explanation:

Through the keyboard, five numbers are entered and their sum is stored in the variable ‘sum’. The for loop is used up to the value of ‘sum’ in the reverse order (−−). While decrementing the value of sum, the same is tested each time as to whether decremented sum is equal to one of the entered numbers. In case the condition is satisfied, the largest number is displayed and exit() terminates the program. The largest number entered through the keyboard appears first while decrementing the value of ‘sum’ (sum=a+b+c+d+e).

6.18  Write a program to print the five entered numbers in the ascending order.

 

void main()

{

int a,b,c,d,e,sum=0,i;

clrscr();

printf(“\nEnter Five numbers :”);

scanf(“%d %d %d %d %d”,&a,&b,&c,&d,&e);

printf(“\n Numbers in ascending order :”);

sum=a+b+c+d+e;

for(i=1; i<=sum;i++)

{

  if(i==a || i==b || i==c || i==d || i==e)

  {

    printf(“%3d”,i);

  }

}

}

OUTPUT:

Enter Five numbers : 5 8 7 4 1

Numbers in ascending order : 1 4 5 7 8

Explanation:

The logic used is the same as in the previous program. Here, after satisfying the if condition the program does not terminate and searches for the next number. This procedure is continued till the value of ‘a’ reaches to ‘sum’. The numbers are sorted and displayed in the increasing order.

For descending order the for should be ‘for(i=sum; i<=sum;i−−)’.

6.19  Perform multiplication of two integers by using the negative sign.

 

void main()

{

int a,b,c,d=0;

clrscr();

printf(“\n Enter two numbers :”);

scanf(“%d %d”, &a,&b);

for(c=1;c<=b;c++)

d=(d)−(−a);

printf(“Multiplication of %d * %d :%d”,a,b,d);

getche();

}

OUTPUT:

Enter two numbers : 5 5

Multiplication of 5 * 5 : 25

Explanation:

The multiplication is nothing but repetitive addition. For example, multiplication of 5 × 5 is 25 and the result is obtained by adding 5, five times. Here, the two numbers are entered and the 1st number (‘a’) is repeatedly added to ‘b’ (2nd number) times and result is stored in ‘d’. Instead of using ‘+’ sign double negative is used. Multiplication of two −ve signs is +ve (−*− = +).

6.20  Perform multiplication of two integers by using repetitive addition.

 

void main()

{

int a,b,c=1,d=0;

clrscr();

printf(“\n Enter two numbers:”);

scanf(“%d %d”, &a,&b);

for(;;)

{

  d=d+a;

  if(c==b)

  goto stop;

  c++;

}

stop:

printf(“Multiplication of %d * %d :%d”,a,b,d);

getche();

}

OUTPUT:

Enter two numbers : 8 4

Multiplication of 8 * 4 : 32

Explanation:

Here, also the two numbers are entered through the keyboard. The infinite for loop is used and counter ‘c’ is initialized to 1 and ‘d’ to 0. Variable ‘d’ is used for storing the result after repetitive addition. After adding the value of ‘a’ in ‘d’ each time the counter ‘c’ is tested with ‘b’. If there is no match, counter is incremented and program goes back in the loop and the addition is performed again. When ‘c’ equals to ‘b’ (repetitive addition of the first number till the counter is equal to the second number), program terminates using the goto statement and the result of multiplication is displayed.

6.21  Calculate the sum and average of five subjects.

 

void main()

{

int a,b,c,d,e,sum=0,i;

float avg;

clrscr();

printf(“\nEnter The Marks of Five Subjects”);

for(i=1;i<=5;i++)

{

  printf(“\n[%d] Student:”,i);

  if(scanf(“%d %d %d %d %d”,&a,&b,&c,&d,&e)==5)

  {

    sum=a+b+c+d+e;

    avg=sum/5;

    printf(“\n Total Marks of Student[%d] %d”,i,sum);

    printf(“\n Average Marks of Student[%d] %f\n”,i,avg);

  }

  else

  {

    clrscr();

    printf(“\n Type Mismatch”);

  }

}

}

OUTPUT:

Enter The Marks of Five Subjects

[1] Student: 58 52 52 56 78

Total Marks of Student[1] 296

Average Marks of Student[1] 59.000000

[2] Student:

Explanation:

Here, the for loop is used for entering marks of five students. The marks of five subjects are entered through the keyboard. They are assigned to variables ‘a’, ‘b’, ‘c’, ‘d’ and ‘e’. Their ‘sum’ and ‘average’ are calculated. If by mistake, the user enters marks other than integers the program reports the error message ‘Type Mismatch’. The scanf() is compared with the number of arguments entered correctly. If it is less than the given argument the program displays ‘Type Mismatch’. The marks of the second student onwards can be entered and the results can be observed.

6.22  Write a program to enter a character and display its position in alphabets.

 

# include <ctype.h>

void main()

{

int c=1;

char i, ch;

clrscr();

printf(“Enter a character :”);

scanf(“%c”,&ch);

ch=toupper(ch);

for(i=65;i<=90;i++,c++)

if(ch ==i)

printf(“\n’%c’is%d [st/nd/rd/th] Character in Alphabetic.”,i,c);

}

OUTPUT:

Enter a character : U

‘U’ is 21 [st//nd/rd/th] Character in Alphabetic.

Explanation:

In this program, a character is entered. It is converted into capital. The ASCII values of A to Z are from 65 to 90. The for loop is taken from 65 to 90 and these values are compared with the entered character. Certainly, there will be a match somewhere. For this, statement (ch==i) is used. Till the match is achieved counter is incremented. Once the match occurs, we get the position of character from the first alphabetic with the help of a counter.

6.23  Write a program to enter mantissa and exponent. Calculate the value of mx. Where ‘m’ is a mantissa and ‘x’ is an exponent.

void main()

{

int i,number,power;

long ans;

clrscr();

printf(“\n Enter Number :”);

scanf(“%d”,&number);

printf(“\n Enter Power :”);

scanf(“%d”,&power);

ans=1;

for(i=1;i<=power;i++)

ans*=number;

printf(“\n The Power of %d raised to %d is %ld\n”, number, power,ans);

getche();

}

OUTPUT:

Enter Number : 5

Enter Power : 3

The Power of 5 raised to 3 is 125.

Explanation:

In the above program, mantissa and exponents are entered. The first number is mantissa and the second is its power. The variable ‘ans’ stores repetitive multiplication of mantissa till the loop is active. Finally, it displays the power of a given number.

6.3  NESTED fOR LOOPS

We can also use loop within loops. In nested for loops one or more for statements are included in the body of the loop. In other words C allows multiple for loops in nested forms. The numbers of iterations in this type of structure will be equal to the number of iteration in the outer loop multiplied by the number of iterations in the inner loop. Given below examples are based on the nested for loops.

6.24  Write a program to perform subtraction of two loop variables. Use nested for loops.

void main()

{

int a,b,sub;

clrscr();

for(a=3;a>=1;a−−)

{

  for(b=1;b<=2;b++)

  {

    sub=a−b;

    printf(“a=%d\t b=%d\t a−b=%d\n”,a,b,sub);

  }

}

}

OUTPUT:

a=3 b=1 a−b = 2

a=3 b=2 a−b = 1

a=2 b=1 a−b = 1

a=2 b=2 a−b = 0

a=1 b=1 a−b = 0

a=1 b=2 a−b =−1

Explanation:

In the above program, the outer loop variable and inner loop variables are ‘a’ and ‘b’, respectively. For each value of ‘a’ the inner loop is executing twice. The inner loop terminates when the value of ‘b’ exceeds 2 and the outer loop terminates when the value of ‘a’ is 0. Thus, the outer loop executes thrice and for each outer loop, the inner loop executes twice. Thus, the total iterations are 3 × 2 = 6 and six output lines are shown in the output.

6.25  Write a program to illustrate an example based on the nested for loops.

void main()

{

int i,j;

clrscr();

for(i=1;i<=3;i++) /* outer loop */

{

  for(j=1;j<=2;j++) /* inner loop */

  printf(“\n i*j : %d”,i*j);

}

}

OUTPUT:

i*j = 1

i*j = 2

i*j = 2

i*j = 4

i*j = 3

i*j = 6

Explanation:

Here, in the above example for each value of ‘i’ the inner loop’s j value varies from 1 to 2. Outer loop executes three times whereas the inner loop executes six times. The inner loops terminate when the value of j = 2 and the outer loop terminates when the value of i =3. The total number of iterations=outer loop iterations (3)* inner loop iterations (2) = 6.

6.26  Write a program using nested for loops. Print values and messages when any loop ends.

void main()

{

int a,b,c;

clrscr();

for(a=1;a<=2;a++) /* outer loop */

{

  for(b=1;b<=2;b++) /* middle loop */

  {

    for(c=1;c<=2;c++) /* inner loop */

    printf(“\n a=%d + b=%d + c=%d : %d”,a,b,c,a+b+c);

    printf(“\n Inner Loop Over.”);

  }

    printf(“\n Middle Loop Over.”);

}

printf(“\n Outer Loop Over.”);

}

Explanation:

The execution of the above program will be done by the C compiler in sequence as per Table 6.4. The total number of iterations is equal to 2 * 2 * 2 = 8. The final output provides eight results.

Table 6.4  Output of program 6.27

6.27  Write a program to find perfect cubes up to a given number.

/* 1, 8, 27, 64 are perfect cubes of 1, 2, 3 and 4 */.

# include<math.h>

void main()

{

int i, j, k;

clrscr();

printf(“Enter a Number :”);

scanf(“%d”,&k);

for(i=1;i<k;i++)

{

   for(j=1;j<=i;j++)

  {

    if(i==pow(j,3))

    printf(“\nNumber : %d & it’s Cube :%d”,j,i);

  }

}

}

OUTPUT:

Enter a Number : 100

Number : 1 & it’s Cube : 1

Number : 2 & it’s Cube : 8

Number : 3 & it’s Cube : 27

Number : 4 & it’s Cube : 64

Explanation:

In the above program, the programmer has to enter the number up to which the perfect cubes are to be obtained. For example, if the user enters 100, the perfect cubes up to 100 are 1, 8, 27 and 64. Here, the two for loops are used. The outer for loop varies up to the entered number. The inner for loop varies up to value of ‘i’. For each value of ‘j’, its cube is calculated and checked with the value of ‘i’. If the if condition is true, the perfect cubes are printed, otherwise the loop continues. Thus, all the perfect cubes up to a given number are displayed.

6.28  Write a program to display numbers 1 to 100 using ASCII values from 48 to 57. Use the nested loops.

void main()

{

int i,j=0,k= −9;

clrscr();

printf(“\t Table of 1 to 100 Numbers Using ASCII Values \n”);

printf(“\t ===== == = == === ======= ===== ===== ======\n”);

for(i=48;i<=57;i++,k++)

{

  for(j=49;j<=57;j++)

  printf(“%5c%c”,i,j);

  if(k!=1)

  printf(“%5c%c”,i+1,48);

  if(k==0)

  printf(“\b\b%d%d%d”,k+1,k,k);

  printf(“\n\n”);

}

getche();

}

OUTPUT:

Table of 1 to 100 Numbers Using ASCII Values

==== == = == === ======= ===== ===== ==

Explanation:

The first for loop is varying from 48 to 57. These numbers are used for printing the first digit of every number from 1 to 100. 48 to 57 are ASCII codes for 0 to 9. The second for loop is varying from ASCII 49 to 57 whose equivalent numerical numbers are 1 to 9. These ASCII codes are used for printing the second digit. In each output line the common digit like 0 in the first line is decided by the variable of the outer loop. It varies from 0 to 9. The second digit of each line is decided by the variable of inner loop, which varies for all lines from 1 to 9. The value of k = −9 for displaying 10 rows. For displaying numbers from 01 to 99, ‘i’ and j’ are printed without using space in one printf() statement. The first if statement is used for printing 10, 20, 30 up to 90 numbers. The second if is used to print 100.

6.29  Write a program to count number of votes secured by ‘A’ & ‘B’. Assume three voters are voting them. Also count the invalid votes.

# include <ctype.h>

void main()

{

int a=0,b=0,o=0,i;

char v;

clrscr();

printf(“\tPress A or B\n”);

for(i=1;i<=3;i++)

{

  printf(“\n\nVoter no. %d”,i);

  printf(“Enter Vote :”);

  v=getche();

  v=toupper(v);

  if(v==‘A’)

  a++;

  else if(v==‘B’)

  b++;

  else

  o++;

}

printf(“\n\n Status of vote(s) \n”);

printf(“\nA secures %d vote(s).”,a);

printf(“\nB secures %d vote(s).”,b);

printf(“\nInvalid votes %d.”,o);

}

OUTPUT:

Press A or B

Voter no. 1 Enter Vote :A

Voter no. 2 Enter Vote :A

Voter no. 3 Enter Vote :A

Status of vote(s)

A secures 3 vote(s).

B secures 0 vote(s).

Invalid votes 0.

Explanation:

In the above program, the for loop is used for the number of voters who will be voting to either ‘A’ or ‘B’. The body of the loop is executed for three times. The voter can give his/her choice by pressing either ‘A’ or ‘B’. Apart from these two characters, if the user enters any other character, the vote will be invalid. The results are displayed at the output.

6.30  Write a program to simulate a digital clock.

 

# include <dos.h>

void main()

{

int h,m,s;

clrscr();

for(h=1;h<=12;h++)

{

  clrscr();

  for(m=1;m<=59;m++)

  {

    clrscr();

    for(s=1;s<=59;s++)

    {

      gotoxy(8,8);

      printf(“hh mm ss\n”);

      gotoxy(8,9);

      printf(“%d %d %d”,h,m,s);

      sleep(1);

    }

  }

}

}

OUTPUT:

hh mm ss

1     1    1

Explanation:

The above program uses three for loops for hour, minute and second. The inner most loop is for second’s operation, followed by middle loop for minutes and the outer most for hours. When the second’s loop executes 60 times, the minutes loop increments by 1. Similarly, the hours loop increments after completing minute’s loop. The hours loop increments only up to 12. Thereafter, it resets from 1. The gotoxy() function is used for selecting the position where hh mm ss is to be marked.

6.31  Write a program to count the occurrence of 0 to 9 digits between 1 and the given decimal number.

void main()

{

int t,k,n,l,i;

static int st[10];

clrscr();

printf(“\n Enter a Decimal Number :”);

scanf(“%d”,&n);

for(l=1;l<=n;l++)

{

  t=l;

  while(t!=0)

  {

    k=t%10;

    t=t/10;

    st[k]++;

  }

}

printf(“\occurrence of 0−9 digits between 1 to %d Numbers.”,n);

printf(“\n======= = == === ====== ======= = ========\n”);

for(i=0;i<10;i++)

if(st[i]>0)

printf(“\n %d Occurs %8d Times.”,i,st[i]);

getch();

}

OUTPUT:

Enter a Decimal Number: 15

Occurrence of 0−9 digits between 1 to 15 Numbers.

0 Occurs 1 Times.

1 Occurs 8 Times.

2 Occurs 2 Times.

3 Occurs 2 Times.

4 Occurs 2 Times.

5 Occurs 2 Times.

6 Occurs 1 Times.

7 Occurs 1 Times.

8 Occurs 1 Times.

9 Occurs 1 Times.

Explanation:

A decimal number is entered through a keyboard with the variable n. The for loop is used from 1 to n (up to the given number). The value of ‘l’ is copied to another variable ‘t’. In the body of the while loop mod operation is performed on variable ‘t’ for separating individual digits, and the separated digit is stored in the variable ‘k’. Further, the ‘t’ is divided by 10 for obtaining remainders and is assigned to ‘t’. The array st[10] is initialized to 0 using static storage class. The variable ‘k’ is used as an argument with st[], and it is incremented. The value of ‘k’, whatever it contains when used in arrays st[] that element number will be incremented. Thus, we get the occurrence of digits from 0 to 9 by printing this array.

6.32  Write a program to accept a number and find sum of its individual digits repeatedly till the result is a single digit.

 

void main()

{

int n,s=0;

clrscr();

printf(“\n Enter a Number :”);

scanf(“%d”,&n);

printf(“\n Sum of Digits till a single digit\n %d”,n);

for(; n!=0 😉

{

  s=s+n%10;

  n=n/10;

  if(n==0 && s>9)

  {

    printf(“\n %2d”,s);

    n=s;

    s=0;

  }

}

printf(“\n %2d”,s);

}

OUTPUT:

Enter a Number :4687

Sum of Digits till a single digit

4687

25

7

Explanation:

In the above program, a number is entered through the keyboard. The for loop executes till the value of variable ‘n’ is non-zero. The sum of digits obtained is assigned to variable ‘n’. If ‘n’ is found zero and sum is greater than 9 the for loop continues. Thus, repeatedly the sum of digits is calculated till the result of sum becomes less than 10.

6.33  Write a program to display octal numbers in binary. Attach a parity bit with “1” if number of 1s are even otherwise “0”.

 

OR

Generate odd parity to octal numbers 0 to 7. Express each number in binary and attach the parity bit.

 

void main()

{

int x,y,a,b,c=0,j=12,k=2;

clrscr();

printf(“ Binary Bits Parity Bits\n”);

printf(“ =========== ===========”);

for(x=0;x<8;x++)

{

  k++;

  j=12;

  y=x;

  for(a=0;a<3;a++)

  {

    b=y%2;

    gotoxy(j−=3,k);

    printf(“%d”,b);

    y=y/2;

    if(b==1)

    c++;

  }

  if(c%2==0)

   {

    gotoxy(25,k);

    printf(“%d”,1);

  }

  else

  {

    gotoxy(25,k);

    printf(“%d”,0);

  }

  c=0;

}

}

OUTPUT:

Binary Bits
Parity Bits
===========
===========
0 0 0
1
0 0 1
0
0 1 0
0
0 1 1
1
1 0 0
0
1 0 1
1
1 1 0
1
1 1 1
0

Explanation:

In the above program, two for loops are used. The inner for loop generates three binary bits for each octal number. The 0 to 7 octal numbers are taken from the outer for loop. If the bit is 1 counter ‘c’ is incremented. The value of ‘c’ is checked for even or odd condition. If ‘c’ is odd, the parity bit ‘0’ is displayed otherwise ‘1’ will be displayed.

6.34  Write a program to evaluate the series given in comments.

/* sum of series of x−x3/3!+x5/5!−x7/7!+...xn/n! */

 

# include <math.h>

void main()

{

int n,i,x,c=3,f=1,l;

float sum;

clrscr();

printf(“Enter x & n :”);

scanf(“%d %d”,&x,&n);

sum=x;

for(i=3;i<=n;i+=2)

{

  f=1;

  if(c%2!=0)

  {

    for(l=1;l<=i;l++)

    f=f*l;

    sum=sum−pow(x,i)/f;

  }

  else

  {

    for(l=1;l<=i;l++)

    f=f*l;

    sum=sum+pow(x,i)/f;

  }

c++;

}

printf(“\nSum of series Numbers :%f”,sum);

getche();

}

OUTPUT:

Enter x & n : 2 5

Sum of series Numbers :0.9333

Explanation:

Through the keyboard, the values of ‘x’ and ‘n’ are entered, where numerical constant values are assigned to ‘x’ and ‘n’. Throughout the series, ‘n’ decides how long the series should continue. The series contains alternate + and − terms. The two for loops within if are used for calculating the factorials. The if statement decides the positive or negative term depending upon odd or even value of ‘c’.

The following are the programs based on a series. The logic of the programs is simple for understanding.

6.35  Write a program to evaluate the series given in comment.

/* x+x2/2!+x4/4!+x6/6!+...xn/n! */

 

# include <math.h>

void main()

{

int f=1,l,i,x,y;

float sum;

clrscr();

printf(“Enter the value of x & y :”);

scanf(“%d %d”,&x,&y);

sum = x;

for(i=2;i<=y;i+=2)

{

  f=1;

  for(l=1;l<=i;l++)

  f=f*l;

  sum = sum + pow(x,i)/f;

}

printf(“\n Sum of Series : %f”, sum);

getche();

}

OUTPUT:

Enter the value of x & y : 4 4

Sum of Series :22.6666

6.36  Write a program to evaluate the series given in comment.

/* 1−1/1!+2/2!−3/3!...n/n! */

 

# include <math.h>

void main()

{

int n,i,c=3,l;

float sum=0,f=1,k;

clrscr();

printf(“Enter value of n :”);

scanf(“%d”,&n);

sum=1;

for(i=1;i<=n;i++)

{

  f=1;

  if(c%2!=0)

  {

    for(l=1;l<=i;l++)

    f=f*l;

    k=i/f;

    sum=sum−k;

  }

  else

  {

    for(l=1;l<=i;l++)

    f=f*l;

    sum=sum+(i/f);

  }

  c++;

}

printf(“\nSum of series Numbers :%f”,sum);

}

OUTPUT:

Enter value of n : 3

Sum of series Numbers : 0.5000

6.37  Write a program to detect the Armstrong numbers in three digits from 100 to 999. If the sum of cubes of each digits of the number is equal to the number itself, then the number is called an Armstrong number (e.g. 153 = 13 * 53 * 33 = 153).

 

# include <math.h>

void main()

{

int n,d,x;

int k,i,cube=0;

clrscr();

printf(“\n The following numbers are armstrong numbers.”);

for(k=100;k<=999;k++)

{

  cube=0;

  x=1;

  d=3;

  n=k;

  while(x<=d)

  {

    i=n%10;

    cube=cube+pow(i,3);

    n=n/10;

    x++;

  }

  if(cube==k)

  printf(“\n\t\ %d”,k);

}

}

OUTPUT:

The Following Numbers are Armstrong numbers.

153

370

371

470

Explanation:

The program separates individual digit of number and calculates cubes of each digit. If the sum of the cubes of individual digits of a number is equal to that number, then the number is called Armstrong numbers.

6.38  Write a program to display the stars as shown below.

*

* *

* * *

* * * *

* * * * *

 

void main()

{

int x,i,j;

clrscr();

printf(“How many lines stars (*) should be printed ? :”);

scanf(“%d”,&x);

for(i=1;i<=x;i++)

{

  for(j=1;j<=i;j++)

  {

    printf(“*”);

  }

  printf(“\n”);

}

}

OUTPUT:

How many lines stars (*) should be printed ? : 5

*

* *

* * *

* * * *

* * * * *

Explanation:

Here in the above example, the two for loops are used for displaying as per the format shown in the output. Variables ‘x’, ‘i’ and ‘j’ are used according to the requirement. On the execution of inner loop star/stars are displayed. To display them in different lines the second printf() statement is used.

6.39  Write a program to generate the pattern of numbers as given below.

5 4 3 2 1 0

4 3 2 1 0

3 2 1 0

2 1 0

1 0

0

void main()

{

int i,c=0;

clrscr();

printf(“Enter a Number :”);

scanf(“%d”,&i);

for(;i>=0;i−−)

{

  c=i;

  printf(“\n”);

  for(; 😉

  {

    printf(“%3d”,c);

    if(c==0)

    break;

    c−−;

  }

}

}

OUTPUT:

Enter a number: 6

6 5 4 3 2 1 0

5 4 3 2 1 0

4 3 2 1 0

3 2 1 0

2 1 0

1 0

0

Explanation:

An integer value is read for variable ‘i’. The first for loop decrements the value of ‘i’. The value of ‘i’ is assigned to variable ‘c’. In the second infinite for loop, the value of ‘c’ is printed and decremented. The if condition terminates the infinite for loop when it finds the value of ‘c’ is 0.

6.40  Write a program to display the series of numbers as given below.

1

1 2

1 2 3

1 2 3 4

4 3 2 1

3 2 1

2 1

1

 

void main()

{

int i,j,x;

printf(“\nEnter Value of x :”);

scanf(“%d”,&x);

clrscr();

for(j=1;j<=x;j++)

{

  for(i=1;i<=j;i++)

  printf(“%3d”,i);

  printf(“\n”);

}

printf(“\n”);

for(j=x;j>=1;j−−)

{

  for(i=j;i>=1;i−−)

  printf(“%3d”,i);

  printf(“\n”);

}

}

OUTPUT:

Enter Value of x : 4

1

1 2

1 2 3

1 2 3 4

4 3 2 1

3 2 1

2 1

1

Explanation:

The first two for loops are used to display the first four lines of the output. The next two for loops are used to display the last four lines of the output. The outputs of the first four lines are in ascending order whereas in the last four lines the numbers are in descending order.

6.41  Write a program to generate the pyramid structure using numerical.

void main()

{

int k,i,j,x,p=34;

printf(“\n Enter A number :”);

scanf(“%d”,&x);

clrscr();

for(j=0;j<=x;j++)

{

  gotoxy(p,j+1);

  /* position curosr on screen (x cordinate,y cordinate) */

  for(i=0−j;i<=j;i++)

  printf(“%3d”,abs(i));

  p=p−3;

}

}

OUTPUT:

Enter a number : 3

      0

    1 0 1

  2 1 0 1 2

3 2 1 0 1 2 3

Explanation:

Here, in the above program ‘p’ is equated to 34. This number decides the ‘x’ co-ordinate on the screen from where numbers are to be displayed. The ‘y’ co-ordinate is decided by j+1 where ‘j’ is varying from 0 to the entered number. The value of ‘i’ is negative towards the left of zero. Hence, its absolute value is taken. The inner for loop is executed for displaying digits towards the left and right of zero.

6.42  Write a program to convert a binary number to a decimal number.

void main()

{

int x[5]={1,1,1,1,1};

int y=x[0],i;

clrscr();

printf(“\n Values in different Iterations. \n”);

printf(“====== == ========= ===========\n”);

for(i=0;i<4;i++)

{

  y=y*2+x[i+1];

  printf(“[%d] %d\t”,i+1,y);

}

printf(“\nEquivalent of [”);

for(i=0;i<5;i++)

printf(“%d”,x[i]);

printf(“] in Decimal Number is :”);

printf(“%d\t”,y);

getche();

}

OUTPUT:

Values in different Iterations.

=======================

[1] 3 [2] 7 [3] 15 [4] 31

Equivalent of [1 1 1 1 1] in Decimal Number is : 31

Explanation:

A binary number is initialized in an array. The first element of the array is assigned to variable ‘y’. The logic used here is to multiply by 2 the variable ‘y’ and add the next successive bit. For this the equation y=y*2+x[i+1] is used. The number of iterations to be carried out is equal to the number of binary bits minus 1. Here, five bits are initialized, hence the number of iterations will be four.

6.43  Write a program to add a parity bit with four binary bits such that the total number of one’s should be even.

void main()

{

int bit[5],j,c=0;

clrscr();

printf(“\n Enter four bits :”);

for(j=0;j<4;j++)

{

  scanf(“%d”,&bit[j]);

  if(bit[j]==1)

  c++;

  else

  if(bit[j]>1 || bit[j]<0)

  {

    j−−;

    continue;

  }

}

if(c%2==0) bit[j]=0;

else bit[j]=1;

printf(“\n Message bits together with parity bit :”);

for(j=0;j<5;j++)

printf(“%d”,bit[j]);

}

OUTPUT:

Enter four bits : 1 1 1 1

Message bits together with parity bit : 11110

Explanation:

In the above program, the four binary bits are entered through the keyboard. If the number of one’s entered is even, then the fifth bit is set to 0 otherwise to 1. This is checked by the if statement.

6.44  Write a program to convert a binary to decimal number. Enter the binary bits by using the for loop.

#include <process.h>

void main()

{

int a,b,z[10],i;

clrscr();

printf(“\nEnter the number of bits:−”);

scanf(“%d”,&b);

printf(“\nEnter the binary bits:−”);

for(i=0;i<b;i++)

scanf(“%d”,&z[i]);

a=z[0];

for(i=0;i<(b−1);i++)

{

  a=a*2+z[i+1];

  printf(“\n%d”,a);

}

printf(“\nDecimal Number is : %d”,a);

getche();

}

OUTPUT:

Enter the number of bits:− 5

Enter the binary bits:− 1 0 0 0 1

2

4

8

17

Decimal Number is : 17

Explanation:

In the above program, the number of binary bits is entered. Using this number, individual bits are entered through the keyboard. For this for loop is used. The first element of the array is assigned to variable ‘a’. The logic used here is to multiply by 2 to the variable ‘a’ and add the next successive bit. For this the equation a=a*2+z[i+1]; is used. The number of iterations to be carried out is equal to the number of binary bits minus one. Here, five bits are initialized, hence the number of iterations will be four.

Table 6.5 gives the truth table of logic gates AND, OR and EX-OR.

Table 6.5  Logic gates truth table of AND, OR and EX-OR

6.45  Write a program to verify the truth table of AND Gate. Assume AND Gate has two input bits A and B and one output bit C.

 

void main()

{

int x,a[4],b[4],c[4];

clrscr();

printf(“Enter Four Bits :”);

for(x=0;x<4;x++)

{

  scanf(“%d”,&a[x]);

  if(a[x]>1 ||a[x]<0)

{

  x−−;

  continue;

}

}

printf(“Enter Four Bits :”);

for(x=0;x<4;x++)

{

  scanf(“%d”,&b[x]);

  if(b[x]>1 ||b[x]<0)

{

  x−−;

  continue;

}

}

printf(“\nA B C”);

for(x=0;x<4;x++)

{

  if(a[x]==1 && b[x]==1)

  c[x]=1;

  else

  c[x]=0;

  printf(“\n%d %d %d”,a[x],b[x],c[x]);

}

}

OUTPUT:

Enter Four Bits: 1 0 1 0

Enter Four Bits: 1 0 0 1

A B C

1 1 1

0 0 0

1 0 0

0 1 0

Explanation:

The four binary bits for A and B are entered. The if statement checks the bits of A and B. If both of them are 1 then the output ‘C’ must be 1, otherwise for all other conditions the output is 0.

6.46  Write a program to verify the truth table of OR Gate.

void main()

{

int x,a[4],b[4],c[4];

clrscr();

printf(“Enter Four Bits :”);

for(x=0;x<4;x++)

{

  scanf(“%d”,&a[x]);

  if(a[x]>1 ||a[x]<0)

  {

    x−−;

    continue;

  }

}

printf(“Enter Four Bits :”);

for(x=0;x<4;x++)

{

  scanf(“%d”,&b[x]);

  if(b[x]>1 ||b[x]<0)

  {

    x−−;

    continue;

  }

}

for(x=0;x<4;x++)

{

  if(a[x]==0 && b[x]==0)

  c[x]=0;

  else

  c[x]=1;

  printf(“\n%d %d %d”,a[x],b[x],c[x]);

}

}

OUTPUT:

Enter Four Bits: 1 1 1 0

Enter Four Bits: 1 0 0 0

A B C

1 1 1

1 0 1

1 0 1

0 0 0

Explanation:

The four binary bits for A and B are entered. The if statement checks the bits of A and B. If one of them is at logic 1, then the output ‘C’ must be 1. When the inputs are 0, the output is also 0.

6.47  Write a program to verify the truth table of EX-OR GATE.

void main()

{

int x,a[4],b[4],c[4];

clrscr();

printf(“Enter Four Bits :”);

for(x=0;x<4;x++)

{

  scanf(“%d”,&a[x]);

  if(a[x]>1 ||a[x]<0)

  {

    x−−;

    continue;

  }

}

printf(“Enter Four Bits :”);

for(x=0;x<4;x++)

{

  scanf(“%d”,&b[x]);

  if(b[x]>1 ||b[x]<0)

  {

    x−−;

    continue;

  }

}

printf(“\nA B C”);

for(x=0;x<4;x++)

{

  if(a[x]==0 && b[x]==1)

  c[x]=1;

  else

  if(a[x]==1 && b[x]==0)

  c[x]=1;

  else

  c[x]=0;

  printf(“\n%d %d %d”,a[x],b[x],c[x]);

}

}

OUTPUT:

Enter Four Bits: 1 1 1 0

Enter Four Bits: 1 0 0 0

A B C

1 1 0

1 0 1

1 0 1

0 0 0

Explanation:

The four binary bits for A and B are entered. The if statement checks the bits of A and B. If the input bits are dissimilar the output ‘C’ must be 1. When the inputs are similar, the output is also 0. In the two extreme cases, the output is zero.

6. 48  Write a program to find the Hamming code for the entered binary code. Assume the binary code of four bits in length. The Hamming code should be seven bits.

Tip: R.W. Hamming developed error correcting and detecting codes in communication the four bits data which is to be transmitted containing additional three check bits. The word that is to be transmitted, its format, will be D7, D6, D5, P4, D3, P2 and P1. Where D bits are data bits and the P bits are parity bits. P1 is set so that it provides even parity over bits P1, D3, D5 and D7. P2 is set for even parity over bits P2, D3, D6 and D7. P4 is set for even parity over bits P4, D5, D6 and D7

void main()

{

static int c[7];

int x,b[4];

clrscr();

printf(“\n Read the Binary Numbers :”);

for(x=0;x<4;x++)

scanf(“%d”,&b[x]);

/* piece copy operation */

c[0]=b[0];

c[1]=b[1];

c[2]=b[2];

c[4]=b[3];

printf(“\n Before XOR operation :”);

for(x=0;x<=6;x++)

printf(“%3d”,c[x]);

c[6]= c[0]^c[2]^c[4];

c[5]= c[0]^c[1]^c[4];

c[3]= c[0]^c[1]^c[2];

printf(“\n Hamming code after XOR operation :”);

for(x=0;x<=6;x++)

printf(“%3d”,c[x]);

getche();

}

OUTPUT:

Read the Binary Numbers : 1 0 1 0

Before XOR operation : 1 0 1 0 0 0 0

Hamming code after XOR operation : 1 0 1 0 0 1 0

Explanation:

The hamming code that contains seven bits is initially assumed as zeros. This is declared with static int c[7]. The four bit data is read through the keyboard using the first for loop. The data bits are placed at the appropriate positions using piece copy operations. The three parity bits are evaluated using XOR bitwise operations. Ultimately, the seven bits are displayed using the last for loop.

6.49  Write a program to show the results of students who appeared in the final examination. Assume that the students have to appear in six subjects. The result declared should be as per the following table.

Total Marks

Result

>=420

Distinction

>=360

First Division

>=240

Second Division

Otherwise

Fail

#define DISTINCTION 420

#define FIRST 360

#define SECOND 240

void main()

{

int number,i,j,roll_no,marks,total;

clrscr();

printf(“\n Enter number of Students :”);

scanf(“%d”,&number);

printf(“\n”);

for(i=1;i<=number;++i)

{

  printf(“Enter Roll Number :”);

  scanf(“%d”,&roll_no);

  total=0;

  printf(“\n Enter Marks of 6 Subjects for Roll no %d : \n”,roll_no);

  for(j=1;j<=6;j++)

  {

    scanf(“%d”,&marks);

    total=total+marks;

  }

  printf(“TOTAL MARKS =%d”,total);

  if(total>= DISTINCTION)

  printf(“\n(Distinction)\n\n”);

  else if(total>=FIRST)

  printf(“\n(First Division)\n\n”);

  else if(total>=SECOND)

  printf(“\n(Second Division)\n\n”);

  else

  printf(“\n(***Fail****)”);

}

}

OUTPUT:

Enter number of Students : 1

Enter Roll Number : 1

Enter Marks of 6 Subjects for Roll no 1 :

42 52 62 72 82 92

TOTAL MARKS = 402

(First Division)

Explanation:

In the above program, the number of students whose result is to be calculated is entered. After this, the marks of six subjects with their roll numbers are entered. The sum of six subjects is calculated. The sum is compared with distinction, first and second macros using if–else ladder and appropriate result is displayed.

In this program, macros are used. During preprocessing, the preprocessors replace every occurrence of distinction with 420, similarly, first and second are replaced with 360 and 240, respectively. Distinction, first and second in the above program are ‘macro templates’, whereas 420, 360 and 240 are called their corresponding macro expansions. For details of macros refer to Chapter 12.

6.4  THE while LOOP

Another kind of loop structure in C is the while loop. The while loop is frequently used in programs for the repeated execution of statement/s in a loop. Until a certain condition is satisfied the loop statements are executed.

The syntax of while loop is

 

while(test condition)

{

body of the loop

}

The test condition is indicated at the top and it tests the value of the expression before processing the body of the loop. The test condition may be any expression. The loop statements will be executed till the condition is true, i.e. the test condition is evaluated and if the condition is true, then the body of the loop is executed. When the condition becomes false the execution will be out of the loop.

The execution of the loop can be followed by the following flow chart given in Figure 6.5.

Figure 6.5  The flow chart showing the execution of the loop

Here, the block of the loop may contain either a single statement or a number of statements. The same block can be repeated.

The braces are needed only if, the body of the loop contains more than one statement. However, it is good practice to use braces even if the body of the loop contains only one statement.

6.50  Write a program to print the string ‘You have learnt C program’ nine times using while loop.

 

void main()

{

int x=1;

while(x<10)

{

  printf(“\n You have learnt C program”);

  x++;

}

}

OUTPUT:

You have learnt C program

You have learnt C program

You have learnt C program

You have learnt C program

You have learnt C program

You have learnt C program

You have learnt C program

You have learnt C program

You have learnt C program

Explanation:

The parentheses after ‘while’ contains a condition. As long as the condition remains true, all the statements within the body of the loop get executed repeatedly. The variable ‘x’ is initialized to 1. The compiler checks the condition and after satisfying it, the body of the loop is executed. The control then goes to the while loop. Next time, the value of ‘x’ is incremented by 1. Now if ‘x’ is 2 again it satisfies the condition and the body of the loop gets executed. This process is continued till the value of ‘x’ reaches 9. When the condition becomes false (after 9), the control passes to the first statement that follows the body of the while loop and the program is now terminated. The output of the program is shown above.

6.51  Write a program to add 10 consecutive numbers starting from 1. Use the while loop.

void main()

{

int a=1,sum=0;

clrscr();

while(a<=10)

{

  printf(“%3d”,a);

  sum=sum+a;

  a++;

}

printf(“\n Sum of 10 numbers :%d”,sum);

}

OUTPUT:

1 2 3 4 5 6 7 8 9 10

Sum of 10 numbers : 55

Explanation:

In the above program, integer variable ‘a’ is initialized to 1 and variable ‘sum’ to 0. The while loop checks the condition for a≤10. The variable ‘a’ is added to variable ‘sum’ and each time ‘a’ is incremented by 1. In each while loop ‘a’ is incremented and added to ‘sum’. When the value of ‘a’ reaches 10, the condition given in while loop is false. At last the loop is terminated. The sum of the number is displayed.

6.52 / 6.53  Write a program to calculate factorial of a given number. Use while loop.

void main()

{

int a,fact=1;

clrscr();

printf(“\n Enter The Number :”);

scanf(“%d”, &a);

while(a>=1)

{

  printf(“ %d *”,a);

  fact=fact*a;

  a−−;

}

printf(“ = %d”,fact);

printf(“\n Factorial of Given number is %d”,fact);

}

OUTPUT:

Enter The Number: 5

5* 4 * 3 * 2 * 1 * = 120

Factorial of Given number is 120

Explanation:

In the above program, the working of the while loop is the same as that in the previous one. The only difference is that variable ‘a’ is decremented. Factorial of a number means a product from 1 to that number. Here, variable ‘fact’ is initialized to 1. For each iteration of while loop the entered number is multiplied with the previous value of the variable ‘fact’ and ‘a’ is decremented. When the entered number ‘a’ reaches 1, the while loop terminates and ‘fact’ variable contains the product of 1 to the entered number. Here, the entered number is 5 and its factorial value is 120, and the same is displayed.

 

OR

 

void main()

{

int a,b=1,fact=1;

clrscr();

printf(“\n Enter The Number :”);

scanf(“%d”, &a);

while(b<=a)

{

  printf(“ %d *”,b);

  fact=fact*b;

  b++;

}

printf(“ = %d”,fact);

printf(“\n Factorial of %d is %d”,b−1,fact);

}

OUTPUT:

Enter the Number: 4

1 * 2 * 3 * 4 * = 24

Factorial of 4 is 24.

Explanation:

The working of the above program is the same as the last one. Here, we declared and initialized one more variable ‘b’ to 1. Here, we are keeping the variable ‘a’ unchanged. We require an extra variable to count the number of loops completed by the while loop. Once the value of the variable ‘b’ matches with the entered number ‘a’, the while loop terminates. The factorial of a number in variable ‘fact’ is displayed.

6.54  Write a program to convert decimal number to binary number.

void main()

{

int x,y=40;

clrscr();

printf(“Enter a Number :”);

scanf(“%d”,&x);

printf(“\n Binary Number :”);

while(x!=0)

{

  gotoxy(y−−,3);

  printf(“%d”,x%2);

  x=x/2;

}

}

OUTPUT:

Enter a Number : 25

Binary Number : 11001

Explanation:

In the above program, the number, which is to be converted into binary, is entered through the keyboard. The while loop is executed till the value of ‘x’ becomes non-zero. The body of the while loop contains the mod (%) and divide operations. With these operations, remainders are obtained and the value of ‘x’ is reduced to half. Binary bits corresponding to the decimal number which are obtained are taken in the reverse order by using the gotoxy() function. In the statement gotoxy (y−−, 3), the first argument (y−−) provides the column position and the second provides the row number where the output is to be displayed.

Similarly, for conversion of decimal to octal instead of 2 one can use 8 for mod as well as division operations.

6.55  Write a program to convert decimal number to the user-defined number system. The base of the number system may be taken up to 9.

 

void main()

{

int m,b,y=35;

clrscr();

printf(“Enter the Decimal Number :”);

scanf(“%d”,&m);

printf(“Enter base of number System :”);

scanf “%d”,&b);

printf(“The Number Obtained :”);

while(m!=0)

{

  gotoxy(y−−,3);

  printf(“%d”,m%b);

  m=m/b;

}

getche();

}

OUTPUT:

Enter the Decimal Number : 50

Enter base of number System : 5

The Number Obtained : 200

Explanation:

The logic of the above program is the same as explained in the previous program. The only difference is that the user has a choice to enter the base of any number system. This program is more flexible than the previous one.

6.56  Write a program to convert binary number to equivalent decimal number.

# include <math.h>

# include <process.h>

void main()

{

long n;

int x,y=0,p=0;

clrscr();

printf(“\n Enter a Binary Number :”);

scanf(“%ld”,&n);

while(n!=0)

{

  x=n%10;

  if(x>1 || x<0)

  {

    printf(“\n Invalid Digit.”);

    exit(1);

  }

  y=y+x*pow(2,p);

  n=n/10;

  p++;

}

printf(“\n Equivalent Decimal Number is %d.”,y);

getche();

}

OUTPUT:

Enter a Binary Number : 1111

Equivalent Decimal Number is 15

Enter a Binary Number : 120

Invalid Digit.

Explanation:

In the above program, binary number is entered. The equation y=y+x*pow (2,p) is used in each iteration where y is initialized to 0. The variable x is obtained by mod operation which separates individual digit of entered number, and the variable p acts as an exponent for base 2. It is initially zero and incremented by one in each iteration, where p varies from 0 to the number of digits −1. The product (x*pow (2,p)) is added with the previous value ofy.

6.57  Write a program to read a positive integer number ‘n’ and generate the numbers in the following way. If entered number is 5, the output will be as follows. OUTPUT: 5 4 3 2 1 0 1 2 3 4 5.

 

# include <math.h>

void main()

{

int n,i,k=0;

clrscr();

printf(“Enter a number :”);

scanf(“%d”,&n);

i=n+1; k=k−n;

while(i!=k)

{

  printf(“%3d”,abs(k));

  k++;

}

}

OUTPUT:

Enter a number : 3

3 2 1 0 1 2 3

Explanation:

The value of n  is entered through the keyboard. The variable k is initially declared zero. The equation k=k−n i.e. k=0−n=−n. The value of k is negative, hence abs() function is used to print the positive (absolute) value. The while loop checks the condition for(i!=k). Variable k is printed and incremented till its value becomes n+1. In this way, the numbers are printed as asked in the problem.

6.58  Write a program to enter a number through keyboard and find the sum of its digits.

void main ( )

{

int n,k=1,sum=0;

clrscr();

printf(“Enter a Number :”);

scanf(“%d”,&n);

while(n!=0)

{

  k=n%10;

  sum=sum+k;

  k=n/10;

  n=k;

}

printf(“Sum of digits %d “,sum);

}

OUTPUT:

Enter a Number : 842

Sum of digits 14

Explanation:

In the above program, a number is entered by the user. It is assigned to variable n. In the while loop mod and division operations are done on the entered number. At each rotation of while loop, the remainder is obtained and added to the variable ‘sum’. The original number is also reduced by the division operation. Due to continuos division, at one stage the entered number reduces to zero. At this stage, the while loop condition mismatches and is terminated. The variable ‘sum’ displays the ‘sum’ of all digits of the entered number.

6.59  Write a program to enter few numbers and count the positive and negative numbers together with their sums. When 0 is entered program should be terminated.

 

void main()

{

int j=1,p=0,n=0,s=0,ns=0;

clrscr();

printf(“\n Enter Numbers (0) Exit :”);

while(j!=0)

{

  scanf(“%d”,&j);

  if(j>0)

  {

    p++;

    s=s+j;

  }

  else if(j<0)

  {

    n++;

    ns=ns+j;

  }

}

printf(“\n Total Positive Numbers : %d”,p);

printf(“\n Total Negative Numbers : %d”,n);

printf(“\n Sum of Positive Numbers : %d”,s);

printf(“\n Sum of Negative Numbers : %d”,ns);

}

OUTPUT:

Enter Numbers (0) Exit :1 2 3 4 5 −5 −4 −8 0

Total Positive Numbers : 5

Total Negative Numbers : 3

Sum of Positive Numbers : 15

Sum of Negative Numbers : −17

Explanation:

Numbers are entered through the keyboard. The if statement checks whether the entered numbers are greater or less than zero. If the numbers are greater than zero the if block is executed otherwise the else block is executed. The output shows the number of positive and negative numbers and their sums. When 0 is entered while loop terminates.

6.60  Read an integer through the keyboard. Sort odd and even numbers by using while loop. Write a program to add the sum of odd and even numbers separately and display the results.

 

void main()

{

int a,c=1,odd=0,even=0;

float b;

clrscr();

printf(“Enter a Number :”);

scanf(“%d”, &a);

printf(“ODD EVEN”);

printf(“\n”);

while(c<=a) /* A

{

  b=c%2;

  while(b==0) {/* B

  printf(“\t%d “,c);

  even=even+c;

  b=1;}

  b=c%2;

  while(b!=0){ /*c

  printf(“\n%d”,c);

  odd=odd+c;

  b=0;}

  c++;

}

printf(“\n===============”);

printf(“\n%d %d”,odd,even);

}

OUTPUT:

Enter a Number: 10

ODD
EVEN
1
2
3
4
5
6
7
8
9
10
==========
25
30

Explanation:

The above program is an example of nested while loops. When the entered number is even the first loop (B loop) is executed and number is added to variable ‘even’, otherwise the while loop (C loop) is executed and the same job of addition is done with variable ‘odd’. Thus, variables ‘odd’ and ‘even’ give the sum of even and odd numbers.

6.61  Write a program to print the entered number in the reversed order.

void main ()

{

int n,d,x=1;

int i;

clrscr();

printf(“Enter the number of digits :−”);

scanf(“%d”,&d);

printf(“\nEnter the number which is to be reversed:−”);

scanf(“%d”,&n);

printf(“\nThe Reversed Number is :−”);

while(x<=d)

{

  i=n%10;

  printf(“%d”,i);

  n=n/10;

  x++;

}

getche();

}

OUTPUT:

Enter the number of digits :− 4

Enter the number which is to be reversed:− 5428

The Reversed Number is :− 8245

Explanation:

The statements following the while loop are i=n%10 and n=n/10. They provide the remainder and quotient values, respectively. By taking repeatedly remainders and quotients, we get the number in the reverse order. For repeating the loop the x is to be incremented.

6.62  Write a program to enter a statement entering a combination of capital, lower case, symbols and numerical. Carry out separation of capitals, lower case, symbols and numerical by using ASCII values from 48 to 122.

 

# include <ctype.h>

void main()

{

static char scan [40], cap[20],small[20],num[20],oth[20];

int i=0,c=0,s=0,h=0,n=0;

clrscr();

puts(“Enter Text Here :\n”);

gets(scan);

while(scan[i]!=‘\0’)

{

  if(scan[i]>=48 && scan[i]<=57)

  num[++n]=scan[i];

  else

  if(scan[i]>=65 && scan[i]<=90)

  cap[++c]=scan[i];

  else

  if(scan[i]>=97 && (scan[i]<=122))

  small[++s]=scan[i];

  else

  oth[++h]=scan[i];

  i++;

}

printf(“\nCapital Letters :[”);

for(i=0;i<20;i++)

printf(“%c”,cap[i]);

printf(“]\nSmall Letters :[”);

for(i=0;i<20;i++)

printf(“%c”,small[i]);

printf(“]\nNumaric Letters :[”);

for(i=0;i<20;i++)

printf(“%c”,num[i]);

printf(“]\nOther Letters :[”);

for(i=0;i<20;i++)

printf(“%c”,oth[i]);

printf(“]”);

getche( );

}

OUTPUT:

Enter Text Here: HAVE A NICE DAY, contact me on 51606.

Capital Letters: [HAVEANICEDAY]

Small Letters : [contactmeon]

Numaric Letters : [28669]

Other Letters: [,]

Explanation:

The array scan[40]contains the string. The string is to be entered by the user. The arrays small[20], num[20] and oth[20] are used at run time in the program. The while loop reads the array scan[] character by character. The if-else ladder statements check the characters, whether the character is small, capital or symbol, and assigns it to the different arrays according to its case or type.

6.63 /6.64  Write a program to sort numbers 0 to 9, alphabets in upper and lower case using equivalent ASCII values. The following table can be used.

ASCII values

Corresponding Symbols

48 to 57

0 to 9

65 to 90

A to Z

97 to 120

a to z

void main()

{

char a;

int i=48;

clrscr();

printf(“NUMBERS \n”);

while(i<=57)

{

  printf(“%c”,i);

  i++;

}

i+=7;

printf(“\n\n CAPITAL ALPHABETS\n”);

while(i<=90)

{

  printf(“ %c”,i);

  i++;

}

i+=6;

printf(“\n\n SMALL ALPHABETS \n”);

while(i<=122)

{

  printf(“%c”,i);

  i++;

}

}

OUTPUT:

NUMBERS

0 1 2 3 4 5 6 7 8 9

CAPITAL ALPHABETS

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

SMALL ALPHABETS

a b c d e f g h i j k l m n o p q r s t u v w x y z

Explanation:

In the above program, three while loops are used. These three while loops are used for sorting numbers, capital letters and lowercase letters. The variable ‘i’ is initialized to 48 because the ASCII 48 is ‘0’. The three while loops check ASCII values as per the ranges given in the table. The number, capital and small letters are not continuous in ASCII. Some symbols are also present between these values. To ignore these symbols, variable ‘i’ is increased twice with 7 and 6.

 

OR

 

#include <process.h>

void main()

{

int i=48;

clrscr();

printf(“Numbers :”);

while(i<124)

{

  if(i<58)

  printf(“%2c”,i);

  else

  {

    if(i==58)

    {

      printf(“\nCapital Letters :”);

      i+=7;

    }

    if(i>64 && i<91)

    printf(“%2c”,i);

    if(i==90)

    {

      printf(“\n Small Letters :”);

      i+=7;

    }

    if(i>96 && i<123)

  printf(“%2c”,i);

  }

  i++;

}

}

Explanation:

The output of the above program is the same as for the previous one. Instead of nested while loop, nested if-else statements are used.

6.65  Write a program to use three while nested loops. Print numbers after each iteration and messages after termination of each loop.

 

void main()

{

int i=1,j=1,k=1;

clrscr();

while(i<4)

{

  while(j<3)

  {

    while(k<2)

    {

      printf(“\n\n i=%d j=%d k=%d”,i,j,k);

      k++;

    }

    printf(“\n Inner Loop (k) Completed.”);

    k=1;

    j++;

  }

  printf(“\n Middle Loop (j) Completed.”);

  j=1;

  i++;

}

printf(“\n Outer Loop (i) Completed.”);

}

OUTPUT:

i=1 j=1 k=1

Inner Loop (k) Completed.

i=1 j=2 k=1

Inner Loop (k) Completed.

Middle Loop (j) Completed.

i=2 j=1 k=1

Inner Loop (k) Completed.

i=2 j=2 k=1

Inner Loop (k) Completed.

Middle Loop (j) Completed.

i=3 j=1 k=1

Inner Loop (k) Completed.

i=3 j=2 k=1

Inner Loop (k) Completed.

Middle Loop (j) Completed.

Outer Loop (i) Completed.

Explanation:

In the above program, variables i, j and k are declared and initialized to 1. The inner most loop is ‘k’, the middle is ‘j’ and the outer most is ‘i’. The execution of loop starts from outer to inner and the completion will be from inner most to the outer most. Here, for example, the values of i, j and k are printed and messages are printed to understand the termination of loops.

6.5  THE do-while LOOP

The syntax of do-while loop in C is as follows.

 

do

{

statement/s;

}

while(condition);

The difference between the while and do-while loop is the place where the condition is to be tested. In the while loops the condition is tested following the while statement, and then the body gets executed, whereas in the do-while the condition is checked at the end of the loop. The do-while loop will execute at least one time even if the condition is false initially. The do-while loop executes until the condition becomes false. The comparison between the while and do-while loop is given in Table 6.6

Some programs are given on do-while loop.

Table 6.6  Comparison of the while and do-while loop

Sr. No.

while Loop

do-while Loop

1

Condition is specified at the top.

Condition is mentioned at the bottom.

2

Body statement/s is/are executed when condition is satisfied.

Body statement/s executes even when the condition is false.

3

No brackets for a single statement.

Brackets are essential even when a single statement exits.

4

It is an entry-controlled loop.

It is an exit-controlled loop.

6.66  Use the do-while loop and display a message ‘this is a program of do-while loop’ five times.

 

void main()

{

int i=1;

clrscr();

do

{

  printf(“\n This is a program of do while loop.”);

  i++;

}

while(i<=5);

}

OUTPUT:

This is a program of do while loop.

This is a program of do while loop.

This is a program of do while loop.

This is a program of do while loop.

This is a program of do while loop.

Explanation:

The body of the loop is executed and the value of ‘i’ is incremented. The incremented value is tested with the condition specified at the outside of the loop. If the condition is true the statement within the loop gets executed. In the above program, the statement within the loop gets executed five times and the result is as shown above.

6.67  Write a program to print the entered number in the reversed order. Use do-while loop. Also perform sum and multiplication with their digits.

 

void main()

{

int n,d,x=1,mul=1,sum=0;

int i;

clrscr();

printf(“Enter the number of digits :-”);

scanf(“%d”,&d);

printf(“\nEnter the number which is to be reversed:-”);

scanf(“%d”,&n);

printf(“\n Reversed Number :-”);

do

{

  i=n%10;

  printf(“%d”,i);

  sum=sum+i;

  mul=mul*i;

  n=n/10;

  x++;

}

while(x<=d);

printf(“\n Addition of digits :- %4d”,sum);

printf(“\n Multiplication of digits :- %4d”, mul);

getche();

}

OUTPUT:

Enter the number of digits : 4

Enter the number which is to be reversed:- 4321

Reversed Number :- 1234

Addition of digits :- 10

Multiplication of digits :- 24

Explanation:

In the above program, the length of the number and a number are entered. Using repetitive mod operations, digits are separated and displayed. The separated digits are repeatedly added and multiplied with variables ‘sum’ and ‘mul’, respectively. Initially ‘sum’ is 0 and ‘mul’ is 1. After the termination of loop ‘sum’ and ‘mul’ display addition and multiplication of individual digits of the entered number.

6.68  Write a program to find the cubes of 1 to 10 numbers using do-while loop.

 

/* This is a program of cube of a given number */

#include “math.h”

void main()

{

int y,x=1;

clrscr();

printf(“\n Print the numbers and their cubes”);

printf(“\n”);

do

{

  y=pow(x,3);

  printf(“%4d %27d\n”,x,y);

  x++;

}

while(x<=10);

}

OUTPUT:

Print the numbers and their cubes

1

1

2

8

3

27

4

64

5

125

6

216

7

343

8

512

9

729

10

1000

Explanation:

Here, the mathematical function pow (x, 3) is used. Its meaning is to calculate the third power of x. With this function, we get the value of y=x3. For the use of the pow () function, we have to include math.h header file.

6.69  Write a program to check whether the given number is prime or not?

 

void main()

{

int n,x=2;

clrscr();

printf(“Enter The number for testing (prime or not) :”);

scanf(“%d”,&n);

do

{

  if(n%x==0)

  {

    printf(“\n The number %d is not prime.”,n);

    getch();

    exit(0);

  }

  x++;

}

while(x<n);

printf(“\n The number %d is prime.”,n);

getche();

}

OUTPUT:

Enter The number for testing (prime or not) : 5

The number 5 is prime.

Explanation:

The number is said to be a prime number, if it is not divisible by any number starting from 2 onwards up to n-1, where n is the entered number by the user. Here, in this example, the entered number is 5. The mod operation is performed using the divisor from 2 to n-1 (5−1).

If the remainder is 0 then it is not a prime number and controls exit from the program. Otherwise, if the remainder is non-zero then the number is prime.

6.70  Write a program to count the number of students having age less than 25 and weight less than 50 kg out of five.

 

void main()

{

int age,count=0,x=1;

float wt;

clrscr();

printf(“\nEnter data of 5 boys\n”);

printf(“\nAge Weight\n”);

do

{

  scanf(“%d %f”, &age, &wt);

  if( age<25 && wt<50)

  {

    count++;

  }

x++;

}

while(x<=5);

printf(“\n Number of boys with age <25”);

printf(“and weight <50 Kgs =%d\n”,count);

getch();

}

OUTPUT:

Enter data of 5 boys

Age Weight

24

51

20

45

25

51

20

35

24

54

Number of boys with age <25 and weight <50 kgs = 2

Explanation:

In the above-given program, age and weight of five boys are entered. The if condition checks the age and weight and after satisfying the condition counter variable count is increased by one. Thus, loop executes five times. The program displays the number of students having ages less than 25 years and weight less than 50 kg.

6.71  Compute the factorial of a given number using the do-while loop.

 

void main()

{

int a,fact=1;

clrscr();

printf(“\n Enter The Number :”);

scanf(“%d”, &a);

do

{

  printf(“ %d *”,a);

  fact=fact*a;

  a- -;

}

while(a>=1);

printf(“ = %d”,fact);

printf(“\n Factorial of Given number is %d”,fact);

}

OUTPUT:

Enter The Number : 5

5 * 4 * 3 * 2 * 1 * = 120

Factorial of Given number is 120.

Explanation:

The logic of the program is self-explanatory.

6.72  Write a program to evaluate the series such as 1+2+3+. . . i. Use do-while loop. Where i can be a finite value. Its value should be read through the keyboard.

 

void main()

{

int i,a=1;

int s=0;

clrscr();

printf(“\n Enter a number:”);

scanf(“%d”,&i);

do

{

  printf(“%d +”,a);

  s=s+a;

  a++;

}

while(a<=i);

printf(“\b\bs=%d”,s);

}

OUTPUT:

Enter a number: 5

1 + 2 + 3 + 4 +5 s= 15

Explanation:

In the above program, variable ‘a is initially 1 and s is 0. The value of variable ‘i’ is read which determines the final step of the series. In the do-while loop variable a is printed, added to variable s and then incremented. This loop is continuously executed till a equals the entered number i. The output provides the summation of 1 to the entered number. Here, the entered number is 5. Hence, the sum from 1 to 5 is 15.

6.6  THE while LOOP WITHIN THE do-while LOOP

The syntax of do-while with multiple while statement loop is as follows:

do-while(condition)

 

{

statement/s;

}

while(condition);

6.73  Write a program to use while statement in do-while loop and print values from 1 to 5.

 

void main()

{

int x=0;

clrscr();

do while(x<5)

{

  x++;

  printf(“\t %d”,x);

}

while(x<1);

}

OUTPUT :

1 2 3 4 5

Explanation :

The specialty of using the second while loop in the above program is to know that the programmer can take the second while loop.

6.7  BOHM AND JACOPINI’S THEORY

The structured programming provides simplicity. Bohm and Jacopini showed the following three forms of controls:

  1. sequence
  2. selection
  3. repetition

Sequence means statements appearing one after another. Recall that in the last chapter, we learned that selection can be implemented using if-else and switch statements. Now in this chapter, we learned that repetition can be implemented using for, while and do-while statements. goto instructions can be used by using if and while, for and do-while, i.e., C language includes if and other loop control structures which are equivalent to the same with goto.

All the above controls can be combined by two ways: (i) stacking and (ii) nesting. Thus, the structured programming supports simplicity.

SUMMARY

This chapter deals with the loops that are to be used in the C programs. The scope of the various three loops such as (i) the for loop, (ii) the while loop and (iii) the do-while has been narrated in detail in this chapter. In this chapter the numbers of solved programs on these loops have been given for the benefit of the programmers. Also examples on nested loops have been given in a simple language and in depth. The information on breaking the loop and continuing the same is also elaborated in detail together with examples.

EXERCISES

I  True or false:

  1. A loop repeatedly executes a block of statements for certain number of times.
  2. The loop for(; 😉 is a non-working loop.
  3. The for(; 😉 loop with no arguments can be executed.
  4. The loop for(a=1;a<20;a++) will be executed for 20 times.
  5. The while (1) is an infinite loop.
  6. The loop cannot be nested.
  7. Even if the condition is false the do-while loop executes once.
  8. The do-while loop must be terminated by a semi-colon.
  9. The {} defines the block of the statement.
  10. In case {} is not defined, the default scope is one statement

II  Match the following correct pairs given in Group A with Group B:

  1.  

  2.  

III  Select the appropriate option from the multiple choices given below:

  1. What will be the last value of ‘c’ after the execution of following program? s

    void main()

    {

    int c=1,d=0;

    clrscr();

    while(d<=9)

    {

      printf(“\n %d %d”,++d,++c);

      }

    }

    1. 11
    2. 10
    3. 12
    4. 9
  2. What will be the value of ‘x’ after the execution of following program?

    void main()

    {

    int k;

    float x=0;

    clrscr();

    for(k=0;k<10;k++)

    x+=.1;

    printf(“\nx=%g”,x);

    }

    1. x=1
    2. x=0
    3. x=1.1
    4. None of the above
  3. What will be the value of ‘f’ after the execution of following program?

    void main()

    {

    char k;

    float f=65;

    clrscr();

    for(k=1;k<=10;k++)

    {

      f-=.1;

    }

    printf(“\nf=%g”,f);

    }

    1. f=64
    2. f=-65
    3. f=66
    4. None of the above
  4. What would be the final value of ‘x’ after the execution of the following program?

    void main()

    {

    int x=1;

    clrscr();

    do while(x<=10)

    {

      x++;

    }

    while(x<=5);

    printf(“\n x=%d”,x);

    }

    1. x=11
    2. x=6
    3. x=2
    4. None of the above
  5. How many while statements are possible in the do-while loop?
    1. 2
    2. 1
    3. 3
    4. None of the above
  6. What will be the final values of x and y?

    void main()

    {

    int x=1,y=1;

    clrscr();

    do while(x<=8)

    {

      x++,y++;

    }

    while(y<=5);

    printf(“\n x=%d y=%d”,x,y);

    }

    1. x=9 y=9
    2. x=9 y=6
    3. x=6 y= 6
    4. None of the above

IV  Attempt the following programs:

  1. Write a program to display alphabets as given below.

    Az by cx dw ev fu gt hs Ir jq kp lo mn nm ol pk qj ri sh tg uf ve wd xc yb za.

  2. Write a program to display count values from 0 to 100 and flash each digit for one second. Reset the counter after it reaches to hundred. The procedure is to be repeated. Use for loop.
  3. Develop a program to simulate seconds in a clock. Put the 60 dots on the circle with equal distance between each other and mark them 0 to 59. A second’s pointer is to be shown with any symbol. Also print the total number of revolution made by second’s pointer.
  4. Write a program to simulate analog watch (1 to 12 numbers to be arranged in circular fashion with all the three pointers for seconds, minutes, and hours) on the screen. Use nested for loops.
    1. Use (.) dot for second’s pointer.
    2. Use (*) star for minute’s pointer.
    3. Use (#) hash for hour’s pointer.
  5. Write a program to calculate the sum of first and last number from 1 to 10.

    (Example 1+10,2+9, 3+8 sums should be always 11.)

  6. Write a program to find the total number of votes in favour of persons ‘A’ and ‘B’. Assume 100 voters will be casting their votes to these persons. Count the number of votes gained by ‘A’ and ‘B’. User can enter his/her choices by pressing only ‘A’ or ‘B’.
  7. Write a program to pass the resolution in a meeting comprising of five members. If three or more votes are obtained the resolution is passed otherwise rejected.
  8. Assume that there are 99 voters voting to a person for selecting chairman’s candidature. If he secures more than 2/3 votes he should be declared as chairman otherwise his candidature will be rejected.
  9. Write a program to display the numbers of a series 1, 3, 9, 27, 81. . . . n by using the for loop.
  10. Write a program to check that entered input data for the following. Whenever input is non-zero or positive display numbers from 1 to that number, otherwise display message ‘negative or zero’. The program is to be performed for 10 numbers.
  11. Write a program to check entered data types for 10 times. If a character is entered print ‘Character is entered’ otherwise ‘Numeric is entered’ for numerical values.
  12. Write a program to find the sum of the first hundred natural numbers. (1+2+3+ . . . +100).
  13. Write a program to display numbers 11, 22, 33. . . , 99 using ASCII values from 48 to 57 in loops.
  14. Create an infinite for loop. Check each value of the for loop. If the value is odd, display it otherwise continue with iterations. Print even numbers from 1 to 100. Use break statement to terminate the program.
  15. Write a program to show the display as a rectangle of characters as shown below.

     

    Z
    YZY
    XYZYX
    RXYZYXR
    XYZYX
    YZY
    Z

     

  16. Write a program to read 10 numbers through the keyboard and count number of positive, negative and zero numbers.
  17. Write a nested for loop that prints a 5 × 10 pattern of 0s.
  18. Is it possible to create a loop using the goto statement? If yes write the code for it.
  19. Write a program to find the triangular number of a given integer. Fox example triangular of 5 is (1+2+3+4+5) 15. Use do-while loop.
  20. Write a program to display all ASCII numbers and their equivalent characters numbers and symbols. Use do-while loop. User should prompt every time to press ‘Y’ or ‘N’. If user presses ‘Y’ display next alphabet otherwise terminate the program.
  21. Accept any five two numbers. If the first number is smaller than the second then display sum of their squares, otherwise sum of cubes.
  22. Evaluate the following series. Use do-while loop.
    1. 1+3+5+7. . . . n
    2. 1+4+25+36 . . . n
    3. x+x2/2!+x3/3!+ . . n
    4. 1+x+x2+x3+. . . . xn
  23. Write a program to display the following, using do-while loop.
    1. a+1+b+2+c+3. . . .n, where n is an integer.
    2. z+y+x. . .+a.
    3. za+yb+xc. . .+az.
  24. Enter the 10 numbers through the keyboard and sort them in ascending and descending order, using do-while loop.
  25. Enter text through the keyboard and display it in the reverse order. Use do-while loop.
  26. Print multiplication of digits of any number. Fox example number 235, multiplication to be 5*3*2 = 30. Use do-while loop.
  27. Print square roots of each digit of any number. Consider each digit as perfect square. For example, for 494 the square roots to be printed should be 2 3 2.
  28. Write a program to read a positive integer number ‘n’ and generate the numbers in the following way. If entered number is 3 the output will be as follows.
    1. 9 4 1 0 1 4 9
    2. 9 4 1 0 1 2 3
  29. Write a program to enter two integer values through the keyboard. Using while loop, perform the product of two integers. In case product is zero (0), loop should be terminated otherwise loop will continue.
  30. Write a program to enter a single character either in lower or uppercase. Display its corresponding ASCII equivalent number. Use the while loop for checking ASCII equivalent numbers for different characters. When capital ‘E’ is pressed, the program should be terminated.
  31. Write a program to read a positive integer number ‘n’ and generate the numbers in the following way. If entered number is 4 the output will be as follows. OUTPUT: 4! 3! 2! 1! 0 1! 2! 3! 4! 5!.
  32. Write a program to read a positive integer number ‘n’ and generate the numbers in the different ways as given below. If the entered number is 4 the output will be as follows.
    1. 2 4 6 8 10 . . . n (provided n is even).
    2. 1 3 5 7 9. . . . n (provided n is odd).
  33. Write a program to read a positive integer number ‘n’ and perform the squares of individual digits. For example n=205 then the output will be 25 0 4.
  34. What would be the output of the given below programs?
    1. void main()

      {

      while(0)

      {

        printf(“\n Hello”);

      }

      }

    2. void main()

      {

      while(!0)

      {

        printf(“\n Hello”);

      }

      }

    3. void main()

      {

      while(!1)

      {

        printf(“\n Hello”);

      }

      }

    4. void main()

      {

      while(! NULL)

      {

        printf(“\n %s”,“Hello”);

      }

      }

    5. void main()

      {

      while(“ ”)

      {

        printf(“\n %s”,“Hello”);

      }

      }

  35. What will be the output of the below given program? Attempt this program with other keywords and functions. List the names of keywords and functions, which can be used as arguments in the while loop.

    void main()

    {

    while(main)

    {

      printf(“\n %d”,main);

    }

V  Find the bug/s in the following program/s:

  1. void main()

    {

    int n=1;

    clrscr();

    while(n<10);

    {

      printf(“%d”,n);

      n=n+3;

    }

    getche();

    }

  2. void main()

    {

    int n;

    clrscr();

    printf(“Enter the number up to 8:-”);

    scanf(“%d”,n);

    while(n<9)

    {

      printf(“%d”,);

      n=n+1;

    }

    getche();

    }

  3. void main()

    {

    int k=1;

    clrscr();

    do;

    {

      printf(“\n %d”,k);

      k=k+1;

    }

    while(k<=5);

    getche();

    }

  4. void main()

    {

    chr i=65;

    clrscr();

    do

    {

      printf(“ %c”,i)

      i=i+1;

    }

    while(i<=90);

    getche();

    }

  5. void main()

    {

    int num=678,sum=0,rev=0,digit;

    clrscr();

    do

    {

      digit=num-num\10*10;.

      num=num/10;

      rev=rev*10+digit;

      sum=sum+digit;

    }

    while(num>0);

    printf(“\n %d”,rev);

    printf(“\n”);

    printf(“\n %d”,sum);

    getche();

    }

  6. void main()

    {

    int i,j=1,n=4;

    float sum=1.0;

    clrscr();

    for(i=1;i<=n;i++)

    {

      j=j*i;

      sum=sum+i/j;

    }

    printf(“\n %.2f”,sum);

    getche();

    }

  7. void main()

    {

    int i=10;

    clrscr();

    do

    {

      printf(“%d”,i);

      i=i-1;

    }

    while(i>0 || i=5);

    getche();

    }

  8. void main()

    {

    int x=7,y=0,z=7,i;

    clrscr();

    for(i=0;i<=x;i++);

    {

      y=x+i*z;

      printf(“%d”,y);

    }

    getche();

    }

VI  Answer the following questions:

  1. What happens if you create a loop that never ends?
  2. Is it possible to create a for loop that is never executed?
  3. What is a loop? Why it is necessary in a program?
  4. Is it possible to nest while loop within for loops?
  5. How do you choose between while and for loops?
  6. What is the difference between (!0) and (!1). How while loop works with these values?
  7. What is the difference between (1= =! 1) and (1! =1)?
  8. What is the difference between (! 0) and (! 0)?
  9. What are the values of NULL and ! NULL?
  10. Is it possible to use multiple while statements with Do statement?
  11. Explain Bohm and Jacopini’s theory.
ANSWERS

I  True or false:

Q.
Ans.

1.

T

2.

F

3.

T

4.

F

5.

T

6.

F

7.

T

8.

T

9.

T

10.

T

II  Match the following correct pairs given in Group A with Group B:

  1. Q.
    Ans.

    1.

    C

    2.

    A

    3.

    B
  2. Q.
    Ans.

    1.

    B

    2.

    C

    3.

    A

III  Select the appropriate option from the multiple choices given below:

Q.
Ans.

1.

a

2.

a

3.

a

4.

a

5.

a

6.

a

V  Find the bug/s in the following program/s:

Q.
Ans.

1.

Semi-colon at the end of while loop is not expected program runs with this semi-colon, but nothing appears on screen on execution.

2.

& is missing in scanf and n variable in printf statements.

3.

Semi-colon is not expected in do.

4.

chr should replace with char & semi-colon is missing in printf.

5.

Instead of “\” division “/” is expected in digit statement.

6.

(float)i/j is expected in sum statement, if correct result is required otherwise the program gives runs but result given will be wrong.

7.

i= =5 is expected.

8.

Omit semi-colon from for statement if correct result is required.