How to correct this code of multiplication table in C Language.

kmr1154

Distinguished
Hello

Don't know whether this is the right place to ask this...

I am learning C and i am basically a starter.
I am trying to make a program to give me multiplication of the number i input.
I want the output to look like this.
==============================
Enter number to find its multiplication
5 (for example)
The multiplication of 5 is as follows:-
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

==============================

I am able to do so with the below code, but the problem is after pressing 1 and calling from main again, the table output shows like this...
===========
5 x 11 = 5
5 x 12 = 10
5 x 13 = 15
5 x 14 = 20
etc...
===========
I don't want to close cmd to reset everything, that is why i am using while loop. How to fix such issue?

Regards!!!

C++:
``````#include <stdio.h>
#include <conio.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv)
{
int x,i,o=1,y=1;
while(y==1)

{printf("\nEnter number to find its multiplication:\n");
scanf("%d",&x);
printf("\nThe multiplication of %d is as follows:-\n",x);
for(i=1;i<=10;i++)
//for(o=1;o<=10;o++)
{

printf("\n%d X %d = %d\n",x,o++,x*i);
}
scanf("%d",&y);
}

getch();
return 0;
}``````

Solution
The problem is in this line:
printf("\n%d X %d = %d\n",x, o++, x*i);

Variable o is incremented inside the while loop, without ever being reset to its inital value = 1.

Declare it before the for loop, so it has its inital value restored in each iteration. In fact you can only use one variable here to iterate and display.

int i;
for(i = 1; i <= 10; i++) {
printf("\n%d X %d = %d\n",x, i, x*i);
}

Bejusek

Distinguished
The problem is in this line:
printf("\n%d X %d = %d\n",x, o++, x*i);

Variable o is incremented inside the while loop, without ever being reset to its inital value = 1.

Declare it before the for loop, so it has its inital value restored in each iteration. In fact you can only use one variable here to iterate and display.

int i;
for(i = 1; i <= 10; i++) {
printf("\n%d X %d = %d\n",x, i, x*i);
}

kmr1154

Distinguished

Thanks man, issue solved...

Replies
8
Views
4K
Replies
3
Views
2K
Replies
3
Views
2K
Replies
1
Views
1K
Replies
3
Views
2K