Example
Input
5
Output
9
Required to know
Use of Variables, Use of different operators like assignment or arithmetic operators, Use of methods like System. out. print(), and use for loop, and Use of Data types
Steps
The program asks the user for a number, which gets stored in a variable called
n
.The program also sets up a variable called
sum
to keep track of the sum of odd numbers.It then uses a
for
loop to go through the numbers from 1 ton
.During each iteration, the program checks whether the current number is odd (i.e. not divisible by 2).
If the number is odd, it adds it to the
sum
variable.After the loop ends, the program prints the final value of
sum
, which represents the sum of odd numbers from 1 ton
.
Program
import java.util.Scanner;
public class Mavenproject1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i;
int sum = 0;
for(i = 1; i<=n; i++){
if(i%2!=0){
sum = sum + i;
}
}
System.out.print(sum + " ");
}
}