Switch case in c example program

  • switch case in c programming questions
  • switch case with do you want to continue in c
  • A switch case is a control statement in C that allows you to choose between several different options based on the value of a particular expression. 
  • C has a built-in multi-way decision statement known as a switch. It is a keyword we can select a single option from multiple options. The switch  is having expression; each and every option is known as case and must be followed by colon.
  • Each and every case ends with break statement.
  • The last case is default even that will have break.
  •  The break is a keyword. Each and every case ends with break statement

 SYNTAX:-

 switch(expression)
 {
    case value-1 :block-1 break;
    case value-2 :block-2 break;
    case value-3 :block-3 break;
    .........
    .........
    .........
    .........
    default :default-block break;
 }

Here is an example of how to use a switch case in a C program:

#1; switch case in c programming questions

  1. # include <stdio.h>
  2. void main() {
  3.     char operator;
  4.     double a,b;
  5.     printf("Enter an operator (+, -, *,): ");
  6.     scanf("%c", &operator);
  7.     printf("Enter two numbers ");
  8.     scanf("%lf %lf",&a, &b);
  9.     switch(operator)
  10.     {
  11.         case '+':
  12.             printf("%.1lf + %.1lf = %.1lf",a, b, a + b);
  13.             break;
  14.         case '-':
  15.             printf("%.1lf - %.1lf = %.1lf",a, b, a - b);
  16.             break;
  17.         case '*':
  18.             printf("%.1lf * %.1lf = %.1lf",a, b, a * b);
  19.             break;
  20.         case '/':
  21.             printf("%.1lf / %.1lf = %.1lf",a, b, a / b);
  22.             break;
  23.         default:
  24.             printf("Error! operator is not correct");
  25.     }
  26. }

Output:
  1. Enter an operator (+, -, *,): +
  2. Enter two numbers 12
  3. 12
  4. 12.0 + 12.0 = 24.0
  5. Process returned 18 (0x12)   execution time : 7.392 s
  6. Press any key to continue.



  • In the below  example, the program prompts the user to enter a number and then uses a switch case to determine what to do based on the value of the number. If the user enters 1, the program will print "You entered 1.
  • " If the user enters 2, the program will print "You entered 2," and so on. If the user enters a value that is not covered by any of the cases, the default case will be executed.



Python program to find factorial without recursion

The factorial of a positive integer n is the product of all positive integers less than or equal to n. The factorial of a number is represented by the symbol "!" . For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.

Here is a Python function that calculates the factorial of a given number using a for loop:

def factorial(n):
    if n < 0:
        return None
    if n == 0:
        return 1
    result = 1
    for i in range(1, n+1):
        result *= i
    return result

This function takes a single argument, n, and returns the factorial of n. It first checks if n is less than 0, if so it returns None. If n is equal to 0, it returns 1 (since the factorial of 0 is defined to be 1). It then initializes a variable named result to 1, then uses a for loop to iterate over the range of integers from 1 to n inclusive and multiply each number to result variable. Finally, the function returns the value of result, which is the factorial of n.

You can call this function and pass in any positive integer to calculate its factorial:

>>> factorial(5)
120
>>> factorial(3)
6
>>> factorial(10)
3628800

Alternatively python has math.factorial function which you can use without writing your own function.

import math
math.factorial(5)

Do note that factorial of number can be very large, even for relatively small numbers and python integers may not be large enough to store those values.

#1: Python program to find factorial of a given number without using recursion

  1. #Factorial without recursion

  2. n=int(input("Enter the number: "))
  3. fact=1
  4. if n<0:
  5.     print("factorial doesn't exist for negative numbers")
  6. else:
  7.     for i in range(1,n+1):
  8.         fact=fact*i
  9.     print("factorial of", n, "is", fact)

Output:

  1. Enter the number: 5
  2. factorial of 5 is 120





You Might like :
  1. Python try except else with example program
  2. Python finally block example with program
  3. Python try-except- else vs finally with example program
  4. Find factorial of a number without using recursion using python
  5. Python program to find factorial without recursion
  6. If statement in python example program
  7. Else statement in python with example program
  8. Types of operators in python
  9. python math operators
  10. python division operator
  11. Python modulo operator
  12. Python bitwise operators
  13. python comparison operators
  14. Logical operators in python
  15. Assignment operator in python
  16. Identity operator in python
  17. Python power operator
  18. Not equal operator in python
  19. python not operator
  20. python and operator
  21. python Ternary operator
  22. python string operations
  23. python string methods
  24. Spilt function in python
  25. Format function in python
  26. String reverse in python
  27. python tolower
  28. Remove spaces from string python
  29. Replace function in python
  30. Strip function in python
  31. Length of string python
  32. Concat python
  33. startswith python
  34. strftime python
  35. is numeric python
  36. is alpha python
  37. is digit python
  38. python substring


Find factorial of a number by using recursion using python

  • Python program to find factorial of a number using recursion in python.
  • Algorithm to find factorial of a number using recursion function using python.

#1: Python program to find factorial of a given number using recursion

  1. #Factorial using recursion
  2. def fact(n):
  3.     if n==1:
  4.         return 1
  5.     else:
  6.         return n*fact(n-1)

  7. n=int(input("Enter the number: "))
  8. result=fact(n)
  9. print("Factorial of",n,"is", result)

Output:

  1. Enter the number: 6
  2. Factorial of 6 is 720



You Might like :
  1. Python try except else with example program
  2. Python finally block example with program
  3. Python try-except- else vs finally with example program
  4. Find factorial of a number without using recursion using python
  5. Python program to find factorial without recursion
  6. If statement in python example program
  7. Else statement in python with example program
  8. Types of operators in python
  9. python math operators
  10. python division operator
  11. Python modulo operator
  12. Python bitwise operators
  13. python comparison operators
  14. Logical operators in python
  15. Assignment operator in python
  16. Identity operator in python
  17. Python power operator
  18. Not equal operator in python
  19. python not operator
  20. python and operator
  21. python Ternary operator
  22. python string operations
  23. python string methods
  24. Spilt function in python
  25. Format function in python
  26. String reverse in python
  27. python tolower
  28. Remove spaces from string python
  29. Replace function in python
  30. Strip function in python
  31. Length of string python
  32. Concat python
  33. startswith python
  34. strftime python
  35. is numeric python
  36. is alpha python
  37. is digit python
  38. python substring

Java program to check valid Balanced parentheses

Balanced parentheses:
  •   A string which contains below characters in correct order.
  •  "{}" "[]" "()"
  • We need to check whether given string has valid order of parenthesis order.
  • If the parenthesis characters are placed in order then we can say its valid parentheses or balanced parentheses.
  • If the parentheses characters are not in correct order or open and close then we can say it is not balanced or invalid parenthesis.
  • Program to check given string has a valid parenthesis or not.

#1: Java example program to check given string has valid parenthesis or not.


  1. package instanceofjava;

  2. import java.util.Stack;

  3. public class BalancedParenthensies {

  4. public static void main(String[] args) {
  5. System.out.println(checkParenthensies("{(xxx,yyy)}"));
  6. System.out.println(checkParenthensies("{)(acd,bcvfs}"));
  7. System.out.println(checkParenthensies("{(xxx},yyy)"));
  8. System.out.println(checkParenthensies("[(xxx),yyy]"));
  9. }
  10. public static boolean checkParenthensies(String str) {
  11.         Stack<Character> object  = new Stack<Character>();
  12.         for(int i = 0; i < str.length(); i++) {
  13.             char ch = str.charAt(i);
  14.             if(ch == '[' || ch == '(' || ch == '{' ) {     
  15.             object.push(ch);
  16.             } else if(ch == ']') {
  17.                 if(object.isEmpty() || object.pop() != '[') {
  18.                     return false;
  19.                 }
  20.             } else if(ch == ')') {
  21.                 if(object.isEmpty() || object.pop() != '(') {
  22.                     return false;
  23.                 }           
  24.             } else if(ch == '}') {
  25.                 if(object.isEmpty() || object.pop() != '{') {
  26.                     return false;
  27.                 }
  28.             }
  29.         }
  30.         return object.isEmpty();
  31.     }
  32. }

Output:
  1. true
  2. false
  3. false
  4. true

check valid java balanced parenthesis


Python try-except- else vs finally with example program

  • For detail explanation of try and except block please check below link
  • Python try and except blocks with an example program
  • We will place all statements which are proved to generate exceptions in try block.
  • If any exception occurred then exception block will handle the exceptions.
  • If no exception raised in try block then except block wont be executed and else block will be executed.
  • In this scenario we might move the code from else to try block. If any exception raised in try block other statements in try block wont be executed and also else block will not be executed.
  • Finally block will always executes irrespective of any kind of exceptions.
  • So if we place any statements inside finally block of python script then those those statements will be executed for sure.
  • Else block will be executed when no exception occurred in try and finally will executes irrespective of any exception.
  • Lets see an example python program on try-except-else and try except-else-finally.




#1: Write a Python program which explains usage both else and finally blocks in python programming.

  1. #try_except with both else and finally blocks:
  2. string=input("enter some string: ")

  3. try:
  4.     x=string[5]
  5.     print("char at index 5 is: ",x)
  6.     print("no exception")
  7. except IndexError as e:
  8.     print("exception raised: ",e)
  9. else:
  10.     print("else block is executing becoz of no exception")
  11. finally:
  12.     print("finally block will always executes")


Output

  1. enter some string: python
  2. char at index 5 is:  n
  3. no exception
  4. else block is executing becoz of no exception
  5. finally block will always executes


python else vs python finally

Python finally block example with program

  • Before discussing about finally block, please check our previous articles on try, except and else blocks. 
  • Basic python programs on try , except and else
  • As we already know about try like its duty is to find any exceptions if occurs and pass it to python except block so that except block will assign exception class object to handle exceptions.
  • Else will be executed if no exception occurs.
  • Finally block will executes even exceptions occurs. so in some situations we need to execute some statements compulsory even if any exceptions occurs in that scenario we will use python finally block
  • We will place all statements which would be executes irrespective of exceptions.
  • Lets see an example program on python finally block.
  • Python try except finally example
     



#1: Write a python program which explains usage of finally block in exception handling of python programming.

  1. try:
  2.   x = int(input("enter first number: "))
  3.   y = int(input("enter second number: "))
  4.   result=x/y
  5. except ArithmeticError as e:
  6.    print("cannot devide a number by zero: ", e)
  7. finally:
  8.    print("finally block")

Output
  1. enter first number: 10
  2. enter second number: 0
  3. cannot devide a number by zero:  division by zero
  4. finally block

finally block python
Select Menu