Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying to learn to code in C#. This is the first language I chose to learn how to code. However, I have been practicing some problems from the book I'm referring from and learning from. One of the problems is as follows.

Write a program that reads five integer numbers and prints their sum. If an invalid number is entered the program should prompt the user to enter another number.

While I'm able to write the required code both using a LOOP and using normal typed lengthy codes, I'm unable to figure out how my code is working. :-) :-) Sounds funny...!!

But I'm not able to figure out why the code is still printing Your sum is: when the condition I've mentioned for it is FALSE. Although it is working in the desired manner I'm not able to figure out how...

If someone can look at the code and mention the reason why it is working would be very helpful.

English is not my native language. If you need any more info please let me know.

Thanks in advance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch4ExQ7
{
    class Program
    {
        static void Main(string[] args)

   Console.Write("How many numbers to sum?: ");
            int num = int.Parse(Console.ReadLine());
            int sum = 0;
            bool parseTry = false;  // parseTry is defined here as after initialising it in the for loop
                            // its scope is limited to that loop only.

            Console.WriteLine("Enter your numbers: ");
            {
                for (int i = 1; i <= num; i++)
                {
                    string str = Console.ReadLine();
                    parseTry = Int32.TryParse(str, out int parsed);

                    if (parseTry == true)
                    {
                        sum += parsed;
                    }
                    else
                    {
                        Console.WriteLine("Enter only integers.");
                    }

                }
                if (parseTry == true)
                {
                    Console.WriteLine("Your sum is: " + sum); //Why this sentence is printed while in the Main() method parseTry is set to false
                }
           }
   }
}


What I have tried:

Banged my head for about 2hrs. Scoured the internet but couldn't understand. Feeling dumb :-)
Posted
Updated 29-Apr-18 20:19pm

Thanks everyone for your replies. I found all the solutions useful. Once I complete the basics of C# I will definitely start with more advanced topics such as debugger and understanding VStudios better for developing window based apps rather than console based.

Thanks again.
 
Share this answer
 
Probably a better way to understand the code would be to debug it. Use the debugger to go through the code line-by-line. Investigate the variables, see what affects the execution and so on. Mastering the debugger is one of the key skills for a developer.

For starters, have a look at Get started with the debugger - Visual Studio | Microsoft Docs[^]
 
Share this answer
 
Your loop counter (i) is advancing regardless of whether you have a valid number or not. Consider changing "; i++)" to "; )" and adding an "i++;" following "sum += parsed;".

Assuming you do this, you will never exit the loop until you have entered the requested number of valid integers. Thus, the final check of parseTry is unnecessary. In fact, with those changes, you can make parseTry a variable local to the loop.
 
Share this answer
 
Quote:
I'm unable to figure out how my code is working.

Quote:
There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.
Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
Debugging C# Code in Visual Studio - YouTube[^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
Specifically I can suggest the following solution to the problem stated:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch4ExQ7
{
    class Program
    {
        static void Main(string[] args)

   Console.Write("How many numbers to sum?: ");
            int num = int.Parse(Console.ReadLine());
            int sum = 0;
            bool parseTry = false;  // parseTry is defined here as after initialising it in the for loop
                            // its scope is limited to that loop only.

            Console.WriteLine("Enter your numbers: ");
            {
                int num_count = 0;
                for (int i = 1; i <= num; i++)
                {
                    parseTry = false; // Here you have to initialize parseTry variable to false overagain
                       
                    // Implement a loop during each iteration of which you will scan a string value of number by using Console.ReadLine() and store the result into str variable              
                    do {
                           string str = Console.ReadLine();
                           // Convert the stringified numeric value to integer by using Int32.TryParse method
                           parseTry = Int32.TryParse(str, out int parsed);

                           // If the convertion was suceessful, then accumulate the value of parsed by summing it up with sum variable and increment the count of valid numbers entered num_count by 1.
                           if (parseTry == true)
                           {
                               sum += parsed; num_count++;
                           }
                           else
                           {
                               // If not, pring the assertion method
                               Console.WriteLine("Enter only integers.");
                           }
                    // Proceed with next iteration until you've entered a valid numeric value
                    }while(parseTry == false);

                }
                // If the number of entered values is at least equals to 3
                if (num_count >= 3)
                {
                    // Print out the value of sum variable containing an accumulated total sum value
                    Console.WriteLine("Your sum is: " + sum); //Why this sentence is printed while in the Main() method parseTry is set to false
                }
           }
   }
}

Normally, your code was missing one more loop executed until you've entered a valid parsable value for each of those three numbers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900