Reputation: 3
I want to print a sequence of 1 4 9 16 25...n by inputting any number which is equal to the number of terms I want as an output. For example: if I input 4, it should print 1 4 9 16 but I can't seem to get the result I want using this program I have made. The result goes like 0 1 4 9. I want to eliminate the first term zero, Can someone pls help me see what's wrong with my program?
int result,n;
for (int i = 1; i <= n; i++){
scanf("%d", &n);
printf("%d ", result);
result = pow(i,2);
}
Upvotes: 0
Views: 60
Reputation: 1153
#include <stdio.h>
int main()
{
int result, i, n;
printf("Input n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
result = i*i;
printf("%-3d", result);
}
}
OUTPUT: 1 4 9 16... n^2
Probably, you want this.
You should scan the value of n
before the loop. Otherwise, the behavior of your program would be unpredictable. Second, it is wise to avoid floating-point calculations when possible and here you want to print the series of square of integers. i.e. 1,4,9,...
so you shouldn't use
double pow(double a, double b)
function. Also as Fred said, "Calculate result
before you print it."
Upvotes: 2