Wednesday, October 7, 2020

Assignment 3. Loop Control Structures

  Assignment 3. Loop Control Structures 

Looping statement are the statements execute one or more statement repeatedly several number of times. In C programming language there are three types of loops; while, for and do-while.

 

Why use loop ?

When you need to execute a block of code several number of times then you need to use looping concept in C language.

 

Advantage with looping statement

1.       Reduce length of Code

2.       Take less memory space.

3.       Burden on the developer is reducing.

4.       Time consuming process to execute the program is reduced.

Types of Loops.

There are three type of Loops available in 'C' programming language.

 ·         while loop

·         for loop

·         do..while

Difference between conditional and looping statement

Conditional statement executes only once in the program where as looping statements executes repeatedly several number of time.

 1.       While loop

In While Loop in C First check the condition if condition is true then control goes inside the loop body other wise goes outside the body. while loop will be repeats in clock wise direction.

Syntax:-

while(condition)

{

Statements;

......

Increment/decrements (++ or --);

}

  Example of while loop

#include<stdio.h>

void main()

{

int i;

clrscr();

i=1;

while(i<5)

{

printf("\n%d",i);

i++;

}

}

 

Output

1

2

3

4


 2.       do while loop

In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement. It means that the body of the loop will be executed at least once, even though the starting condition inside while is initialized to be false. General syntax is,

 

do

{

    .....

    .....

}

while(condition)

 Example: Program to print first 10 multiples of 5.

#include<stdio.h>

void main()

{

    int a, i;

    a = 5;

    i = 1;

    do

    {

        printf("%d\t", a*i);

        i++;

    }

    while(i <= 10);

}

OUTPUT:-

5 10 15 20 25 30 35 40 45 50

 

 DIFFERENCE BETWEEN WHILE & DO WHILE LOOPS IN C LANGUAGE:

·         While Loop is executed only when condition is true.

·         do while Loop is executed for first time irrespective of the condition. After executing while loop for first time, then condition is checked.

 

 3.       for loop

for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. We can say it is an open ended loop.. General format is,

Syntax:-

for(initialization; condition; increment/decrement)

{

    statement-block;

}

In for loop we have exactly two semicolons, one after initialization and second after the condition. In this loop we can have more than one initialization or increment/decrement, separated using comma operator. But it can have only one condition.

 The for loop is executed as follows:

1.       It first evaluates the initialization code.

2.       Then it checks the condition expression.

3.       If it is true, it executes the for-loop body.

4.       Then it evaluate the increment/decrement condition and again follows from step 2.

5.       When the condition expression becomes false, it exits the loop.

 

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )

{

    int x;

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

    {

        printf("%d\t", x);

    }

}

OUTPUT:-

1 2 3 4 5 6 7 8 9 10

 

Nested for loop

We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is,

for(initialization; condition; increment/decrement)

{

    for(initialization; condition; increment/decrement)

    {

        statement ;

    }

}

 

Example: Program to print half Pyramid of numbers

#include<stdio.h>

void main( )

{

    int i, j;

    /* first for loop */

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

    {

        printf("\n");

        /* second for loop inside the first */

        for(j = i; j > 0; j--)

        {

            printf("%d", j);

        }

    }

}

OUTPUT

1

2 1

3 2 1

4 3 2 1

5 4 3 2 1

 

Jumping Out of Loops

Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becomes true. This is known as jumping out of loop.

 

1) break statement

When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop.  

2) continue statement

It causes the control to go directly to the test-condition and then continue the loop process. On encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.


Assignments:- 

Set A .

 1. Write a program to accept an integer n and display all even numbers upto n.

#include<stdio.h>

void main()

{

int n,i;

printf("\nEnter Number:");

scanf("%d",&n);

printf("\neven numbers upto %d ",n);

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

{

if(i%2==0)

printf("\n%d",i);

}

}


2. Accept two integers x and y and calculate the sum of all integers between x and y (both inclusive) 

#include <stdio.h>
void main()
{
    int a = 1;
    int b = 0;
    int total_sum = 0;
    while (a > b)
 {
        printf("The second number should be bigger than the first one.\n");
        printf("Type the first number : \n");
        scanf("%d", &a);
        printf("Type the second number : \n");
        scanf("%d", &b);
    }
    while (a<= b)
 {
        total_sum += a;
        a++;
    }
    printf("Result : %d\n", total_sum);
}

3. Write a program to accept two integers x and n and compute xn 

#include<stdio.h>

void main()

{

int x,n,i,ans=1;

printf("\nEnter number and power:");

scanf("%d%d",&x,&n);

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

{

ans=ans*x;

}

printf("\n%d power %d is : %d ",x,n,ans);

}

4. Write a program to accept a character, an integer n and display the next n characters.

#include<stdio.h>

void main()

{

int n;

char c;

printf("\nEnter charcter:");

scanf("%c",&c);

printf("\nEnter Number:");

scanf("%d",&n);

printf("\nNext %d char is :",n);

while(n>0)

{

c=c+1;

printf("\n%c",c);

n--;

}

}

 5. Write a program to accept an integer and check if it is prime or not.

#include<stdio.h>
int main()
{
    int n, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d",&n);

    for(i=2; i<=n/2; ++i)
    {
        if(n%i==0)
        {
            flag=1;
            break;
        }
    }

    if (flag==0)
        printf("%d is a prime number.",n);
    else
        printf("%d is not a prime number.",n);
}

 6. Write a program to accept an integer, count number of digits and calculate sum of digits in the number. Example: Number = 1234 Output: Digits = 4, Sum = 10 

#include<stdio.h>
int main()
{
int a,j=0,p,sum=0;
printf("enter the no : ");
scanf("%d",&a);
while(a!=0)
{
p=a%10;
a=a/10;
j++;
sum=sum+p;
}
printf("digit= %d and sum= %d",j,sum);
}

7. Write a program to accept an integer and reverse the number. Example: Input: 546, Reverse = 645. 

#include<stdio.h>
int main()
{
int a,j=0,p;
printf("enter the no : ");
scanf("%d",&a);
printf("reverse= ");
while(a!=0)
{
p=a%10;
a=a/10;
j++;
printf("%d",p);
}
}

Set B. 

 1. Write a program to display the first n Fibonacci numbers. (1 1 2 3 5 ……) 

#include<stdio.h>

void main()

{

int n,a=1,b=1,c;

printf("\nEnter Nuumber:");

scanf("%d",&n);

if(n==1)

printf("\n%d",a);

if(n>=2)

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

while(n>2)

{

c=a+b;

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

a=b;

b=c;

n--;

}

}


2. Write a program to accept real number x and integer n and calculate the sum of first n terms of the series x+ 3x+5x+7x+… 

#include<stdio.h>

void main()

{

int x,n,i,t=1;

float ans=0;

printf("\nEnter real number and terms ");

scanf("%d%d",&x,&n);

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

{

ans=ans+t*x;

t=t+2;

}

printf("\n Sum of %d terms of series is %f",n,ans);

}

3. Write a program to accept real number x and integer n and calculate the sum of first n terms of the series 1/x + 2/x^2 + 3/x^3 + …

#include<stdio.h>
int main()
{
int x,n,i,j;
float sum=0,p,m;
printf("enter value of x : ");
scanf("%d",&x);
printf("enter limit n : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
m=x;
for(j=1;j<i;j++)
{
m=(m*x);
}
p=i/m;
sum=sum+p;
}
printf("\nsum of series : %f",sum);
}

4. Write a program to accept characters till the user enters EOF and count number of alphabets and digits entered. 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
    char str[100];
    int alp, digit, splch, i;
    alp = digit = splch = i = 0;


       printf("\n\nCount total number of alphabets, digits and special characters :\n");
       printf("--------------------------------------------------------------------\n"); 
       printf("Input the string : ");
       gets(str);

    while(str[i]!='\0')
    {
        if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
        {
            alp++;
        }
        else if(str[i]>='0' && str[i]<='9')
        {
            digit++;
        }
        else
        {
            splch++;
        }

        i++;
    }

    printf("Number of Alphabets in the string is : %d\n", alp);
    printf("Number of Digits in the string is : %d\n", digit);
    printf("Number of Special characters or space in the string is : %d\n\n", splch);
}

 5. Write a program, which accepts a number n and displays each digit in words. Example: 6702 Output = Six-Seven-Zero-Two. (Hint: Reverse the number and use a switch statement) 

#include<stdio.h>

void main()

{

int n,rev=0,d;

printf("\nEnter the number:");

scanf("%d",&n);

while(n>0)

{

d=n%10;

rev=rev*10+d;

n=n/10;

}

while(rev>0)

{

d=rev%10;

switch(d)

{

case 1:printf("\tOne");

break;

case 2:printf("\tTwo");

break;

case 3:printf("\tThree");

break;

case 4:printf("\tFour");

break;

case 5:printf("\tFive");

break;

case 6:printf("\tSix");

break;

case 7:printf("\tSeven");

break;

case 8:printf("\tEight");

break;

case 9:printf("\tNine");

break;

default:printf("\nNot a digit:");

}

rev=rev/10;

}

}

Excercise 2: To demonstrate use of nested loops

Set A . Write C programs for the following problems.

1. Write a program to display all prime numbers between ____ and ____.

#include<stdio.h>

void main()

{

int x,y,i,flag,j;

printf("\nEnter two Numbers:");

scanf("%d%d",&x,&y);

printf("\nPrime numbers between %d and %d is ",x,y);

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

{

flag=0;

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

{

if(i%j==0)

flag=1;

}

if(flag==0)

printf("\n%d",i);

}

}


2. Write a program to display multiplication tables from ___ to ___ having n multiples each.

 The output should be displayed in a tabular format. For example, the multiplication tables

 of 2 to 9 having 10 multiples each is shown below.

2 × 1 = 2 3 × 1 = 3 ………….9 × 1 = 9

2 × 2 = 4 3 × 2 = 6…………..9 × 2 = 18

 …………. ………….

 2 × 10 = 20 3 × 10 = 30………..9 × 10 = 90


#include<stdio.h>

void main()

{

int i,j,x,y;

printf("\nEnter two Numbers:");

scanf("%d%d",&x,&y);

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

{

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

{

printf("\t%dx%d=%d",j,i,j*i);

}

printf("\n");

}

}


3. Modify the sample program 1 to display n lines as follows (here n=4).

A

B C

D E F

G H I J

#include <stdio.h>

int main() {

   int i, j, rows;

   char c='A';

   printf("Enter the number of rows: ");

   scanf("%d", &rows);

   for (i = 1; i <= rows; ++i) {

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

         printf("%c ", c);

            c++;

      }

      printf("\n");

   }

   return 0;

}


Set B. Write C programs for the following problems. 

1. Write a program to display all Armstrong numbers between 1 and 500. (An Armstrong number is a number such that the sum of cube of digits = number itself. Ex. 153 = 1*1*1 + 5*5*5 + 3*3*3 

Program

#include <stdio.h>
main()
{
    int number, temp, digit1, digit2, digit3;

    printf("Print all Armstrong numbers between 1 and 500:\n");
    number = 001;
    while (number <= 500)
    {
        digit1 = number - ((number / 10) * 10);
        digit2 = (number / 10) - ((number / 100) * 10);
        digit3 = (number / 100) - ((number / 1000) * 10);
        temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3);
        if (temp == number)
        {
            printf("\n Armstrong no is:%d", temp);
        }
        number++;
    }
}

2. Accept n numbers and display the number having the maximum sum of digits.

Program


#include<stdio.h>

#include<math.h>

int main()

{

 int x[100],n,max=0,i,j,p,s,q;

 printf("enter how many no.:");

 scanf("%d",&n);

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

 {

  scanf("%d",&x[i]);

 }

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

 {

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

  {

   if(i!=j)

   {

    p=x[i]+x[j];

    if(p>max)

    {

     max=p;

     s=i;

     q=j;

    }

         }

  }

 }

 printf("%d and %d number having the maximum sum of digit is : %d",x[s],x[q],max);

}

 3. Display all perfect numbers below 500. [A perfect number is a number, such that the sum of its factors is equal to the number itself]. Example: 6 (1 + 2 + 3), 28 (1+2+4+7+14) 

Program

#include <stdio.h>

void main()

{

    int i, j, sum;

    printf("All Perfect numbers between 1 to 500 :\n");

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

    {

        sum = 0;

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

        {

            if(i % j == 0)

            {

                sum += j;

            }

        }

        if(sum == i)

        {

            printf("%d, ", i);

        }

    }

}

No comments:

Post a Comment