For sigma like Σ

This assignment was focused on a different kind of loop, previously I used a “do while” loop, check it out here,  but this time I’ll be using a “for” loop.

Ok, so… the “for” loop consist of 4 parts:

  • Initialization: here is where you will declare how the loop starts.
  • Condition: in this part, the program will evaluate if the loop is true or false.
  • Increment: the initialization that you started at first will either increase or decrease.
  • Statement: What happens every time a loop is completed.

If you need further information check this out.

Ok check the code:

#include <iostream>

using namespace std;

int main(){

int i, low, high, sum = 0;

cout << "Give me the lower number: ";
cin >> low;
cout << "Give me the higher number: ";
cin >> high;

for (i = low; i <= high; i++){
sum = sum + i;
}

cout << "The sum of numbers between " << low << " & " << high << " is: " << sum << endl;

return 0;
}

So now that you have seen the code, let me show you what the “while” loop can do, I wanted to make my code check if the input the user gives is correct. The lower boundary can’t be bigger than the higher one, so if this is the case the program will keep asking the user until the boundaries are correct.

  1. The original input for “low” & “high”.
  2. “While” loop with the condition that low is bigger than high.
  3. A message telling the user he’s messing it up.
  4. Get new boundaries.
  5. Be a happy person.

Check it out

#include <iostream>

using namespace std;

int main(){

int i, low, high, sum = 0;

cout << "Give me the lower number: ";
cin >> low;
cout << "Give me the higher number: ";
cin >> high;

while (low > high){
cout << "The lower number is bigger than the higher, please try again!" << endl;
cout << "Give me the lower number: ";
cin >> low;
cout << "Give me the higher number: ";
cin >> high;
}

for (i = low; i <= high; i++){
sum = sum + i;
}

cout << "The sum of numbers between " << low << " & " << high << " is: " << sum << endl;
return 0;
}

 

Featured image.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s