Home > Software engineering >  How to change program from while loop to for loop?
How to change program from while loop to for loop?

Time:10-14

I understand that while loops and for loops have different layouts in order to work. But I am stuck on how to convert this code to for loop format.

How do I change the format while keeping the same output?

#include<stdio.h>
int main(){
int n, i =1, sum =0;
     do{
      printf("enter a positive number to find whether prime or not: ");
      scanf("%d",&n);
   } while (n<=0);
    while (i<=n){
       if (n%i ==0) sum =1; //sum is the validation flag
      i =1;
   }
   if (sum>2) printf("\nThe number %d  is not prime.", n);
   else
   printf("\nThe number %d is prime.", n);
   return 0;
}


CodePudding user response:

A for loop is like a while loop, except that the iteration variable initialization and updating are put into the for header.

The initialization is the declaration int i = 1 before the loop. The update is i = 1 (which is usually written as i ). So take out these separate statements and put them into the header.

for (int i = 1; i <= n; i  ) {
    if (n%i == 0) {
        sum  ;
    }
}

CodePudding user response:

If you mean this do-while loop

 do{
  printf("enter a positive number to find whether prime or not: ");
  scanf("%d",&n);
} while (n<=0);

then it can be rewritten as a for loop for example the following way.

 for ( n = 0; n <= 0; scanf("%d",&n) )
 {
      printf("enter a positive number to find whether prime or not: ");
 }

Pay attention to that this code snippet

    while (i<=n){
       if (n%i ==0) sum =1; //sum is the validation flag
      i =1;
   }
   if (sum>2) printf("\nThe number %d  is not prime.", n);
   else
   printf("\nThe number %d is prime.", n);

does not correctly determine whether a number is a prime number. For example for the number equal to 1 the output will be that the number is a prime number. Change the condition in the if statement like

   if (sum != 2) printf("\nThe number %d  is not prime.", n);

As for the while loop then it can be rewritten the following way

for ( ; i<=n; i   ){
   if (n%i ==0) sum =1; //sum is the validation flag
}

Also as the variable i is used only within the loop then it is better to declare it in the for loop like

for ( int i = 1; i<=n; i   ){
   if (n%i ==0) sum =1; //sum is the validation flag
}

In this case remove the declaration of the variable i from this like

int n, i =1, sum =0;

at least like

int n, sum =0;
  • Related