---
title: CSCI 1301 -- Lab 17
author: Clément Aubert
lang: en
fontsize: 10pt
documentclass: scrartcl
numbersections: true
links-as-notes: true
papersize: letter
geometry: margin=1in
keywords:
- Computer Science
- Problem solving methods
- Syllabus
- Augusta University
- Bachelor of Science
---

# Flavors of while loops

- Write a `while` loop asking the user for an integer, and looping as long as that integer is stricly greater than $0$.
- Transform your `while` loop so that the program displays the sum of all the numbers entered when exiting the `while` loop.

An example of execution could be:

~~~~~~~~{.bash}
Enter a positive number to sum, or a negative number to exit
12
Enter a positive number to sum, or a negative number to exit
3
Enter a positive number to sum, or a negative number to exit
-2
Your total is 15.
~~~~~~~~

Identify what type of loop it is: is it user-controlled, counter-controlled, or sentinel-controlled?
Does it use a counter, a sentinel value, or an accumulator?


<!--
Console.WriteLine("Enter a positive number to sum, or a negative number to exit");
string enter = Console.ReadLine();
int entered = int.Parse(enter);
int sum = 0;
while (entered > 0)
{
    sum += entered;
    Console.WriteLine("Enter a positive number to sum, or a negative number to exit");
    enter = Console.ReadLine();
    entered = int.Parse(enter);
}
Console.WriteLine($"Your total is {sum}.");
-->
# TryParse Method

## Getting Familiar With It

Consider the code we just studied:

~~~~~~~~{.cs}
Console.WriteLine("Please, enter an integer.");
string message = Console.ReadLine();
int a;
bool res = int.TryParse(message, out a);
if (res)
    {
        Console.WriteLine($"The value entered was an integer: {a}.");
    }
else
    {
        Console.WriteLine("The value entered was not an integer, so 0 is assigned to a.");
    }
Console.WriteLine(a);
~~~~~~~~

What happen if:

- The user enters an integer?
- The user enters a floating-point value?
- The user enters nothing?
- The user enters a string that contains alphabetical characters?

## Using It

#. Write a code that ask the user to enter an integer, and ask the user again as long as the user entered something that isn't an integer.
#. Actually, there is a `TryParse` method in other classes as well: there is for instance a `Double.TryParse` and a `Decimal.TryParse` method. Write a small program that uses one of them.

