I tried my first exercise!

Hi guys, first post here - excellent site so I thought I would ask for your help!
I've been following Bucky Roberts C++ programming tutorials on youtube, I seem to be coming along ok in theory and thought I should attempt to write some actual code.
I found some beginner exercises http://www.cplusplus.com/forum/articles/12974 <- here, and attempted the first one.

This is what I have:
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
31
32
33
#include <iostream>

using namespace std;

int main()
{
    int grade;

    cout << "Enter grade scored in %: " << endl;
    cin >> grade;
    while((grade >= 0) && (grade <101)){
        if(grade >90){
            cout << "You scored an A!" << endl;
            break;
        }
        if(grade >80){
            cout << "You scored a B!" << endl;
            break;
        }
        if(grade>70){
            cout << "You scored a C!" << endl;
            break;
        }
        if(grade>60){
            cout << "You scored a D!" << endl;
            break;
        }
        if(grade<60){
            cout << "You scored an F!" << endl;
            break;
        }
        }
}


And this works, it does exactly what is asked of it in the exercise.

However being the ever seeking perfectionist that I am, I'm not happy in the fact that I'm sure there must be a more efficient way of doing things other than just repeating an if statement countless times.

Any way to improve on this attempt?
Many thanks,
Matt
Last edited on
Switch statement maybe? That might work. Not sure though
closed account (zb0S216C)
Instead of repeating if, use else if. if must appear before an else if block. The last being else (optional). An if statement must be defined before using an else statement. For example:

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
if( X < Y )
{
    // ...
}

else if( X > Y )
{
    // ...
}

else 
{
    // ...
}

// Or:
if( X > Y )
{
    // ...
}

else
{
    // ...
}


Wazzak
Last edited on
Topic archived. No new replies allowed.