Objective
Write a C# program to ask the user for an undetermined amount of numbers (until 0 is entered) and display their sum, as follows:
Number? 5
Total = 5
Number? 10
Total = 15
Number? -2
Total = 13
Number? 0
Finished"
Write Your C# Exercise
C# Exercise Example
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
int number; // Declaring a variable to store the number entered by the user
int total = 0; // Declaring and initializing the total variable to 0
// Using a while loop to repeatedly ask for numbers until 0 is entered
while (true) // The loop will continue indefinitely until 0 is entered
{
// Asking the user to enter a number
Console.Write("Number? ");
number = Convert.ToInt32(Console.ReadLine()); // Converting the input to an integer
// Breaking out of the loop if the number entered is 0
if (number == 0) // If the entered number is 0, the program will stop
{
break; // Exiting the loop
}
// Adding the entered number to the total
total += number; // Accumulating the sum of the numbers
Console.WriteLine("Total = " + total); // Displaying the current total
}
// Displaying the finished message once the loop ends
Console.WriteLine("Finished"); // Informing the user that the program has finished
}
}
More C# Programming Exercises of Flow Control
Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.
In this C# exercise, you will learn how to write a program that prompts the user to enter two numbers and determines whether both numbers are negative or not. This type of p...
In this C# exercise, you will learn how to write a program that prompts the user to enter two numbers and then determines whether both numbers are negative, only one is nega...
In this exercise, you will learn how to use the modulo operator % to find numbers between 1 and 500 that are divisible by both 3 and 5. The program will...
This exercise teaches you how to display a number repeated a number of times specified by the user. Three loop structures will be used to perform the repetition: while, d...
In this C# programming exercise, the user is asked to enter their login and password, both as integer numbers. The goal is to create a program that repeatedly ...
This C# exercise aims to create a program that asks the user for their login and password (both must be integer numbers) and repeats the request until the ente...