How do you write a program to take N numbers as input and output all even numbers from 1 to N inclusive, each on a new line. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do you write a program to take N numbers as input and output all even numbers from 1 to N inclusive, each on a new line.

May anyone help? I am confused with how you stop the loop at the input and how you valdate the num is even.

3rd Jan 2021, 7:22 PM
Jay Scott
Jay Scott - avatar
8 Answers
+ 5
while True : try: n = int(input()) if not n%2: print(n) except: break
3rd Jan 2021, 7:39 PM
Oma Falk
Oma Falk - avatar
+ 3
Hi Jay Scott Which language? Could you post your attempt also so we may see where you are struggling
3rd Jan 2021, 7:30 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Here is a python example: user_num = int(input()) for i in range(user_num +1): if i%2==0: print(i)
3rd Jan 2021, 7:34 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
the question leaves room for questions. From your statement "1 to N inclusive" I'd assume that N is just one number and reflects the maximum (even) number to print. Considering this (and python as language) that should work: for i in range(1,int(input("Max:"))+1): if not i%2: print(i) As second solution, as Frogged already demonstrated: you can get multiple input values, maybe collect them in a list, and as soon as the input is just a carrige return (or anything that is not number, like the string "end") you can print out the list: mylist = [] while True: try: mylist.append(int(input())) except: break for i in mylist: if not i%2: print(i)
3rd Jan 2021, 7:56 PM
Martin Ed
Martin Ed - avatar
+ 2
I've been strugling with this one quite a bit and the posts i found didn't really clear it up for me. (probably because im still not skilled at C# at all and don't recognize what the others were suggesting). Eventually this worked for me, i'd thought I post it, mabey it will help someone else :) { int num = Convert.ToInt32(Console.ReadLine()); int res = 0; //your code goes here while (res < num) { res ++; if (res % 2 == 0) { Console.WriteLine(res); } } }
14th Sep 2021, 12:29 PM
PBOL
+ 1
Abhik Mukherjee The following is straight out of the c# tutorial, Conditions and Loops. I suggest you revisit for (int i =0; i <=10; i+=2){ Console.WriteLine(i); }
2nd Jun 2021, 6:13 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
@Rik Wittkopp Thanks a lot mate. It was indeed simple and mere foolish on my part. Much appreciated.
3rd Jun 2021, 12:40 PM
Abhik Mukherjee
Abhik Mukherjee - avatar
0
Hello everyone, I am also facing the same issue but I guess the question being asked is for the C# code, so it'll be very helpful if anyone can explain it.
2nd Jun 2021, 12:12 PM
Abhik Mukherjee
Abhik Mukherjee - avatar