Hello, guys, welcom to Lingarajtechhub. Today we are going to discuss reading 10 numbers from the keyboard and find their sum and average.
Code:
package com.control_loop.java; public class sum_avg_natural_number { public static void main(String[] args) { int sum=0; System.out.println(" 10 natural numbers are : "); for(int i=50;i<=60;i++) { System.out.println(i); sum +=i; } double avg=sum/10; System.out.println("The Sum and average of Natural Number is : " +sum +avg ); } }
Line:1
package com.Operators.Java;
- It is a java package which is a collection of classes and this package is created in a java project(Homework_operator).
- Here com.operators.java is the name of our package.
Line:2
import java.util.Scanner;
- Scanner is a class in java
- . util package used for obtaining the input of the primitive types like int, double, etc. and strings .
Line:3
public class Sum_avg_natural_number
- Here “Sum_avg_natural_number” is defined as a class which is a template used to create objects ,& to define object ,data type and method.
- It is defined as public because it can be accessed anywhere.
- It is the entry point to the application.
Line:4
public static void main(String[] args);
- This is the main () method of our java program .
- Every java program must contain the main() method .
- Public : It is the access modifier of the main function which must be public so that the JRE can access and execute this method.
- If a method is not public then access is restricted and its showing error.
- Static : Static is a keyword in which the main method has to be static in which JVM can load the class into memory and call the main method without creating an instance .
- Void : It means no return types.
- Main() : It is a function.
- String [] args :String means collection of characters
- String[] args represents a collection of Strings ,that are separated by a space and can be typed into the program on the terminal directly.
Line:5
int i,sum;
- Here we Declare 2 variables i,sum which is integer type and int is a local variable.
Line:6
Scanner Sc = new Scanner(System.in);
- Here scanner is a class and Sc is the instance of the object which is the new Scanner. System.in is an argument.
Line:7
n=sc.nextInt();
- “n” is a variable that we take and sc is our instance name which is created for an object and nextInt() is a method of a Scanner object that reads in a string of digits or char and converts them into an int type.
Line:8
for(i=50; i<=60 ; i++ ) {
System.out.println(i); }
sum + = i ; }
- for(initialization; condition; increment/decrement)
It is used when we want to perform initialization,condition & increment/decrement in one single line.
- sum +=1 is add every input number
Line:9
System.out.println( );
- It means System is a class name and out is an instance of the System println is to print a new line and “+” means coordinate.