c program for addition, subtraction, multiplication and division using switch

 C program for addition, subtraction, multiplication and division using switch


  1. #include <stdio.h>

  2. int main() {
  3.     int num1, num2, choice;
  4.     float result;
  5.     printf("Enter two numbers: ");
  6.     scanf("%d %d", &num1, &num2);
  7.     printf("Enter your choice: \n1 for addition\n2 for subtraction\n3 for multiplication\n4 for division\n");
  8.     scanf("%d", &choice);

  9.     switch(choice) {
  10.         case 1:
  11.             result = num1 + num2;
  12.             printf("Addition: %.2f\n", result);
  13.             break;
  14.         case 2:
  15.             result = num1 - num2;
  16.             printf("Subtraction: %.2f\n", result);
  17.             break;
  18.         case 3:
  19.             result = num1 * num2;
  20.             printf("Multiplication: %.2f\n", result);
  21.             break;
  22.         case 4:
  23.             result = (float)num1 / num2;
  24.             printf("Division: %.2f\n", result);
  25.             break;
  26.         default:
  27.             printf("Invalid choice!\n");
  28.     }
  29.     return 0;
  30. }


  • the user is prompted to enter two numbers and then a choice for the operation to be performed. The choice is taken as an integer input and is used in the switch statement. 
  • Depending on the user's choice, the program performs the corresponding operation using the two numbers as input.
  • It's worth noting that, in the division operation, if the second number is zero, it will cause a runtime error because division by zero is not defined. 
  • I have used type casting to convert the int variables to float so as to get the decimal value. Also, I have used the format specifier %.2f to print the result with 2 decimal places.
  • the user is prompted to enter two numbers and then a choice for the operation to be performed. The choice is taken as an integer input using the scanf function and is used in the switch statement. Depending on the user's choice, the program performs the corresponding operation using the two numbers as input.

  • The switch statement checks for the value of the variable choice. Depending on the value, the program enters the corresponding case and performs the operation. The break statement is used at the end of each case to exit the switch statement and prevent the program from executing the next case.
  • In the case of the division operation, I have used type casting to convert the int variables to float so as to get the decimal value. Also, I have used the format specifier %.2f to print the result with 2 decimal places.

  • In the default case, if the user enters any value other than 1, 2, 3, or 4, the program displays an "Invalid choice!" message. This is to handle the scenario when the user enters an unexpected value.

c program addition subtraction, multiplication and division using function

 c program for addition subtraction, multiplication and division using function

  1. #include <stdio.h>

  2. int add(int a, int b) {
  3.     return a + b;
  4. }

  5. int subtract(int a, int b) {
  6.     return a - b;
  7. }

  8. int multiply(int a, int b) {
  9.     return a * b;
  10. }

  11. float divide(int a, int b) {
  12.     return (float)a / b;
  13. }

  14. int main() {
  15.     int a = 10, b = 5;
  16.     int add_result = add(a, b);
  17.     int subtract_result = subtract(a, b);
  18.     int multiply_result = multiply(a, b);
  19.     float divide_result = divide(a, b);

  20.     printf("Addition: %d + %d = %d\n", a, b, add_result);
  21.     printf("Subtraction: %d - %d = %d\n", a, b, subtract_result);
  22.     printf("Multiplication: %d * %d = %d\n", a, b, multiply_result);
  23.     printf("Division: %d / %d = %f\n", a, b, divide_result);

  24.     return 0;
  25. }


  • In this program, four functions are defined for addition, subtraction, multiplication, and division respectively. Each function takes two integer arguments a and b, performs the corresponding operation, and returns the result. 
  • In the main function, variables a and b are initialized with the values 10 and 5 respectively.
  • The functions are called and the results are stored in variables add_result, subtract_result, multiply_result, and divide_result. 
  • These functions take two integer arguments and return the result of the operation. In the main() function, two integers are taken as input, and then the functions are called with these inputs to perform the operations and display the results.
  • In the division operation, if the second number is zero, it will cause a runtime error because division by zero is not defined. 
  • It's also important to consider the case where the division operation results in decimal values, In that case, you should use float or double instead of int.

semicolon in java

 a semicolon (;) is used to separate statements in a program. Each statement in a Java program must end with a semicolon, just like in many other programming languages.

Here's an example of  semicolon in a Java program:

int x = 5; // Declare a variable and assign a value

System.out.println(x); // Print the value of the variable

x++; // Increment the value of the variable

System.out.println(x); // Print the new value of the variable

In this example, there are three statements: one for declaring a variable and assigning a value, one for printing the value of the variable, and one for incrementing the value of the variable. Each statement ends with a semicolon, which separates them from each other.

It's worth noting that, in Java, a semicolon is not always necessary. For example, if you are defining a class or method, you don't need to use a semicolon at the end of the definition. Also, you don't need to use a semicolon after a block statement (statements enclosed in curly braces {}) that is part of a control statement such as if-else, while, for, etc. The end of the block statement is represented by the closing curly brace.

In the case of a single-line if statement or a single-line loop, you can also omit the curly braces {} and write the statement directly after the if or while keyword, respectively.

if(x==5) System.out.println("x is 5");

while(x<10) x++;

In summary, a semicolon is used in Java to separate statements and mark the end of a statement. However, it's not always required and depends on the context of the statement or block.

It's worth noting that in Java, a semicolon is also used in certain control statements such as the "for" loop and the "enhanced for" (or "for-each") loop.

In a "for" loop, the initialization, condition, and increment/decrement statements are separated by semicolons. 


In this example, the initialization statement "int i = 0" is executed once before the loop starts, the condition "i < 10" is checked before each iteration, and the increment statement "i++" is executed after each iteration. Each of these statements is separated by a semicolon.

In the case of the "enhanced for" loop, the semicolon is used to separate the loop variable and the array or collection that is being iterated over.

write a ‘java’ program to display characters from ‘a’ to ‘z’

 Here is a simple program that prints characters from a to Z

  1. public class DisplayAlphabets {
  2.     public static void main(String[] args) {
  3.         for (char c = 'a'; c <= 'z'; c++) {
  4.             System.out.print(c + " ");
  5.         }
  6.     }
  7. }

This program uses a for loop to iterate through the characters from 'a' to 'z'. The loop variable "c" is initialized to 'a' and incremented by 1 on each iteration until it reaches 'z'. Inside the loop, the current character is printed using the System.out.print() method. The " " at the end of the print statement will print the character followed by a space.

Alternatively, we can use the Character.toChars(int) method to convert the int value to a char and use the for loop to iterate from 97 to 122.

java program to print characters from a to z


This will also display the same output as the first example: "a b c d e f g h i j k l m n o p q r s t u v w x y z".
Note that, in both examples, the alphabets will be printed in lowercase. If we want to print uppercase alphabets, you can use 'A' to 'Z' in the for loop or use 65 to 90 in the Character.toChars(int) method.

We can also use the java.util.stream.IntStream to display characters from 'a' to 'z'.
 Here is an example of how you can use IntStream to display characters from 'a' to 'z':

public class DisplayAlphabets {
    public static void main(String[] args) {
        IntStream.rangeClosed('a', 'z').mapToObj(c -> (char) c).forEach(System.out::print);
    }
}

This program uses the IntStream.rangeClosed() method to create a stream of ints from the ASCII value of 'a' to the ASCII value of 'z'. Then it uses the mapToObj() method to convert the ints to chars, and finally the forEach() method to print each character.

we can also use the java.util.stream.IntStream to display characters from 'A' to 'Z' using the same approach. Here is an example of how you can use IntStream to display characters from 'A' to 'Z':


public class DisplayAlphabets {
    public static void main(String[] args) {
        IntStream.rangeClosed('A', 'Z').mapToObj(c -> (char) c).forEach(System.out::print);
    }
}

This will print the uppercase alphabets : "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".

It's worth noting that, in all examples the alphabets will be displayed in a single line, if you want to display them in separate lines, you can modify the System.out.print() method to System.out.println().

How to print array in java

 To print an array in Java, you can use a for loop to iterate through the array and print each element. Here is an example of how to print an array of integers:

Here is a simple program that explains how to print an array of integers in java

  1. int[] myArray = {1, 2, 3, 4, 5};
  2. for (int i = 0; i < myArray.length; i++) {
  3.     System.out.print(myArray[i] + " ");
  4. }

This will print the following output: "1 2 3 4 5".

Alternatively:  Arrays.toString(myArray) and directly print the array.

System.out.println(Arrays.toString(myArray));

This will also print the array in same format "1 2 3 4 5"

We can also use the enhanced for loop (also known as the "for-each" loop) to print an array in Java. This type of loop automatically iterates through each element in the array, making it more concise and easier to read than a traditional for loop:

  1. for (int element : myArray) {
  2.     System.out.print(element + " ");
  3. }

This will also print the same output as the previous example "1 2 3 4 5".

When printing arrays of other types, such as Strings or objects, we can use the same approach. For example, if you have an array of Strings, you can use the enhanced for loop to print each element:

java print array

This will print the following output: "Hello World".

It's worth noting that, the Arrays.toString() method will work for all types of arrays, including arrays of objects, it will call the toString() method of each element in the array.

In case of the custom class objects, you may need to override the toString() method of the class.

Another way to print an array in Java is to use the Arrays.deepToString() method if the array is a multi-dimensional array. This method is similar to Arrays.toString(), but it can handle multi-dimensional arrays and it will recursively call itself for each sub-array. Here's an example of how to use Arrays.deepToString() to print a 2D array:

  1. int[][] my2DArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  2. System.out.println(Arrays.deepToString(my2DArray))

This will print the following output: "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]".

we can also use the java.util.Arrays.stream() method to print an array in Java 8 and later versions. This method returns a stream of the array's elements, which can then be passed to various stream operations such as forEach(). Here's an example of how to use Arrays.stream() to print an array:

int[] myArray = {1, 2, 3, 4, 5};

Arrays.stream(myArray).forEach(System.out::print);

This will also print the same output as the previous examples "1 2 3 4 5".

It's worth noting that when you use the Arrays.stream() method to print an array, it does not add any spaces or newlines between the elements, unlike the for loop and enhanced for loop. If we want to add spaces or newlines, you can use the map() method to transform each element into a string, and then use the forEach() method to print each string.

Instance variable in java

Instance Variables in Java: The Complete Guide

Instance variables are an important topic in Java programming. They are responsible for defining the characteristics of an object and preserving its state for its whole life cycle. In this blog, we will discuss instance variables in great detail, their different characteristics, usage, and best practices.

What Are Instance Variables?

An instance variable is a variable defined in a class (as opposed to a static variable). Since each object of a class has its own copy of instance variables, changes made to such variables in one object do not have any impact on another object of the same class.

Instance Variables:

  • Defined within a class but out of any method, block, or constructor.
  • Every instance has its own copy of instance variables.
  • Gets a default value until you assign it.
  • Can take any access modifier (private, protected, public, or default).
  • They are not shared between entities, unlike static variables.

Syntax of Instance Variables

class Car { String brand; int speed; // Instance variables }

Here, brand and speed are instance variables. Each instance of the Car class will have its own brand and speed values.

Default values of instance variables:

If an instance variable is not initialized, Java assigns default values as shown below:

Data Type Default Value
int 0
double 0.0
boolean false
char '\u0000' (null character)
String (or Other objects) null

Example:

  1. class Example {
  2.     int number; // default value is 0
  3.     String text; // default value is null
  4.     
  5.     void display() {
  6.         System.out.println("Number: " + number);
  7.         System.out.println("Text: " + text);
  8.     }
  9.     
  10.     public static void main(String[] args) {
  11.         Example obj = new Example();
  12.         obj.display();
  13.     }
  14. }

    Instance Variables and Access Modifiers

    Instance variables can have different access modifiers, which control their visibility and accessibility.

    Private Instance Variables

    • Accessibility: same class only.
    • Use getters and setters to provide access.
    1. class Person {
    2.     private String name;
    3.     
    4.     public String getName() {
    5.         return name;
    6.     }
    7.     
    8.     public void setName(String name) {
    9.         this.name = name;
    10.     }
    11. }

      Public Instance Variables

      • Accessible from anywhere in the program.
      • Not recommended, as it violates encapsulation.
      class Animal { public String species; }

      Protected Instance Variables

      • Available within the same package and to subclasses.
      class Vehicle { protected int speed; }

      Default (Package-Private) Instance Variables

      • Only accessible within the same package.
      class Employee { String designation; // Default access modifier }

      Using Instance Variables

      Instance variables are used to store object-specific data.

      Example java program :

      1. class Student {
      2.     String name;
      3.     int age;
      4.     
      5.     // Constructor to initialize instance variables
      6.     public Student(String name, int age) {
      7.         this.name = name;
      8.         this.age = age;
      9.     }
      10.     
      11.     void display() {
      12.         System.out.println("Name: " + name + ", Age: " + age);
      13.     }
      14.     
      15.     public static void main(String[] args) {
      16.         Student s1 = new Student("Alice", 20);
      17.         Student s2 = new Student("Bob", 22);
      18.         
      19.         s1.display();
      20.         s2.display();
      21.     }
      22. }

          Output:

          Name: Alice, Age: 20 Name: Bob, Age: 22

          Each Student object holds its own copy of name and age.


          Instance Variable vs Static Variable

          Feature Instance Variables Static Variables
          Ownership Object specific Class specific
          Memory Allocation At object creation At class loading
          Access Requires an object Accessed via class name

          Example

          1. class Company {
          2. static String companyName = "Tech Corp"; // Static variable
          3. String employeeName; // Instance variable
          4. }

            Best Practices for Instance Variables

            1. Encapsulation: Use the private access modifier and access it through getters and setters.
            2. Meaningful Names: Assign well-defined names to variables.
            3. Initialize in Constructor: Ensure instance variables are initialized in constructors.
            4. Limit Visibility: Use private or protected unless absolutely necessary.
            5. Lower Memory Usage: Use only the necessary instance variables in memory-sensitive applications.

            Instance variables are critical components of Java's object-oriented programming paradigm. They enable objects to store their own independent state and data. Understanding how they work and following best practices allows you to write clean, efficient, and maintainable Java code.

            Want to learn more about Java concepts? Let us know in the comments!

            Select Menu