Write a program that outputs the squares of the inputted numbers. The program stops when 0 is entered. Can't use nested loops.
Ex( Input: 4 , 5, 6, 7, 0; Output: 110)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main() {
int x;
int y;
cin>>x;
if (x!=0) {
x = x*x; //squaring x if it is not zero
int sum = x; //setting int sum as first inputted number squared
while (x!=0 && y!=0) { //I know this is redundant
cin>>y; //inputting another number
if (y!=0) {
y = y*y; //squaring y if it is not zero
sum =sum+ y; //adding the new squared input to sum (first number squared, or first number squared plus the next n-1 numbers squared for each loop)
}
}
cout<<sum<<endl; //outputting sum of squares
}
}
This code does not allow me to enter in another number after the first one, and just prints the square of the first number to the screen. I'm not quite sure why it doesn't work.
I wanted to make int sum kind of like a counter, as in having an initial value of x (or rather x^2) if x!=0, and then adding on more inputted numbers, or values of y(rather y^2 if y!=0, until 0 was entered (as y)). Then we could print the counter from the previous loop to get the sum of the squares of all the numbers entered before 0, which terminates the program.
Shouldn't the output for 4 5 6 7 0 be 126 (16+25+36+49=126)?
You're making this too complicated. You don't need x and y, you don't need an if and a loop:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace std;
int
main()
{
int x, sum=0;
while (cin >> x && x != 0) {
sum += x*x;
}
cout << '\n' << "sum is " << sum << '\n';
}
Line 7 may need some explanation. cin>>x returns a reference to cin whose type is istream. && expects it's operands to be bool so the compiler looks for a way to convert cin to bool. Fortunately, istream defines a bool convertion. It calls the good() method. So in one line, the while loop extracts a number into x, checks if the extraction was successful, and checks if the number extracted is zero.