-
atoanger
can someone tell me what is wrong with this code.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[5]; /* uers's input */
int r_input,count,t_num=0; /* converted intput, counter and tri number */
printf("What number would you like the triangular of? ");
scanf("%d", &input); /* caputre data */
r_input = atoi(input); /* validate input */
/* calculate triangular number
* which is bascically factorial
* ex: 7 + 6 + 5 + 4 + 3 + 2 + 1
*/
for(count = 0; count <=r_input; count++)
{
t_num = t_num + count;
printf("Count = %d \t T_num = %d\n", count, t_num);
}
printf("Finished!\n");
system("pause");
return 0;
}
when i run it, it seems the loop stays at 0? what am i doing wrong?
I removed the atoi function and it worked fine
Code:
#include <stdio.h>
/* #include <stdlib.h> */
int main()
{
/* char input[10]; uers's input */
int r_input,count,t_num=0, input; /* converted intput, counter and tri number */
printf("What number would you like the triangular of?\n");
scanf("%d", &input); /* caputre data */
/* r_input = atoi(input); validate input */
/* calculate triangular number
* which is bascically factorial
* ex: 7 + 6 + 5 + 4 + 3 + 2 + 1
*/
for(count = 0; count <=input; count++)
{
t_num = t_num + count;
printf("Count = %d \t T_num = %d\n", count, t_num);
}
printf("Finished!\n\a");
system("pause");
return 0;
}
What am i doing wrong?
while i'm at. Is the triangular number not the same thing as a factorial.
Thank you.
-
atoi( ) expects a string, and you're passing it an integer.
Also, you need to check scanf's return code, to make sure that the user does input an integer.
>>while i'm at. Is the triangular number not the same thing as a factorial.
Factorials are n(n-1)(n-2)...2(1). Triangular numbers are n + (n-1) + (n-2)+...+2+1.
-
>char input[5]; /* uers's input */
>int r_input,count,t_num=0; /* converted intput, counter and tri number */
>printf("What number would you like the triangular of? ");
>scanf("%d", &input); /* caputre data */
Use %s for strings, and lose the &:
scanf("%s", input); /* capture data */
-
Whoops. Missed the declaration of input as a char[].
-
>Use %s for strings:
>scanf("%s", input); /* capture data */
Bad advice when there are better ways to get strings or integers.- scanf's %s format has the same problem that gets has: it's hard to guarantee that the receiving buffer won't overflow.