Click here to Skip to main content
16,020,345 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
the question is :
Write a program that compute the sum and average of square of first five integers.
Try to write it also for user defined number instead of 5.

Sum = 1*1 + 2*2 + 3*3 + 4*4 + 5*5 ;

Write the programs one with for loop and one with while loop.

What I have tried:

C++
#include <iostream>

using namespace std;

int main()
{
int number , counter ;
float average;
float sum =0;
cout<< "Enter five numbers to find the sum and the average of square of first five integer"<<endl;
cin >>number;
for (counter=0;counter<5;counter++){
    sum=sum+(number*number);
    cin>>number;
    (number+number);
}
cout<<"The sum is :"<<endl <<sum<<endl;
average =sum/counter;
cout<<"The average is :"<<endl<<average;
    return 0;
}
Posted
Updated 4-Dec-16 12:03pm
v2

Your code is weird looking, you should run it under debugger and inspect the variables as you step line by line.

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 
The while loop is also easy:

C++
int counter = 0;
while( counter < 5 ) {
// your code
counter ++;
}


For a variable length of input you only need a another var.
C++
int theCount = 0;
cout<< "Enter count of numbers for computation"<<endl;
cin >> theCount;
int counter = 0;
while( counter < theCount ) { //use for exit loop
// your code
counter ++;
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900