Euroman_21
asked on
A little C# question
Hi
I'm fooling around with C# and made a small program which takes a string calculates its length and then finally prints the whole string and the length.
using System;
class StringInput
{
public static void Main() {
string strInput = Console.ReadLine();
for (int i = 1; i < strInput.Length; ++i)
if (strInput.Length < i *i) {
Console.WriteLine("Hi, " + strInput + " Your Name " + strInput.Length + " characters
long.");
}
}
}
If I type Bill Clinton as input, I get the following output:
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Why does it the program do (length of input X numbers of repeats)
/Fred
I'm fooling around with C# and made a small program which takes a string calculates its length and then finally prints the whole string and the length.
using System;
class StringInput
{
public static void Main() {
string strInput = Console.ReadLine();
for (int i = 1; i < strInput.Length; ++i)
if (strInput.Length < i *i) {
Console.WriteLine("Hi, " + strInput + " Your Name " + strInput.Length + " characters
long.");
}
}
}
If I type Bill Clinton as input, I get the following output:
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Hi, Bill Clinton Your Name 12 characters long.
Why does it the program do (length of input X numbers of repeats)
/Fred
ASKER
Hi Fernando,
What do I need to change to avoid that the loop run 8-times??
Fred
What do I need to change to avoid that the loop run 8-times??
Fred
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The for statement goes through the loop strInput.Length - 1 times. The length of the string “Bill Clinton” 12 characters long. The if statement inside the for loop will only be true when strInput.Length < i * i. So for i = 1, 2, 3 the Console.Writeline will not execute. For the i = 4, 5, 6, 7, 8, 9, 10, and 11 the Console.Writeline will execute. For the 8 times that the Console.Writeline executes it prints the same thing because the values of strInput and strInput.Length never change.
Fernando