Sum integers using a loop c# -
i new programming , think have confused myself i'm trying make loop asks users integers when user inputs integer greater 100 console displays amount of integers user has input , sum of these integers. know it's basic can't figure went wrong.
namespace wip { class program { static void main(string[] args) { string strnum1, strnum2; int num1, num2; int = 0; int sum =0 ; console.writeline("please enter integer between 1 , 100"); // asks user input strnum1 = console.readline(); num1 = int.parse(strnum1); //repeat asking user input { console.writeline("please enter integer between 1 , 100"); // asks user input strnum2 = console.readline(); num2 = int.parse(strnum2); //input stored num2 sum = num2; //store num2 in sum i++; if (num2 >= 100) // if num2 int greater 100 { sum = (num1 +num2 +sum); // calculation console.writeline("no of integers entered {0} {1}", i, sum); //output calculation } } while (i < 100); } } }
any appreciated everyone!
you're on right track... couple of things:
do... while
used when want run through block @ least once, first 'get' user can inside block. can code whatever want happen after condition fails right after block, instead of checking same condition inside it.
make sure if you're using parse
wrap in try...catch
, because user type in (not numbers). use tryparse
instead.
finally, make sure you're comparing correct variable. checking i < 100
keep looping until 100 numbers have been entered; want compare user's input instead.
namespace wip { class program { static void main(string[] args) { string prompt = "please enter {0} integer between 1 , 100"; string strnum; int num = 0; int = 0; int sum =0 ; //ask once , repeat while 'while' condition true { string pluralprompt = > 0 ? "another" : "an"; prompt = string.format(prompt,pluralprompt); console.writeline(prompt); // asks user input strnum = console.readline(); if (!int32.tryparse(strnum, out num)) //input stored num { // warn user, throw exception, etc. } sum += num; //add num sum i++; } while (num < 100); console.writeline("no of integers entered {0} {1}", i, sum); //output calculation } } }
Comments
Post a Comment