Home > Mobile >  Can anyone notice where the mistakes is in my code?
Can anyone notice where the mistakes is in my code?

Time:11-29

Can anyone tell me why is my output wrong "1* 3 = 1" whereas other multiplications is correct? Thanks!

#include <stdio.h>
int main()
{
    int n,i = 1, total;
    
    printf("\nPlease enter multiplication table: ");
    scanf("%d", &n);
    printf("%d Times Table\n",n);

    while(i<= 12)
    {   
    printf("\n%d*%d=%d", i, n, total);
    i  ;
    total = i*n;
    }       
}

CodePudding user response:

You are printing a value, total, before you assign any value to it. On the first iteration of the while loop, total doesn't contain any defined value.

Here's a way to fix it:

#include <stdio.h>

int main(void)
{
    int n, i = 1, total;
    printf("\nPlease enter multiplication table: ");
    scanf("%d", &n);
    printf("%d Times Table\n", n);
    while (i <= 12)
    {
        total= i * n;
        printf("\n%d*%d=%d", i, n, total);
        i  ;
    }
}

Simply calculate total before you print it, not after.

  •  Tags:  
  • c
  • Related