2

hey so i just started programming (C) and i wanna know the difference between while and for loops, so i did a program to sum natural numbers with a for loop and it worked:

int sum = 0;
int count;
int num = 11;

for (count = 1; count <= num; count++){
    sum += count;
}
printf("Sum of numbers is: %d\n", sum);

Sum came out as 66 and count comes out as 11, but when i tried it in a while loop it came out wrong:

int kount = 1;
int ssum = 0;
int number = 11;
while(kount <= number){
    ++kount;
    ssum += kount;
}
printf("Ssum is: %d \n", ssum);
printf("Kount is %d \n", kount);

Here ssum comes out as 77 and kount comes out as 12. Can anyone explain why to a beginner like me?

ooatman
  • 95
  • 6

4 Answers4

2

just add line ++Kount after ssum+=kount and your problem will get solved.

int ssum = 0;
int kount = 1;
int number = 11;
while (kount <= number) {
    ssum += kount;
    ++kount;

}
printf("Ssum is: %d \n", ssum);
printf("Kount is %d \n", kount);
Atharva Jawalkar
  • 166
  • 1
  • 12
1

Inside the body of your while loop try doing

ssum += kount; before you do ++kount;

1

The basic difference between for and while loop is all three steps initalization, test and increment are written in single line.

For loop:

int a ;
for(a= 0; a<10; a++)
{
    //do some stuff
}

While loop:

int a = 0;     // 1. Initialization step
while (a < 10) // 2. Test step
{
    // Do something
    a++;      // 3.Increment step. a++ is the same as saying a=a+1, 
}

Another way of comparing two numbers in while loop:

a=2;
b=3;
while (a < b)
{
    a++;
    printf("%d\n",a);
}

You can do this in one-liner using for loop.

for (a=2,b=3; a < b; a++,printf("%d\n",a));
danglingpointer
  • 4,708
  • 3
  • 24
  • 42
0

For safety reasons, it is often recommended to use for-loops instead of while.

With for-loops you have an "automatic" maximum loop count. When using while this depends on your code in the while-loop.

This is specially important on microcontrollers where your programm will get stuck if you do not leave the loop implementation.

A.R.C.
  • 910
  • 11
  • 22