Consider the following C# program that reads a line from the console and prints it back with a greeting.
using System;
class Program {
static void Main() {
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
}
}If the user types Anna and presses Enter, what will be printed?
using System; class Program { static void Main() { string name = Console.ReadLine(); Console.WriteLine($"Hello, {name}!"); } }
Remember that Console.ReadLine() reads the exact text the user types.
The program reads the input string Anna and stores it in the variable name. Then it prints Hello, Anna! using string interpolation.
Look at this C# code:
using System;
class Program {
static void Main() {
string input = Console.ReadLine();
if (input == "") {
Console.WriteLine("Empty input");
} else {
Console.WriteLine("Input received");
}
}
}If the user just presses Enter without typing anything, what will be printed?
using System; class Program { static void Main() { string input = Console.ReadLine(); if (input == "") { Console.WriteLine("Empty input"); } else { Console.WriteLine("Input received"); } } }
Pressing Enter without typing anything returns an empty string, not null.
Console.ReadLine() returns an empty string if the user presses Enter immediately. The condition input == "" is true, so it prints Empty input.
Examine this C# code snippet:
using System;
class Program {
static void Main() {
int number = int.Parse(Console.ReadLine());
Console.WriteLine(number * 2);
}
}If the user types abc and presses Enter, what error will occur?
using System; class Program { static void Main() { int number = int.Parse(Console.ReadLine()); Console.WriteLine(number * 2); } }
Think about what happens when you try to convert a non-number string to an integer.
Trying to convert the string "abc" to an integer using int.Parse causes a FormatException because "abc" is not a valid number.
Which of the following C# code snippets correctly reads a line from the console and converts it to a double variable named value?
Remember to call methods with parentheses ().
Options A and B correctly call Console.ReadLine() with parentheses and use valid conversion methods (double.Parse and Convert.ToDouble). Options C and D miss the parentheses on ReadLine, causing syntax errors.
Consider this C# program:
using System;
class Program {
static void Main() {
int count = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 0; i < count; i++) {
int num = int.Parse(Console.ReadLine());
sum += num;
}
Console.WriteLine(sum);
}
}If the user inputs the following lines:
3 10 20 30
How many times will the for loop run, and what will be the output?
The first input line tells how many numbers to read next.
The first input is 3, so the loop runs 3 times. The numbers 10, 20, and 30 are read and summed. The sum is 60.