Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the Correct output using " while loop "?

The Expected Output is 2000 but it stops on 1980.

Note: The Execution is started from 20 and not from 0 as int i = 1

The Code:

#include <iostream>
using namespace std;
int main() {
  const int iarraysize = 100;
  int i = 1;
  int iarray[iarraysize];
  while (i < iarraysize) {
    iarray[i] = 20 * i;
    cout << iarray[i++] << "\n";
  }
}
like image 625
Arnold-Baba Avatar asked Dec 22 '22 18:12

Arnold-Baba


2 Answers

Arrays start at 0, and end one before their size.

You don't need an array however.

#include <iostream>
int main()
{
    int limit = 100;
    int i = 1;
    while (i <= limit)
    {
        std::cout << (i++ * 20) << "\n";
    }
}
like image 194
Caleth Avatar answered Jan 08 '23 07:01

Caleth


The last value of the variable i that is less than 100 is 99. So 20 * 99 is equal to 1990.

If you want to get 2000 then rewrite the loop like

int i = 0;
while (i < iarraysize) {
  iarray[i] = 20 * (i + 1);
  cout << iarray[i++] << "\n";
}
like image 38
Vlad from Moscow Avatar answered Jan 08 '23 06:01

Vlad from Moscow