C# - program about while loop [duplicate] - c#

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I'm a newbie to C# Programming and we're still starting on the loops. For our exercise today, we were tasked to create program using (while loop).
the question is :
Read 5 marks from the user, print the sum and "Passed" if the marks greater or equal to 50 or if among the marks there is only one mark less than 50.
if the user enters 2 marks less than 50 then the program should print STOP and end the program.
this is my try
unfortunately not complete and I can't do it
May you help me, please ?
int sum=0 , counter = 0, number=0 ;
while (counter < 5 || number < 50)
{
number = Convert.ToInt16(Console.ReadLine());
sum = sum + number;
counter++;
}
Console.WriteLine(sum + "\nPassed");

In the while loop you need && (and) instead of || (or).
After reading a number you can check if it's less than 50 or not and you can also count these.
So after the loop you need to check the lessCounter to decide to print Passed or STOP.
int sum = 0, counter = 0, number = 0, lessCounter = 0;
while (counter < 5 && lessCounter <= 1)
{
number = Convert.ToInt16(Console.ReadLine());
sum += number;
if (number < 50)
lessCounter++;
counter++;
}
if (lessCounter <= 1)
Console.WriteLine(sum + "\nPassed");
else
Console.WriteLine(sum + "\nSTOP");

Thank you all for all your effort and a time, special thanks to Mr.Szkup.
I was able to do it this way:
int number = 0, sum = 0, count = 0;
while (number < 5)
{
Console.Write("Input Number {0} : " , (number + 1));
int mark = Convert.ToInt16(Console.ReadLine());
if (mark < 50)
{
count++;
}
if (count == 2)
{
Console.WriteLine("\nStop\n");
break;
}
sum += mark;
number++;
}
if (count <= 1)
{
Console.WriteLine("\nsum = {0}\nPassed\n",sum);
}

Related

Trying to end a while loop once a 1 is randomly generated or it loops 10 times

(I apologize for the atrocious formatting)
I am attempting to make a random number generator (min = 1, max = 10) that loops until either
a) a 1 is generated (serve as primary sentinel).
b) loop iterates 10 times (secondary sentinel) without generating 1.
I am looking for something like this:
6 3 8 4 1
"A one was received in 5 attempts,"
or
3 8 5 7 2 2 4 8 8 3
"A one was never received."
but the problem is that the loop continues even if a 1 is generated, and the "A one was never recieved." message displays.
The loop is as follows:
while (randomNumber.Next() != 1 || loopCounter <= 10));
{
loopCounter++;
Console.WriteLine(randomNumber.Next(10));
Thread.Sleep(100);
if (randomNumber.Next() == 1)
{
Console.WriteLine($"A one was recieved in {loopCounter} attempts.")
break;
}
if (loopCounter <= 10)
{
Console.WriteLine("A one was not recieved.")
break;
}
}
giving something like
1 4 6 9 7 1 3 3 1 9 "A one was not recieved."
You more or less had the right idea for deducting whether each of the two conditions were met (aside from the sleeping thread ?).
But if you do it after initialising variables to track what you were doing rather than checking as you go along it's easier to produce a method that meets the requirements for what I'm assuming is a homework question.
Random rand = new Random();
int randomNumber = 0;
int maxLoops = 10;
string numbersSoFar = "";
for (int i = 1; i <= maxLoops; i++)
{
//Generate random number between 1 and 10:
randomNumber = rand.Next(1, 10);
numbersSoFar += randomNumber + " ";
if (randomNumber == 1)
{
Console.WriteLine(numbersSoFar);
Console.WriteLine("1 was found on loop number: " + i);
break;
}
else if (i == 10)
{
Console.WriteLine(numbersSoFar);
Console.WriteLine("10 loops completed, no 1 found.");
}
}
Since one of the conditions is that you have a maximum number of loops, you can use this in a for loop, rather than a while loop giving you access to an immediate iterator to compare against rather than declaring an extra value coupled with a while loop. This way it terminated automatically where as in your question you'd need a breakout/termination clause additionally for that.
Your main issue is that Next() returns a new random integer on each call, and without arguments returns any valid integer, so you have about a 1/(2^32) chance of getting 1. Instead you should be calling it once on each iteration and reading that result a few times. Your loop could look something like this:
List<int> nums = new List<int>();
for(int i = 0; i < 10; ++i)
{
nums.Add(randomNumber.Next(1, 10));
if(nums.Last() == 1)
{
break;
}
}
Console.Write(String.Join(" ", nums) + " ");
if(nums.Last() == 1)
{
Console.WriteLine("A 1 was received after " + nums.Length + " attempts");
}
else
{
Console.WriteLine("A 1 was not received.");
}

Correct ICCID algo

I need to validate ICCID, I found only one algo:
int numberStringLength = 18;
int cs = 0;
int dodd;
for (int i = 0; i < numberStringLength; i += 2)
{
dodd = Convert.ToInt32(iccid.Substring(i + 1, 1)) << 1;
cs += Convert.ToInt32(iccid.Substring(i, 1)) + (int)(dodd / 10) + (dodd % 10);
}
cs = (10-(cs % 10)) % 10;
if (cs == Convert.ToInt32(iccid.Substring(numberStringLength, 1)))
{
return true;
}
else
{
return false;
}
but it returns false for 100% right ICCID (89148000005339755555). Where can I get real ICCID algo?
Thanks
According to Wikipedia, ICCIDs use the Luhn algorithm.
Your code that you found is a bit broken, as it assumes that the value has an odd number of digits (an even number of normal digits, plus 1 check digit). It starts parsing the value from the left-most digit, and assumes that this left-most digit ("8" in your example) is not doubled and the next one ("9") is doubled. But this is not correct if the value has an even number of digits. The "8" should be the one that's doubled in your case.
Thankfully, it's very easy to implement the Luhn algorithm ourselves, properly, using that Wikipedia page as reference:
string input = "89148000005339755555";
int sum = 0;
// We'll use index i = 0 means the right-most digit, i = 1 is second-right, etc
for (int i = 0; i < input.Length; i++)
{
// Get the digit at the i'th position from the right
int digit = int.Parse(input[input.Length - i - 1].ToString());
// If it's in an odd position (starting from the right), then double it.
if (i % 2 == 1)
{
digit *= 2;
// If it's now >= 10, subtract 9
if (digit >= 10)
{
digit -= 9;
}
}
sum += digit;
}
// It's a pass if the result is a multiple of 10
bool pass = sum % 10 == 0;
Console.WriteLine(pass ? "Pass" : "Fail");
See it on dotnetfiddle.net.

Ask user to apply columns and rows for a 2d array

//Ask user how many woodchucks to simulate
while(!validNumber)
{
Write("How many woodchucks would you like to simulate? (1 - 100) ");
int.TryParse(ReadLine(), out woodchuckSim);
if((woodchuckSim <= 0) || (woodchuckSim > 100))
{
WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
}
if((woodchuckSim >= 1) && (woodchuckSim <= 100))
{
validNumber = true;
}
}
//Ask user how many days to simulate
while(!validDays)
{
Write("\nHow many days would you like to simulate? (1 - 10) ");
int.TryParse(ReadLine(), out numOfDays);
if((numOfDays <= 0) || (numOfDays > 10))
{
WriteLine("Please enter a positive whole number between 1 and 10: ");
}
if((numOfDays >= 1) && (numOfDays <= 10))
{
validDays = true;
}
}
//Using random class populate each cell between 1 and 50 that represents # of pieces of wood chucked by specific woodchuck on that specific day
int[,] sim = new int[woodchuckSim, numOfDays];
WriteLine($"{woodchuckSim} {numOfDays}");
for (int i = 0; i < sim.Length; i++)
{
for (int j = 0; j < sim.Length; j++)
{
sim[i, j] = ran1.Next(1, 50);
WriteLine(sim[i, j]);
}
}
WriteLine("Press any key to continue...");
ReadLine();
So this is my code so far, and I keep getting a "Index was outside the bounds of the array" error and I'm basically trying to ask the user to input the numbers of woodchucks and the number of days then populate the 2d array with random numbers. Any help will be really appreciated, and btw I am a beginner in programming. Thanks!
As Quercus already said, Length property refers to overall size of the array and array.GetLength(index) should be used instead.
Moreover, since you are a beginner in programming as you mentioned, I would like to tell you as an advice that it would be better to use if-else statement in this case:
if((woodchuckSim <= 0) || (woodchuckSim > 100)) {
WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
} else {
validNumber = true;
}
If-else statement is pretty basic but important concept in programming and since your if hypotheses are mutual exclusive you can use it here for a nicer code.
You have incorrect cycle bounds. sim.Length is an overall size of array, which is woodchuckSim * numOfDays.
To get size of each dimension use sim.GetLength(0) and sim.GetLength(1) respectively.
Length is the size of the first dimension of the array - the number of Woodchucks in your case. For the size of the other dimensions, you could use GetLength(index):
for (int i = 0; i < sim.GetLength(0); i++)
{
for (int j = 0; j < sim.GetLength(1); j++)
{
sim[i, j] = ran1.Next(1, 50);
WriteLine(sim[i, j]);
}
}

How to reverse the print out of numbers

I'm currently trying to learn C# for my university degree and I can't work out how to get my code to print out only the even numbers from 0-100 starting at the largest number i.e 100 down too 0. I have the code printing the output from smallest to largest but cannot get it to go the other way around.
Can anyone give me a hand?
This is my code:
Console.WriteLine("Print first 100 even No in reverse");
for (int i = 1; i < 100; i++)
{
if (i % 2 == 0)
{
Console.Write(i + " ");
}
}
You need to replace your code with this code:
Console.WriteLine("Print first 100 even No in reverse");
for (int i = 100; i >= 0 ; i--)
{
if (i % 2 == 0)
{
Console.Write(i + " ");
}
}
you just need to start your loop from 100 and decrease from there:
for (int i = 100; i >= 0; i--)
use ">" instead of ">=" operator, if you don't want the zero included

How to do the loop and solve the following

I'm supposed to code a program that writes out a division just like in school.
Example:
13:3=4.333333333333
13
1
10
10
10....
So my approach was:
Solve the division then get the solution in a List.
Then question if the first number (in this case 1) is divisible by 3.
If not put it down and add the second number and so on...
I managed to do this the first time. It's sloppy but works. The problem is that it only works with numbers that when divided get to have a decimal in it.
Exapmle:
123:13
This is the first code:
do
{
for (int number = 1; number <= divNum; number++)
if (number % divisor == 0) countH++;
for (int i = 0; i < count; i++)
Console.Write(" ");
if ((c = divNum % divisor ) < divisor )
{
Console.WriteLine(" " + ((divNum- (countH * divisor ))) * 10);
}
else Console.WriteLine(" " + (divNum- (countH * divisor )));
c = divNum % divisor ;
if (c < divisor )
{
divNum = c * 10;
}
count++; countH = 0;
} while ((divNum >= divisor ) && (count < x));
Any ideas or help? Sorry if this is a bad question.
************ added
Try of a better explanation:
1 cant be divided by 13, so it goes down, we get the 2 down and try 12 divided by 13, still nothing so we get the 3 down and try 123:13, 13 goes 9 times in 123 so we have 123-9*13 = 6 the six goes down we write 9 in the result. We try 6:13 not going so we drop a 0 next to 6. Next we try 60:13, 13 goes 4 times so 60-4*13 = 8, we get the 8 down. And so on..
123:13=9.46153....
123
60
80
20
70
50
....
Something like this should work. Not the fastest solution most likely, but should do the job.
var number = 123;
var b = 12;
int quotient;
double remainder = number;
var x = 10;
do
{
quotient = (int)Math.Floor(remainder / b);
remainder = remainder - (quotient * b);
for (int i = 0; i < count; i++)
Console.Write(" ");
remainder *= 10;
Console.WriteLine(" " + remainder);
count++;
} while ((remainder > 0) && (count < x));

Categories

Resources