Thursday, December 22

Syntax " for " and " if " statements - Java tutorials with a simple program

Today we are going to discuss for statement in Java syntax. With our code we are going to write it asks the user to enter multiply values ( inputs ) as much as the user wants, then program compares among these values and shows bigger, smaller and numbers of numbers that which are bigger than number 50 " for instant". Note: Our program uses console  " Standard inputs and outputs".

import java.util.*;

public class J_you3

    public static void main(String[]args)
        int number, num;  // Numbers entered by user
        int maxV = 0, small = 1000, bigger=0; // variable named small, bigger -----

        Scanner scan = new Scanner(;
        System.out.println("Type number of values  "); // Number of values
        number = scan.nextInt();
        for( int  i = 0; i < number; i++) // for statement to go into the loop

            System.out.println("Type value " + i ) ;
            num = scan.nextInt();
            if (num > maxV)maxV = num;  // if statement into for loop
            if (num < small)small = num;  // Compare between number and constants or variable
            if(num > 50 )bigger = bigger +1;  // bigger with increment operator "++"
        System.out.println("The miximum value = " + maxV);
        System.out.println("The minimum value = " + small);     // Outputs to show results
        System.out.println("Values bigger than 50 = " + bigger);

We used for statement to control repetition of values that will be executed based on the user's need and we control the loop by comparing among constants or variables. As you can see in for statement   for ( int  i = 0; i < number; i++), it is in general for ( initialization; boolean expression; update ), there is not difference if we put the name of the variable like " i " outside then initialization will be after or all them inside. ( if statement ) into the loop of for statement can be easily done to compare values that you have initialized. You may also want to use nested-if statement rather than if, it is up to you.

Final note:
Think more how to any other loop such as while statement and interrupt it by if or nested-if statement to compare values. Actually everything depends on the programer thoughts, so do not stop at this point and go ahead.