Trying to implement a simple for loop that works 0 and the end at the same time, the problem i'm running into though is that it only works on even amounts of items. For odd numbered items it does'nt return the last item.
int x = 10;
for(int i=0; i!= x; i++)
{
Console.WriteLine(i + " " +x + " ");
x--;
}
In the code above, 5 won't be printed because at that time i is equal to x which violates the loop condition and exits the loop. Hence the value is not printed. Changing the loop condition from i != x to i<=x will fix the problem. This is shown below.
int x = 10;
for (int i = 0; i <= x; i++, x--)
{
Console.WriteLine(i + " " + x + " ");
}
Hope it helps :)
Related
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
Hello had a pretty simple problem, I'm trying to create a console program in C# that gets 3 inputs from the user. The start, stop and number of steps.
It's supposed to be a for loop but I don't really get how I can put user input in the for loop, I tried making int's of the user input and then placing the names of the int's in the for loop but it's giving me errors.
The program is supposed to look like the following program in "Ovning 1" site is in Swedish but I hope you guys will get it, tried searching the site but there was never an explanation given. http://csharpskolan.se/showarticle.php?id=119
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ovning12
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Mata in Start");
int startNummer = int.Parse(Console.ReadLine());
Console.WriteLine("Mata in Stop");
int stopNummer = int.Parse(Console.ReadLine());
Console.WriteLine("Mata in Steg");
int stegNummer = int.Parse(Console.ReadLine());
for (int startNummer; startNummer >= stopNummer; startNummer + stegNummer)
{
Console.WriteLine();
}
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Mata in Start");
int startNummer = int.Parse(Console.ReadLine());
Console.WriteLine("Mata in Stop");
int stopNummer = int.Parse(Console.ReadLine());
Console.WriteLine("Mata in Steg");
int stegNummer = int.Parse(Console.ReadLine());
for (int n = startNummer; n < stopNummer; n += stegNummer)
{
Console.Write(n + " ");
Console.Write("{0} ", n); //(Alternative)
}
}
a for loop should look like this
for (int i = startNummer; i <= stopNummer; i += stegNummer)
{
Console.Write(i + " ");
}
there are 3 mistakes in your current code:
for (int startNummer; startNummer >= stopNummer; startNummer + stegNummer)
you can't initialize a variable twice int startNummer; - that won't compile
your comparison heads into the wrong direction (except you're working with negative steps) startNummer >= stopNummer
you're not assigning the calculated new step here startNummer + stegNummer - it should be startNummer += stegNummer or startNummer = startNummer + stegNummer
Most of it looks okay. But couple of things do not make sense,
for (int startNummer; startNummer >= stopNummer; startNummer + stegNummer);
{
Console.WriteLine();
}
there's a semi colon ';' at the end of for loop. This ends for loop, making next curly braces syntax error. Also startNumber >= stopNumber and then startNumber + stegNumber would possibly either not run it at all, or run an infinite loop based on the inputs.
Is this for loop supposed to be like below?
for (int start = startNummer /*have to initialize the start value*/;
start < stopNummer;
start += stegNummer)
{
Console.Write(start + " "); //need Console.Write to print all numbers on same line. Console.WriteLine puts each index on its own line
}
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
A few weeks ago I began studying a c# beginners course, I got stuck on Arrays.
I do not want the complete answer for my problem, I want the tools or links to figure it out of myself
I´am trying to make a console Application that acts like a "Weather Station".
The program should take user input as an array on how many measurements have been made (Done). After that the user will enter the degrees in an loop (Done)
The program should write out all the measurements and the average measurement.
I can calculate the average but don't know how to print the results
I've come this far...
Console.WriteLine("How many measurements have you done");
string str = Console.ReadLine();
int size = Convert.ToInt32(str);
int[] temperatur = new int[size];
for (int i = 0; i < temperatur.Length; i++)
{
Console.WriteLine("Enter temperature " + i + ": ");
str = Console.ReadLine();
int element = Convert.ToInt32(str);
temperatur[i] = element;
}
Console.WriteLine("");
int sum = 0;
for (int i = 0; i < temperatur.Length; i++)
sum = sum + temperatur[i];
Console.WriteLine("The average temperature is " +
sum / temperatur.Length);
Seeing as you state that the only problem you are having is 'print out all the measurements', all you have to do is add an additional Console.WriteLine() to the existing for loop you already have. You will also to have to add braces. As such:
int sum = 0;
for (int i = 0; i < temperatur.Length; i++){
sum = sum + temperatur[i];
Console.WriteLine("Measurement {0} is {1}", i+1, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
You might not recognise that Console.WriteLine(), but it's basically a neat way of formatting your output using placeholders. The {0} will be replaced with the first value provided, the {1} with the second.
EDIT: MSDN documentation on Console.WriteLine() and also String.Format
for (int i = 0; i < temperatur.Length; i++)
sum = sum + temperatur[i];
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Change this to :
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
Console.WriteLine("Temperature {0} is {1}", i, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
If you want to do it in the same for:
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
Console.WriteLine("Temperature {0}", temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
In another statement:
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
}
temperatur.ForEach(x => Console.WriteLine("Temperature {0}", x));
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
...
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Console.ReadLine();
In the end type Console.ReadLine();
This seems like a really simple thing to do but I cant't seem to get my ahead around it. I have 10 documents entitled 1.txt to 10.txt. I just want to count the number of lines in each doc and end up with the final summation of the line counts.
This is where I got to.
for (int i = 1; i < 11; i++)
{
int lineCount = File.ReadLines(#i + ".txt").Count();
lineCount += lineCount;
Console.WriteLine("Total IDs: " + lineCount);
}
UPDATE
My docs have carriage returns at the bottom of them which I do not want to include in the count.
You are reinitializing lineCount every time. Change it like so:
int lineCount = 0;
for (int i = 1; i < 11; i++)
{
lineCount += File.ReadLines(#i + ".txt").Count();
}
Console.WriteLine("Total IDs: " + lineCount);
This way you don't reinitialize lineCount every time, and you are simply adding the Count to it for each iteration.
You have declared lineCount inside of the loop, so it is destroyed and created again after each iteration, i.e., you are only seeing the last result. Declare lineCount outside the scope of the loop instead.
lineCount += lineCount; is the same as lineCount *= 2;; is that what you intended?