Tuesday, November 29, 2011

Lesson #6: Branching with the if Decision Statement and the Conditional Operator

This lesson provides two things that we'll need to learn: 1. How to assign string values a user entered value. 2. How to do if/then statements. After this, I'll have some things for you to try on your own.


Lesson #6

I'm going to present a simple challenge for what we've learned so we can make sure we can do what we've supposedly learned. Create a program that asks for a person's first name and their last name and then says "Hello" and addresses the user. So if it was John Doe, the program would output "Hello John Doe" If you want to get more practice on some techniques, try having the program add a "!" at the end of it. I'll present what I write here, but stop reading now, try it yourself, and come back...

OK, you're back. Here's how I went about it:

            string firstName = "";
            string lastName="";
            Console.WriteLine("First name:");
            firstName = Console.ReadLine();
            Console.WriteLine("Last name:");
            lastName = Console.ReadLine();
            Console.WriteLine("Hello " + firstName + " " + lastName);
            Console.ReadLine();


If I wanted to add the "!" to the end, I would have changed the second to last line to:

Console.WriteLine("Hello " + firstName + " " + lastname + "!");

I also experimented and learned that if you change the "WriteLine" to "Write" it doesn't have the return after it writes what it's told to write. So instead of having the user enter their answer on the next line, they enter it right next to the ":" If I put a space after the ":" within the quote marks it provides a space between the ":" and the users answer. That's all just to make it look a little better.

No comments:

Post a Comment