-5

I tried to print the multiplication of two 3-digit numbers.

 #include <stdio.h>
 int main()
 {
    int x,y;
    for(x=100;x<1000;x++)
    {
        for(y=100;y<1000;y++)
        {
            printf("%d,",(x*y));
        }
    }
 }

When I put the count up values to little numbers like 110, this generates the correct answer, but when it is put to bigger values like 500, 1000, the answer is wrong.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Destructor
  • 523
  • 1
  • 3
  • 13
  • 1
    Could your `int`s be too small ? What does `sizeof(int)` say ? – cnicutar Sep 09 '13 at 04:26
  • "when it is put to bigger values like 500,1000 answer is wrong." What does that mean? Neither `x` nor `y` can reach 1000 because of your loop bounds, so I'm not sure what you might mean. – rliu Sep 09 '13 at 04:27
  • 3
    Read: [What is an integer overflow error?](http://stackoverflow.com/q/2641285/315052) – jxh Sep 09 '13 at 04:28
  • roliu - i said when i change the conditions in the both for loops to x<1000 and y<1000 the answer is freaked. I need help in solving that. Thanks – Destructor Sep 09 '13 at 04:37
  • @user2760267: Freaked in what way? Values negative? Your terminal screen gets messed up? What do you mean exactly? – jxh Sep 09 '13 at 04:40
  • @jxh: answers are totally wrong. as an example the first print should be 10000 ryt? In the result its something like 64 . – Destructor Sep 09 '13 at 04:45
  • @user2760267: How do you verify that is the first number printed? Are you sure your scrollback buffer in your window is large enough? Try redirecting the output to a file and look at the output in an editor. – jxh Sep 09 '13 at 04:46
  • @jgx thanks alot. It must be the problem. Int can hold that much of a number ryt? – Destructor Sep 09 '13 at 04:49
  • 2
    You can print `INT_MAX` from `` to see the maximum value `int` can handle. – jxh Sep 09 '13 at 04:51

2 Answers2

1

Because when you multiply bigger numbers like 999*999 the result value will be greater than range of int. so you have to use long instead

printf("%ld",(x*y));
Voonic
  • 4,667
  • 3
  • 27
  • 58
0

The problem is that output was so voluminous, you overflowed the scrollback buffer of your terminal. So what you thought was the first output number was probably the end of some other number that got cut off. This led you to believe the program was giving incorrect output.

Redirect your output to a file, and look at the output in an editor.

prog > output.txt

Another suggestion is to output each result on a separate line, and also provide the x and y values on the output line, so you can see the input and result on one line:

        printf("%d * %d = %d\n",x,y,(x*y));

This way, your output won't be ambiguous, your problem would have manifested itself as some missing output, rather than leading you to assume the output is incorrect.

jxh
  • 69,070
  • 8
  • 110
  • 193