Monday, May 24, 2010

Help with a very simple C program using 'for' to sum numbers?

hello





i am a C novice, and my teahcer wanted to make a program using for to sum the numbers that where before a certain number





for exmple input 5





5+4+3+2+1=15





#include%26lt;dos.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;stdio.h%26gt;








void main()





{


int total,number,contador;





clrscr();


printf("inserte numero\n\n\n");


scanf("%d",%26amp;numero);





for(contador=numero; contador%26gt;0;contador--)


{


clrscr();





resultado1=numero+contador;





resultado1=resultado1+resultado1;

















}


printf("%d es el resultado\a\n", resultado1);





getch();





}








so, contaodor is supposed to decrease so that the 5,4,3,2,1 are added to 5, and the result should be 15





but, the program simply sums 5+1, the last number before 0, so the total is 6 and the other line insisde the for just does a stupid 6+6





i think the solution should be very easy but im tired as hell..





anyone can help please :P?

Help with a very simple C program using 'for' to sum numbers?
Hi Jose,





Try this out :





#include%26lt;dos.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;stdio.h%26gt;








void main()





{


int resultado1=0,numero,contador;





clrscr();


printf("inserte numero\n\n\n");


scanf("%d",%26amp;numero);





for(contador=numero; contador%26gt;0; contador--)


{





resultado1 += contador;





}


printf("%d es el resultado\a\n", resultado1);





getch();





}
Reply:int result;





for(int i = contador; i %26gt; 0; i--)


{


result += i;


}


printf("%d", result);
Reply:Everyone is correct. You are just missing something in your code. Declare resultado1 up top and it should compile correctly as you intended it.


No comments:

Post a Comment