Issue with IF statement / Array / While loop

Hi there,

I am fairly new to C++ and am only asking for a bit of direction, not to have code created for me. I have written a program that allows one to enter an integer into an array using a while loop. I have tried to add an IF statement to break the program out if a mark is greater than 100 or less than 0. When I have added the if statement it is breaking my program and I cannot seem to figure out why. From my view the logic seems to be correct but there is obviously something I am missing.

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
26
27
28
29
30
#include<iostream>

using namespace std;

int main()

{
	int marks[10], sum=0, add=0;
	
	while(add < 10)
	{
		cout << "Enter a mark: ";
		cin >> marks[add++];
		
		if(marks[add] > 100 || marks[add] < 0)
		{
			cout << "Invalid mark, start over" << endl; break;
		}
	}
	
	add= 0;
	
	while(add < 10)
	{
		sum += marks[add++];
	}
	
	cout << "the sum of the array is: " << sum << endl;
	cout << "the avarage of the array is: " << sum/10 << endl;
}

Any assistance is appreciated.
Last edited on
Your if statement causes you to break out of the first while loop if an out of range number is entered.

Your code continues with the second while loop computing the sum and average even if you broke out of the first loop on the first iteration (meaning there are no valid numbers in the array).

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Thank you for your response and sorry about the formatting, this is my post and I have corrected it as you specified.

I understand that my the statement breaks if the number is outside the range, I actually want that. What I cannot understand is when I enter a valid integer such as "12" the if statement is giving a true return instead of a false as it should.

Maybe the way I am handling the situation is not good practice? Should I try and use a while loop to return to the original line instead of an IF statement?

Thank you,
Didn't spot it before. Your problem is due to where you're incrmenting add.

First interation, add is 0. line 13, you cin a number to marks[add++]. That stores the number correctly, but add is now 1. line 15: you're now testing marks[1], which contains garbage.

Increment add at the bottom of your loop after line 18 (after all references to add).
Last edited on
You're a gentleman and a scholar, thanks Anon.
Topic archived. No new replies allowed.