C LanguageProgramming

Switch Case Statements in C Programming

switch case statements in c
Spread the love

In this article, I am going to explain the implementation of Switch Case statements in C with example. Before you go to the program firstly you have to know some basics of C language which will help you to understand the program. Before you move further first you need to know the meaning and syntax of the Switch case.

switch case in c
switch case syntax

Also watch the two basic videos (which have data types, operators, printf, scanf, header files, etc) on C language by clicking here and here.

Also read: C Program for Right-Angle Triangle (Pythagoras Theorem)

Program on Switch case statements in C

#include<stdio.h>
main()
{
	int a = 3;
	switch(a)
	{
		case 4: printf("value is four");
		break;
		case 3: printf("Value is three");
		break;
		case 1: printf("Value is nine");
		break;
		default: printf("enter valid number");	
	}
}

Also read: C Program to find Area Of a Circle

Explanation

  • We are starting with the header files and the main function. Inside the curly brackets of the main function, we have to write our whole program code.
#include<stdio.h>
main()
{ 
  • In the fourth line, I have taken an integer variable ‘a’ and assigned it by three.
int a = 3;
  • In the fifth and sixth lines, I have used a switch keyword to declare the switch case. Inside the brackets, I have passed the integer variable and opened the curly bracket of
switch(a)
{
  • From the seventh line, I had made a case that has different values. To make a case you have to use case keyword after that the value or condition the colon and then we write our code for that particular case.
  • When our case code is completed the use break keyword followed by a semicolon to end that case.
  • Then close the bracket of the switch case and main function.
                case 4: printf("value is four");
		break;
		case 3: printf("Value is three");
		break;
		case 1: printf("Value is nine");
		break;
		default: printf("enter valid number");	
	}
}
Output: Value is three
  • The integer variable ‘a’ has 3 when we run the program switch case search for the number three in its cases and the case which has ‘3’ will be executed.
  • If the cases don’t have the value then its default part will be executed.

Program pdf: Download


Spread the love
Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.