for loop help

I want to execute a for loop. All I need to is stop the program after n=5 and get the results of 1,4,9,16,25.
I got wrong calculations. The square of 1 is 3.
The square of 2 is 0. etc..
Can you tell me what is the problem here?

# include <stdio.h>
# include <stdlib.h>

main()
{
int a,b,n;
printf("Please enter a value.\n");
scanf("%d", &n);

for (a=1; a<=n; a++)
{
b=a^2;
printf("The square of %d value is:%d\n",a,b);
if(a>=6);{
break;
}
}
return 0;
}






@sercandemir

To get the square, you need to multiply a by a. So it should like b = a * a;.

And also remove the semicolon after the if statement. Actually, you don't need the if statement and break command.
Last edited on
you could also use the pow function.

#include <cmath>

change this statement b=a^2; to b=pow(a,2);
that way you'll be able to easily change the exponent value.

and yes take out
1
2
3
if(a>=6);{
break;
}
When I use cmat.h and try to compile the code, I got this error: No such file or directory.
Also, here I am trying to learn how does break command work. That is why I want to keep it. All I want to do is stop the calculation when 'a' hits 5.
I mean if I type 8 for n, I want to get the squares up to 5 and stop there.
When I use cmat.h and try to compile the code


Looks like you're using C. You want to do this then

#include <math.h> I Think that one was used in C.

Edit: Also, if you want to learn how the break command works. Try switch statements.
Last edited on
Yes, I am using C. And yes, it works.
I also switched the statements and got the result I wanted.

Thank you all,
Topic archived. No new replies allowed.