![]() |
| ||
| adding from 0 to a number that will be entered by the user . hi, well this is my first post on this great forum, hope to be a good boy :) i m writing a programm that adds numbers from 0 to any numer entered by the user . for Example : - if the user enter 4, the sum will be 10 = 0+1+2+3+4. - if 10 --> the sum is : 1+2+3+4...+10 = 64 . i make the code like that : #include <stdio.h> the result : the sum is : 2293586 when i enter 4 :-/ i don t know why . any ideas how to make this work Thanks. |
| ||
| Re: adding from 0 to a number that will be entered by the user . #include <stdio.h> |
| ||
| Re: adding from 0 to a number that will be entered by the user . thank you very much mathematician for this quick answer but i have small question why did you use %u in the place of %i i mean it works with %i too . thanks again ;) |
| ||
| Re: adding from 0 to a number that will be entered by the user . its just sum=sum+i hehehe |
| ||
| Re: adding from 0 to a number that will be entered by the user . for ( i = 0; i <= number; i++ ) { sum =sum+ i; } try this code... |
| ||
| Re: adding from 0 to a number that will be entered by the user . Quote:
Secondly, given what you are doing, you presumably want the user to enter a positive (unsigned) integer (%u). |
| ||
| Re: adding from 0 to a number that will be entered by the user . thanks james14 it works too ( well i m a beginner i coudn t figure it out :) ) thanks ;) Quote:
but the idea to use %ufor the positive numbers is great :) thank you mathematecian for solving this . |
| ||
| Re: adding from 0 to a number that will be entered by the user . Quote:
for(i = 0, sum = 0; i <= number; i++) will be correct ;) thanks :) |
| ||
| Re: adding from 0 to a number that will be entered by the user . mrayoub: %i and %d are equivalent. both of them specify the format for a signed decimal integer, and either are acceptable to use. %u, as you have seen, is for unsigned decimal integer however, if you have declared a variable of type intthen you should not print it as %u, an unsigned int. That is a bad practice to get into... because while it may in many cases appear to work correctly, your integer may very well have a valid negative value , and the %u format will print an incorrect value. if you want the variable to be unsigned, then make it unsigned by declaring it so: unsigned number; . |
| ||
| Re: adding from 0 to a number that will be entered by the user . thank you very much jephthah this was really helpful, well programming in C has to be very specific ;) . i got more informations now trough this post .Really nice to join you ! |
| All times are GMT -4. The time now is 1:55 pm. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC