-4

Task: to make console to display a message "Happy birthday!". Number of messages equals the number which user inputs to console.

Condition: program should break the cycle, when number of messages equals 5 or more.

The problem: my code works correct without "if" condition. When I add condition if (age == 5), and user's input is "6" or more, console shows just 1 message!

First of all I thought about mistakes in my code, but I didn't find it. Then I copied code 1 in 1 from the learning video (I learn C# with video course), but the code still works incorrect, when in video it works perfectly!

Here is my code:

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

namespace Learning
{
    class Program
    {
        static void Main(string[] args)
        {
            int age;
            Console.Write("Please, input your age: ");
            age = Convert.ToInt32(Console.ReadLine());

            while (age-- > 0)
            {
                Console.WriteLine("Happy Birthday!");

                if (age == 5)
                {
                    break;
                }
            }
        }
    }
}
5
  • 1
    Please edit your question to include the original task given by the author/instructor. Maybe you read it incorrectly and wrote the wrong code. Commented Jul 6 at 8:09
  • 1
    When I add condition if (age == 5), and user's input is "6" or more, console shows just 1 message! of course because age do not count the number of times you written the message Commented Jul 6 at 8:12
  • Tell us what you think -- does. Commented Jul 6 at 8:39
  • 1
    When I add condition if (age == 5), and user's input is "6" or more, console shows just 1 message! That is not true. If you enter 7, you will see it twice. Commented Jul 6 at 8:39
  • The following may be of interest: Debug for absolute beginners. Also see this post about how to write pseudo-code. Commented Jul 6 at 16:09

4 Answers 4

0

When I add condition if (age == 5), and user's input is "6" or more, console shows just 1 message!

of course because age does not count the number of times you written the message, except if you enter a number from 0 up to 5

A simple way from your program is to limit age to 5 before to enter in the loop :

using System;

namespace Learning
{
    class Program
    {
        static void Main(string[] args)
        {
            int age;

            Console.Write("Please, input your age: ");
            age = Convert.ToInt32(Console.ReadLine());

            if (age > 5)
              age = 5;
              
            while (age-- > 0)
              Console.WriteLine("Happy Birthday!");
        }
    }
}

of course now to name the variable age is not appropriate


Additional remarks :

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

Why all these useless using ?

Condition: program should break the cycle, when number of messages equals 5 or more

this statement is weird because or more has non sense

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you very much, mr. Bruno, but I need to understand the mistake while using "break"
your loop can stop on two conditions, first if age values 0 before to do (age-- > 0) or when (age == 5) in the if. If you input 6 for the age, (age-- > 0) is false and then you print the message, but age values now 5 and then the if does the break. If you input 7 you loop one time more etc. If the input age is less than 5 then (age == 5) is never true and you loop until it become 0
your problem is not only the break but the overall with these two antagonist conditions. In my proposal the loop has only one condition to stop, and I manage first and out of the loop the case when age is greater than 5. You can also see the code is more simple and does not need two variables
Is it clear now ? You need to learn to use a debugger to see how your variables change during the execution, that will help you to understand what happens
Thank you very much, sir! I guess step by step code execution could help me understand processes deeper
ok. to indicate your problem is solved I encourage you to 'accept' one of the answers (for instance mine of course, you can 'accept' only one). You can also 'upvote' any number of answers you think useful for you (including the 'accepted' one) What should I do when someone answers my question?
0
using System;

namespace Learning
{
    class Program
    {
        static void Main(string[] args)
        {
            int age;
            Console.Write("Please, input your age: ");
            age = Convert.ToInt32(Console.ReadLine());

            int nMessages = 0;
            while (age-- > 0)
            {
                Console.WriteLine("Happy Birthday!");

                nMessages++;
                if (nMessages == 5)
                {
                    break;
                }
            }
        }
    }
}

The problem is that you do "break" when the "age" variable equals 5, not when you've printed five message

5 Comments

I don't comment on other answers when I've posted one myself, but I'm going to make an exception, not to disturb you but in the hope that this is useful to you. First, you haven't explained to the OP why his program doesn't work, even though he would like to understand why. Then, your proposal is unnecessarily complicated with two variables (age and nMessages) when one is enough (see my own answer). That can explain why you had a dv (not from me)
Agree with "First, you haven't explained to the OP why his program doesn't work, even though he would like to understand why.". Don't agree with "Then, your proposal is unnecessarily complicated with two variables (age and nMessages) when one is enough". Less variables != better code :)
Complicated code is not good code. Your code is unnecessary complicated managing your two vars. Is the statement speaks about age ? no, so you can do what you want with the input number. In your loop you decrease and test the two vars, that is useless, unclear and expensive for nothing. I really hope you will understand that for the next codes you will do ;-)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
@MaximTishalovich, Max, spasibo tebe bol'shoye! It's the most useful answer of the post! Can you tell me, please, how "age" binds with "nMessages"? I don't understand the connection, because user inputs only "age", not "nMessages", and I don't see any condition like "nMessages = age"
0

This is perfect example of more general rule called Single Responsibility Principle.

Here you got yourself to a problem where code becomes hard to reason about and you quickly got lost.

This is because age has now responsibility to store age information as well as control the loop.

Better is to have separate variable for controlling the loop.

More readable version of your code would be:

static void Main(string[] args)
{   
    Console.Write("Please, input your age: ");
    var age = Convert.ToInt32(Console.ReadLine());
 
    const int MAX_LOOP_EXECUTIONS = 5;
    var loopExecutions = Math.Min(MAX_LOOP_EXECUTIONS, age);
    var loopExecutionsCount = 0;

    while (true)
    {
        Console.WriteLine("Happy Birthday!");
        loopExecutionsCount++;

        if (loopExecutionsCount >= loopExecutions)
        {
            break;
        }
    }
}

or

static void Main(string[] args)
{   
    Console.Write("Please, input your age: ");
    var age = Convert.ToInt32(Console.ReadLine());

    const int MAX_LOOP_EXECUTIONS = 5;
    var loopExecutions = Math.Min(MAX_LOOP_EXECUTIONS, age);
    var loopExecutionsCount = 0;

    while (loopExecutionsCount < loopExecutions)
    {
        Console.WriteLine("Happy Birthday!");
        loopExecutionsCount++;
    }
}

Comments

-3
Console.Write("Please, input your age: ");
int age = Convert.ToInt32(Console.ReadLine());

int counter = 0;

while (counter < age)
{
    if (counter >= 5)
    {
        break;
    }

    Console.WriteLine("Happy Birthday!");
    counter++;
}

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.