inquiry about while loop structure

hello guys.. i just started studying while loop ..!

this is the first code i that i wrote.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
int main()
{
	int sum,i;
	i=0;
	sum=0;
	int num;
	int n;
	cout<<"enter the number of your marks"<<endl;
	cin>>n;
		
	while (i<n){
	cout<<"enter the value of ur marks"<<endl;
		cin>>num;

		sum=sum+num;
	
			i++;
	}
	double avg;

	cout<<"SUM="<<sum<<endl;
	cout<<"Avg="<<avg/sum;
}


the error is: it doesn't calculate the avearge..?!?!?!?
why??
Last edited on
And what was this error? Post the complete error messages exactly as they appear in your development environment along with the code that generated these errors.

Last edited on
it tells me that the variable avg is being used without being initialized..?!?

i did initialize it.!!??!?!?

And what do you want? The message of the compiler is clear enough.
i did initialize it.!!??!?!?

Where?

line 21
.. i found..
the avg is wrong.. it isn't calculated like this.!

avg=sum/number of times.!!

should it be .. avg=sum/i or n?????? in my code
should it be .. i or n?????? in my code

Which represents the number of marks?
This code is functionally equivalent to what you posted in the original (logical errors and all). All I did was add a little whitespace and make more descriptive variable names. The logical error at your 'average' calculation really jumps out when more descriptive names are used.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
int main()
{
	int totalSumOfMarks, numberOfMarksIChecked;
	numberOfMarksIChecked=0;
	totalSumOfMarks=0;
	int theNextMark;
	int totalNumberOfMarks;
	cout<<"enter the number of your marks"<<endl;
	cin>>totalNumberOfMarks;
		
	while (numberOfMarksIChecked < totalNumberOfMarks){
	cout<<"enter the value of ur marks"<<endl;
		cin>> theNextMark;

		totalSumOfMarks= totalSumOfMarks + theNextMark;
	
			numberOfMarksIChecked++;
	}
	double averageMark;

	cout<<"SUM="<< totalSumOfMarks <<endl;
	cout<<"Avg="<< averageMark/totalSumOfMarks;
}
You declared the variable i but you never initialized it (gave it an initial value) so when the program goes to check if it's less than n it has nothing to do (no value to check), thus you get a compiling error.
Last edited on
Next time you get an error saying you didn't initialize something, if the answer isn't immediately obvious google c++ initialize (or whatever the error message or terms are) for clues.

I'm surprised nobody answered this.
Topic archived. No new replies allowed.