0
Why i cant output the varibles inside the while loop
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { while (true) { int e = Convert.ToInt32(Console.ReadLine()); int sum = 0; if (e % 2 == 0) { sum+=e; } } Console.Write(sum); } } }
6 Answers
+ 3
Two problems here ,
1. You have an infinite loop here : while(true) means loop forever and will eventually cause a Stack Overflow.
2. The variable you are trying to Console.write() is not in the current scope . In simple terms , you have to declare the variable in the same layer or scope as the Console.write()
https://code.sololearn.com/c01jz8JgbPf7/#cs
+ 5
Xenon
You have declared sum inside loop but accessed outside loop so you will get error because the scope of sum is inside the loop.
+ 3
Use description to add the code you are talking about.
+ 2
To anticipate infinite loop, use Int32.TryParse to convert input line into an integer.
Combined with an `if` conditional and `break` statement to exit the loop when no more input was available, the code tries to convert input to integer, and (on success) add the integer to <sum> following the even number verification.
using System;
namespace ReadingInput
{
class Practice
{
static void Main( string[] args )
{
int sum = 0, e = 0;
while ( true )
{
if( !Int32.TryParse( Console.ReadLine(), out e ) )
{
break; // conversion failed!
}
if (e % 2 == 0)
{
sum += e;
}
}
Console.Write( sum );
}
}
}
0
Oh yea right i forgot