Loops

Muhammad Magdi

Increment Operator

x = x + 1;

This statement assigns to `x` the value of `x` + 1:

gets the old value of `x`, then adds 1 to it, then stores the new value in `x` again.

 

This  operation can also be done using the increment operator.

x++;

URI 1060 - Positive Numbers

[Problem Summary]

  • Read 6 decimal numbers.
  • Print an integer number indicating how many positive numbers were there in the input.
  • Follow this number by the word " valores positivos".
#include <iostream>

using namespace std;

int main() {
  double a, b, c, d, e, f;
  cin >> a >> b >> c >> d >> e >> f;
  int counter = 0;
  if (a > 0) {
    counter++;
  }
  if (b > 0) {
    counter++;
  }
  if (c > 0) {
    counter++;
  }
  if (d > 0) {
    counter++;
  }
  if (e > 0) {
    counter++;
  }
  if (f > 0) {
    counter++;
  }
  cout << counter << " valores positivos" << endl;
  return 0;
}
  • For each input number we:
    • Declared a variable "double a".
    • Took it as input "using cin".
    • Checked if it's positive "using if".
  • What if there were more than 6 Numbers as input?
  • What if they were 10 numbers? 100 Numbers? Millions of numbers?...

For Loops

for ( INITIALIZATION; CONDITION; ASSIGNMENT ) {

    BODY

}

INITIALIZATION: What to do before starting the loop?

CONDITION: What is the condition to continue looping?

ASSIGNMENT: What to do after each iteration?

#include <iostream>

using namespace std;

int main() {
  int counter = 0;
  for (int i = 1; i <= 6; i++) {
    double x;
    cin >> x;
    if (x > 0) {
      counter++;
    }
  }
  cout << counter << " valores positivos" << endl;
  return 0;
}
  • The Lines from 8 to 12 will be repeated 6 times.
  • Each repetition is called iteration.

Assignment

Thanks

Content

Loops1

By Muhammad Magdi

Loops1

  • 169