Learner94
Learner94

Reputation: 21

Getting undesired result by using while loop to find the sum of n natural numbers

I am attaching the code for the same.Its working fine.But once i enter a number less than the previous one it stops giving desired output.Any help/suggestion shall be greatly appreciated.

int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
   printf("Enter the number upto which you want the sum of \n \n");
   scanf("%d",&n);

   while(i<=n)
   {

      j=j+i;
      i++;

   } 
   printf("%d \n",j);
   printf("Do it with another number? Y/N \n \n");
   scanf("%s",&ch);
}
return 0;

Upvotes: 2

Views: 356

Answers (5)

Mohit Kumar Raj Badi
Mohit Kumar Raj Badi

Reputation: 14

#include<stdio.h>
int main(){
int n;
char ch;
while(ch!='n')
{
   printf("Enter the number upto which you want the sum of \n \n");
   scanf("%d",&n);
int i=1;//it should be 1 in every loop of the number
int j=0;//the sum should also be initialized to zero to erase the previous value 
   while(i<=n)
   {

      j=j+i;
      i++;

   } 
   printf("%d \n",j);
   printf("Do it with another number? Y/N \n \n");
   scanf("%c",&ch);//this is a char not a string
}
return 0;
}

Due to the i is not initializing to 1 when the loop is coming for the second time there it is not going inside the loop and printing the previous value .

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76591

The simplest solution is to set i to 0 at the outer while:

int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
i = 0;
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);

while(i<n)
{

j=j+i;
i++;

} 
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;

Note that I have changed <= to < for your inner while, since you do not want to increment the value if the same n is inputted one after the other.

Upvotes: 0

WhozCraig
WhozCraig

Reputation: 66234

There are a smattering of bugs in this code, including:

  1. Comparison to uninitialized value of of ch in the initial while expression.
  2. Failing to reset i and j for each outer-loop iteration
  3. Failing to test for data-read success in either scanf call to ensure proper input.
  4. The continuation scanf("%s", &ch) is simply wrong for a single character with skipped whitespace (which you must do to avoid reading the newline after your list integer input). Unless EOF or an error state is reached, what you have now is guaranteed to invoke undefined behavior, as a string-read of at least one character requires at least two for storage (the character, and a subsequent terminator).

Addressing all of those:

#include <stdio.h>

int main()
{
    char ch;
    do
    {
        int n;
        printf("Enter the number upto which you want the sum of \n \n");
        if (scanf("%d", &n) != 1) // See (3)
            break;

        int j = 0; // See (2)
        for (int i = 1; i <= n; ++i) // See (2)
            j += i;
        printf("%d \n", j);

        printf("Do it with another number? Y/N \n \n");
        if (scanf(" %c", &ch) != 1) // See (3) and (4)
            break;

    } while (ch != 'n' && ch != 'N'); // See (1)

    return 0;
}

Everything here is self-explanatory when referred to the previous bug punch list, save for maybe the format string for reading the single character. You mentioned in comments that you tried %c but it skipped to another loop iteration. That's because you didn't have the leading whitespace " %c" that tells scanf to skip white space before extracting the next argument. With that, it should work as desired.

Upvotes: 1

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

You need to reset i and j for every n.

i = 1;j=0;
while(i<=n)
{

Also your format specifer is wrong. For char, it should be %c and not %s

scanf("%c",&ch);

Upvotes: 0

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4774

In your outer while loop, you're never resetting the value of the variable i back to 1, or j back to 0. That is why subsequent loops will produce an incorrect sum.

Upvotes: 2

Related Questions