Search

while loop

           C programs based on while loop


Sample Program based on Looping concept



#include<stdio.h>
int main()
{
  int i;
  for(i=1; i<=10; i++)
  {
     printf("%d ", i);
  }
  return 0;
}

Output of program

1 2 3 4 5 6 7 8 9 10




1.C program to print A to Z using while loop.

#include<stdio.h>
int main()
{
  char ch='A';

  while(ch <= 'Z')
  {
printf("%c ", ch);
ch = ch + 1;
  }
  return 0;
}


Output of the program:

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



2.C program to print 10 to 20 numbers using while loop.

#include<stdio.h> 
int main()
{
int number=10;

while(number <= 20)
{
printf("%d ", number);
number = number + 1;
}
 return 0;
}

Output of the program:
 

10 11 12 13 14 15 16 17 18 19 20

3.C program to count no. of digits in a given number.

#include <stdio.h>
int main()
{
  int number, count=0;
  printf("Enter your number: ");
  scanf("%d", &number);
  while(number!=0)
  {
      number = number / 10;   
      count = count + 1;
  }
  printf("Number of digits = %d", count);
  return 0;
}


Output of the program: 

Enter your number: 10123
Number of digits = 5



4.C program to calculate the power of an integer without use of inbuilt math function.




#include <stdio.h>
int main()
{
  int base, exponent, flag;
  long int answer=1;
 
  printf("Enter base number:");
  scanf("%d", &base);
 
  printf("Enter exponent number:");
  scanf("%d", &exponent);
  flag = exponent;
  while (flag != 0)
  {
      answer = answer * base; 
      --flag;
  }
  printf("Power of %d to the %d = %d", base, exponent, answer);
  return 0;
}


Output of the program: 

Enter base number:2
Enter exponent number:5
Power of 2 to the 5 = 32


5.C program to count words in a given string.


#include<stdio.h>
#include<stdlib.h>

int main(){

char str1[80]="Hello Student How are you?", *token ;
const char s[2] = " ";
    
int counter=0;
printf("Given String = %s",str1);
token = strtok(str1,s);
while (token != NULL)
{
counter++;
token = strtok(NULL, s);
}
printf("\nTotal words in a given string is %d", counter );
 return 0;
}


Output of the program: 

Given String = Hello Student How are you?
Total words in a given string is 5




6..Greatest Common Divisor(GCD) of given 2 numbers


Write a C program to find Greatest Common Divisor (GCD) of given 2 numbers.

      GCD is also known as Greatest Common Factor (GCF)

      GCD is also known as Highest Common Factor (HCF)


#include <stdio.h>
int main()
{
  int num1, num2, i, j, temp, gcd;

  printf("Enter number 1:");
  scanf("%d", &i);

  printf("Enter number 2:");
  scanf("%d", &j);

  num1 = i;
  num2 = j;

  while (num2 != 0)
  {
    temp = num2;
    num2 = num1 % num2;
    num1 = temp;
  }

  gcd = num1;
  printf("Greatest Common Divisor(GCD) of %d and %d is %d.\n", i,j,gcd);
  return 0;
}

Output of  the program:

Enter number 1:20
Enter number 2:30
Greatest Common Divisor(GCD) of 20 and 30 is 10.





No comments:

Post a Comment