-3

I am a newbie and this is my homework for school. The program is suppose to print from 1 to 5 (not 5 to 1) and so far, i have only been able to make the program print from 5 to 1, any assistance with this will be appreciate. the program should only use while loop

#include <iostream>
#include <stdlib.h>

using namespace std;

int main (int argc, char *argv[])
{
    //if statement to check only 2 argument can be passed
    if (argc != 2)
    {
            cout << "ERROR!" << endl;
    }
    else
    {
            if (atoi(argv[1]) < 1)          //if statement to check negative numbers
            {
                    cout << "ERROR!"<< endl;
            }
            int temp = atoi(argv[1]);       //convert the number inthe character argument to integer
            int sum = 0;                    //variable declaration to find the sum passed in the while loop

    //the while loop is used to print out the numbers entered in descending order
    while (temp > 0)
    {
            cout << temp << endl;           //output numbers in the iteration
            sum = sum + temp;               //sums the number of iteration
            temp --;                        //counter, used to stop the while loop to avois an infinity loop
    }

    cout << "Sum is " << sum << endl;
    }

    return 0;

}

leet
  • 9
  • 3
  • 3
    Please take a look at this [C++ books list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read one of the introductory books. – Ron Sep 08 '17 at 02:59

1 Answers1

2

use a for loop

for(int i=1;i<=temp;i++){
        cout << i << endl;        //output numbers in the iteration
        sum = sum + i;
 }

or with a while loop like this

   int counter=1;

   while (counter<=temp)
    {
            cout << counter << endl;           //output numbers in the iteration
            sum = sum + counter;               //sums the number of iteration
            counter ++;                        //counter, used to stop the while loop to avois an infinity loop
    }

https://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm

Lucas Hendren
  • 2,786
  • 2
  • 18
  • 33
  • Thanks, but the instructors insisted on while loop for the homework – leet Sep 08 '17 at 03:00
  • 1
    @leet if there are additional requirements then you need to put them in your question so people don't waste their time writing correct answers that don't actually help you. Please edit your question and put ALL the requirements in your question. – xaxxon Sep 08 '17 at 03:06
  • @xaxxon, sorry about that. I will edit the question. – leet Sep 08 '17 at 03:17