c - square roots with arrays

Jun 26, 2018 at 5:41pm
I know it's dumb of me to ask, but how do I make a program that calculates the square of the elements of an array of 10 numbers?
Jun 26, 2018 at 5:45pm
1. Do you know how to get the square of a number?
2. Do you know how to apply a function to each element of an array?
Jun 26, 2018 at 6:10pm
This is what I did.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>  
#include <math.h>    
 
int main()
{
	int i;
	float num[10], square;
	
	printf("Enter 10 numbers to start calculating the square root: \n");
	
	for(i=0; i<10 ;i++)
	{
		scanf("%f", &num[i]);
		
		square=sqrt(num[i]);
		
		printf("%4.2f \n", square);
		printf("\n");
	}	
}
Jun 26, 2018 at 6:27pm
Those are square roots, not squares.
And if that's all you need to do then you don't need an array.
Jun 27, 2018 at 4:01pm
How do I do it with squares then?
Jun 27, 2018 at 4:14pm
c++ has a pow() function but it is very heavy because it supports floating point powers, so it has to do a bunch of things that are totally unnecessary for simple squares.

if you wanted x to the pi power, use pow().
if yuo want x squared, a good old fashioned x*x is all you need.

square = num[i] * num[i]; in your code, then.

There seems to be some confusion.
your code's text says:
printf("Enter 10 numbers to start calculating the square root: \n");

but you ask about squares.
Be sure you know what it is you actually want to do here.
Last edited on Jun 27, 2018 at 4:17pm
Jun 27, 2018 at 4:16pm
The real question is, do you need the square, or the square root? Because it feels like you're using both terms interchangeably.
Jun 27, 2018 at 4:50pm
Well originally this is translated straight from spanish. Though, we asked our prof. if it was square or square root. He said square root. I'm not sure anymore.
Jun 27, 2018 at 5:04pm
Then just do square root (raíz cuadrada), sqrt(). Your variable name (square/cuadrada) is just misleading, in that case.
Topic archived. No new replies allowed.