ashers
ashers

Reputation: 7

How to convert this while loop into a for loop?

#include <stdio.h>

int main ()
{ 
int num, sum=0;
printf("Please enter a number: ");
scanf("%d",&num);

while (num>0)
{
    sum += num;
    printf("Please enter a number: ");
    scanf("%d",&num);
}

printf ("Sum = %d ", sum);
return 0;
}

This is something I did. I was trying to convert this while loop which add numbers until user entered 0 to a for loop. May I know what is my mistake here?

    #include <stdio.h>
    int main ()

    {
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    int sum=0;

    for (int i=num; i!=0; )
    {
        sum += num;
        printf("Enter a number: ");
        scanf("%d", &num);
    }

    return 0;
}

Upvotes: 0

Views: 184

Answers (3)

Siddhant
Siddhant

Reputation: 636

One can use an infinite for-loop and insert a jump statement to terminate the loop. In this case:-

#include <stdio.h>

int main ()
{ 
int num, sum=0;
printf("Please enter a number: ");
scanf("%d",&num);

for(;;)  // pretty common and casual way of running an infinite for-loop
{
    if (num <= 0)  // executes if num is less than or equals 0
    {
        break;     // when break is executed this 'for' loop is terminated
    }

    sum += num;
    printf("Please enter a number: ");
    scanf("%d",&num);
}

printf ("Sum = %d ", sum);
return 0;
}

Upvotes: 0

r3mainer
r3mainer

Reputation: 24547

Why do you think a for() loop is necessary? It would be better to not repeat the call to scanf() and use a while loop instead. For example:

int main(void) {
    int num, sum=0;

    while (1) {
        printf("Enter a number: ");
        if (scanf("%d", &num) != 1) break;  // exit if there is no more input
        if (num == 0) break;                // also exit if 0 is entered
        sum += num;
    }
    printf("Total = %d\n", sum);
    return 0;
}

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

You only update num and sum in the loop. The i, which is used as the loop condition, is not updated. You should remove the variable i, which is not properly used, and fix the loop condition.

#include <stdio.h>
int main ()

{
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    int sum=0;

    for (; num!=0; )
    {
        sum += num;
        printf("Enter a number: ");
        scanf("%d", &num);
    }

    return 0;
}

Upvotes: 2

Related Questions