Home > Software design >  A unexpected output with if condition
A unexpected output with if condition

Time:12-09

I want to wirte a program to calculate the sum of first n natural numbers

The code that i have tried:

    #include<stdio.h>
    void main()
    {
        int sum=0,i=1,n;
        printf("Enter the number upto where you want to print add  : ");
        scanf("%d",&n);
        printf("\nSUM = ");
        while(i<=n)
    
        {
          if(i<n)
          {
              printf("%d ",i);
          }
          if(i=n)
          {
              printf("%d",i);
          }
          sum=sum i;
          i  ;
        }
        printf("\nThe sum of the first %d numbers is : %d",n,sum);
        return 0;
    }

And the expected output is if n=5

Enter the number upto where you wnat to print add :

sum =1 2 3 4 5

The sum of the first %d numbers is : 5

But what I'm getting is

sum=1 5

and the value is 5

But when I'm using if else instead of two if's its working

CodePudding user response:

The problem is your if statement :

if(i=n)

A single = is an assignment; what you want is the comparison with ==, so :

if(i==n)

CodePudding user response:

You have used i=n instead of i==n in if statement.

CodePudding user response:

You are using the assignment operator = instead of the comparison operator == in the expression in this if statement

      if(i=n)
      {
          printf("%d",i);
      }

You need to write

      if( i == n)
      {
          printf("%d",i);
      }

Also it is better to use for loop instead of the while loop.

For example

for ( int i = 0; i < n;  )
{
    printf(   i == n ? "%d" : "%d ", i );
    sum  = i;
}

The variable i is used only in the loop. So it should be declared in the scope where it is used.

Always try to declare variables in minimum scopes where they are used. This will make your programs more readable.

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )
  • Related