How to reverse the print out of numbers - c#

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

Related

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]);
}
}

C# - program about while loop [duplicate]

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);
}

Project Euler #23 in C#

Project Euler challenge 23 states this:
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
So I've been trying to get this working, however I keep getting back an incorrect result, I'm not sure where this is going wrong in the code though I have:
static void Main(string[] args)
{
List<int> abundantNums = Enumerable.Range(12, 1000000).Where(i => isAbundant(i)).ToList();
abundantNums = abundantNums.Distinct().ToList();
var boolArr = new bool[28124];
for (int i = 0; i < abundantNums.Count; ++i)
{
for (int j = i; j < abundantNums.Count; ++j)
{
var sum = abundantNums[i] + abundantNums[j];
if (sum < 28124) boolArr[sum] = true;
else break;
}
}
var total = 0;
for (int i = 0; i < boolArr.Length; i++)
{
if (boolArr[i] == false)
{
total += i;
}
}
Console.WriteLine(total);
Console.ReadKey();
}
static bool isAbundant(int num)
{
if (getFactors(num).Sum() > num)
{
return true;
}
else
{
return false;
}
}
And then to find the factors of a number I have:
static List<int> getFactors(int num)
{
List<int> factors = new List<int>();
Stopwatch watch = Stopwatch.StartNew();
for (int i=1; i < Math.Sqrt(num) + 1; i++)
{
if (num % i == 0)
{
factors.Add(i);
if (num / i != i)
{
factors.Add(num / i);
}
}
}
watch.Stop();
factors.Remove(num);
return factors;
}
Now I've been at this for a day or two and as far as I can tell this should be doing the trick, anyone wiser than I able to point out my failings?
The problem is your getFactors loop. Change:
for (int i=1; i < Math.Sqrt(num) + 1; i++)
to
for (int i=1; i <= Math.Sqrt(num); i++)
And it should work. I'll let you try and understand why :-)

Find number on a certain position in array, depending on some rules, added plural to "numbers"

I am a beginner to programming and I am attempting to write a program that should solve the following mathematical problem:
"On a circle we have 108 numbers. The sum of any 20 consecutive numbers is always 1000. At position "1" we have the number 1, at position "19" we have the number 19 and at position "50" we have number 50. What number do we have on position "100"?" The numbers are always integers.
Up to this point i know how to use array and looping structures like "for".
I attempted to set a variable "check" which I initialized it as "false" in order to change it later to true, when I will find the number on position "100".
My initial thought is to go through the array and make the sum of each 20 consecutive numbers. I used two variables in order to assign values for each position that is not 1, 19 or 50 and then make the sum. I did this in two "for" structures, one inside another. Of course, this creates an issue that i am not able to properly calculate the values of the first 20 number.
I checked on the MSDN some information about the "Queue" structure, yet I can't understand how to use it in my particular case.
Let me know please if anyone has some suggestions on how i should handle this.
Thank you.
As you asked, here is the code that I have managed to write so far. Please take into consideration that I am really in the begging of programming and I still have a lot to learn.
check = true;
int[] array = new int[108];
for (counter = 1; counter <= array.Length; counter++)
{
if (counter !=1 || counter !=19 || counter !=50)
{
for (i = 1; i <= 999; i++)
{
array[counter] = i;
if (counter >= 20)
{
for (consecutive = counter; consecutive => 2; consecutive--)
{
checkValue = array[consecutive] + array[consecutive]-1;
}
if (checkvalue != 1000) check = false;
}
}
}
}
As say #fryday the code of this problem doesn't mean anything without logic, so you should understand well the solution before read this.
Let me explain to you the logic of this problem and then read the code (you will see that is quite simple). First you may note that each time you get 20 consecutive numbers, the next number must be equal to the first in the 20 consecutive, because you have
x_1 + x_2 + ... + x_20 = 1000
and
x_2 + ... + x_20 + x_21 = 1000
so
x_1 + x_2 + ... + x_20 = x_2 + ... + x_20 + x_21
and finally
x_1 = x_21
Following this insight all we have to do is walk through the array starting at each one of this positions 1, 19 and 50, fill the positions in the array with this values and then calculate the next position adding 20 to the current and mod by 108, repeat the process until the value in the array is equal to 1, 19 or 50 in each case. Then the values in the array equals to 0 means that all must have the same value (and has not found yet). To found this value sum 20 values consecutive and divide the difference with 1000 by the count of elements with value equal to 0 in such 20 consecutive. You can notice that the position 100 is one of this that have value equals to 0. Finally we get the value of 130.
This is the code:
using System;
namespace Stackoverflow
{
class Program
{
static void Main(string[] args)
{
int[] values = { 1, 19, 50 };
int[] arr = new int[108];
foreach (var val in values)
{
int pos = val - 1;
while (arr[pos] != val)
{
arr[pos] = val;
pos += 20;
pos %= 108;
}
}
int sum = 0;
int zeros = 0;
for (int i = 0; i < 20; i++)
{
if (arr[i] == 0) zeros++;
sum += arr[i];
}
Console.WriteLine((1000 - sum) / zeros);
}
}
}
I solved this problem with array, but better use some type of cycle list. It's about structure choice.
In general you should solve this problem with logic, computer only can help you to check result or visualize data. I'll append code which show how I use array for solving this problem:
N = 108
step = 20
a = [None] * (N + 1)
def toArrayIndex(i):
if i < 0:
return toArrayIndex(N + i)
if i % N == 0:
return N
else:
return i % N
def setKnownNumbers(value, index):
while a[toArrayIndex(index)] != value:
if a[toArrayIndex(index)] != None:
print "ERROR: problem unsolvable i = %d" % toArrayIndex(index)
a[toArrayIndex(index)] = value
index += step
setKnownNumbers(1, 1)
setKnownNumbers(19, 19)
setKnownNumbers(50, 50)
Now you only need to understand how finish it. It's not hard ;)
You can use thi code to output array and check correctness
# output
for i in range(1,N + 1):
print i, a[i]
counter = 0
for i in range(1,N + 1):
s = 0
for j in range(0,step):
s += a[toArrayIndex(i + j)]
if s == 1000:
counter += 1
if counter == N:
print "Correct"
print "a[100] = %d" % a[100]

Exiting loop without break/return/if

If you have a for loop:
for(i=0;i<10;i++){}
Now, when i==5, how can I exit the for loop completely without using break, return, or if?
The best I could come up with was this:
for (int i = 0; i < 10; i++)
{
i = (i == 5) ? 10 : i;
Trace.WriteLine("i = " + i.ToString());
}
...which will cause the loop to run six times (i=0..5) and display this..
i = 0
i = 1
i = 2
i = 3
i = 4
i = 10
The alternative way to "exit the loop" (in a particularly nasty fashion) would be to do this...
for (int i = 0; i < 10; i++)
{
int a = 3 / ((i == 5) ? 0 : 1);
Trace.WriteLine("i = " + i.ToString());
}
..which crashes out, errr, successfully exits the loop without using the break, return or if commands.
i = 0
i = 1
i = 2
i = 3
i = 4
A first chance exception of type 'System.DivideByZeroException' occurred in MikesProgram.dll
language is C# .it was an interview question actually..curious
Do I get the job ?
I would need to check your health & dental plans, and I have to leave early on Thursdays to collect my daughters from school.
;-)
for (int n = 0; n < 10; n++)
{
n += (n / 5) * 5;
}
well here's another way if you want to break the processing exactly when i = 5 without using break, return, or if
for (int lowsetLimit = 0, highestLimit = 10, i = lowsetLimit; i < highestLimit; i++)
{
//normal code which process before i gets eqaul to 5 goes here...
i = (i < 5) ? i : highestLimit; //and here is the pivot point.
}
for(i=0;i<10;i++){
(i==5) ? goto Outer : //do something;
}
Outer:
//do something
The question says that loop should end when i=5, It says nothing about start, So this should be valid (ternary operator solution is better, but if we are not allowed to use any conditional operator)
for (int i = 0; i < 10; i++)
{
i=i-4;
Console.WriteLine("i = " + i.ToString());
i=i+4;
}
this Starts at -4 and ends at 5.
The real answer of course would be the following:
for (i=0; i!=5; i++)
{
// do something
}
But let's make it a bit more generic: stop if (expression) becomes true.
The second argument of the for loop is a boolean expression which determines whether to continue the loop with the next element or not.
So if you want to stop looping because of any condition:
for (i=0; !(expression) && i<10; i++)
{
// do something
}
This works using while and goto:
for (int i = 0; i < 10; i++)
{
while (i < 5)
{
Console.Write(i + " ");
goto OutsideWhile;
}
OutsideWhile:
continue;
}
// 0 1 2 3 4

Categories

Resources