Why i cant output the varibles inside the while loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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); } } }

4th Jul 2021, 7:29 AM
Xenon
Xenon - avatar
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
4th Jul 2021, 7:55 AM
Ćheyat
Ćheyat - avatar
+ 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.
4th Jul 2021, 8:01 AM
A͢J
A͢J - avatar
+ 3
Use description to add the code you are talking about.
4th Jul 2021, 7:30 AM
Abhay
Abhay - avatar
+ 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 ); } } }
4th Jul 2021, 8:29 AM
Ipang
0
Oh yea right i forgot
4th Jul 2021, 7:36 AM
Xenon
Xenon - avatar