202k views
2 votes
Write a while loop that adds the first 100 numbers (from 1 to 100) together. To do so, use a while loop that continues while the condition of cur_num being less than or equal to stop_num is True. Inside the loop, it should add cur_num to the running total variable, and also add 1 to cur_num. Make sure to check at the end that the value of total reflects the total summation.

User DJeanCar
by
2.9k points

1 Answer

0 votes

Answer:

I am writing JAVA and C++ program. Let me know if you want the program in some other programming language.

Step-by-step explanation:

JAVA program:

public class SumOfNums{

public static void main(String[] args) { //start of main function

int cur_num = 1; // stores numbers

int stop_num= 100; // stops at this number which is 100

int total = 0; //stores the sum of 100 numbers

/* loop takes numbers one by one from cur_num variable and continues to add them until the stop_num that is 100 is reached*/

while (cur_num <= stop_num) {

total += cur_num; //keeps adding the numbers from 1 to 100

//increments value of cur_num by 1 at each iteration

cur_num = cur_num + 1;}

//displays the sum of first 100 numbers

System.out.println("The sum of first 100 numbers is: " + total); }}

Output:

The sum of first 100 numbers is: 5050

C++ program

#include <iostream> //for input output functions

using namespace std; //to identify objects like cin cout

int main(){ //start of main() function body

int cur_num = 1; // stores numbers

int stop_num= 100; // stops at this number which is 100

int total = 0;//stores the sum of 100 numbers

/* loop takes numbers one by one from cur_num variable and continues to add them until the stop_num that is 100 is reached*/

while (cur_num <= stop_num) {

//keeps adding the numbers from 1 to 100

//increments value of cur_num by 1 at each iteration

total += cur_num;

cur_num = cur_num + 1; }

//displays the sum of first 100 numbers

cout<<"The sum of first 100 numbers is: "<<total; }

The output is given in the attached screen shot.

Write a while loop that adds the first 100 numbers (from 1 to 100) together. To do-example-1
Write a while loop that adds the first 100 numbers (from 1 to 100) together. To do-example-2
User Chris Aldrich
by
3.3k points