C Programing
C Programing
Languages such as C++/Java are developed from 'C'. These languages are
widely used in various technologies. Thus, 'C' forms a base for many other
languages that are currently in use.
'C' contains 32 keywords, various data types and a set of powerful built-in
functions that make programming very efficient.
Another feature of 'C' programming is that it can extend itself. A 'C' program
contains various functions which are part of a library. We can add our features
and functions to the library. We can access and use these functions anytime
we want in our program. This feature makes it simple while working with
complex programming.
Various compilers are available in the market that can be used for executing
programs written in this language.
It is a highly portable language which means programs written in 'C' language
can run on other machines. This feature is essential if we wish to use or
execute the code on another computer.
Nowadays, various compilers are available online, and you can use any of
those compilers. The functionality will never differ and most of the compilers
will provide the features required to execute both 'C' and 'C++' programs.
Clang compiler
MinGW compiler (Minimalist GNU for Windows)
Portable 'C' compiler
Turbo C
Summary
'C' was developed by Dennis Ritchie in 1972.
It is a robust language.
It is a low programming level language close to machine language
It is widely used in the software development field.
It is a procedure and structure oriented language.
It has the full support of various operating systems and hardware
platforms.
Many compilers are available for executing programs written in 'C'.
A compiler compiles the source file and generates an object file.
A linker links all the object files together and creates one executable file.
It is highly portable
In 1988, the American National Standards Institute (ANSI) had formalized the C language.
C was invented to write UNIX operating system.
C is a successor of 'Basic Combined Programming Language' (BCPL) called B language.
Linux OS, PHP, and MySQL are written in C.
C has been written in assembly language.
Database Systems
Language Interpreters
Compilers and Assemblers
Operating Systems
Network Drivers
Word Processors
Disadvantages of C
C does not provide Object Oriented Programming (OOP) concepts.
There are no concepts of Namespace in C.
C does not provide binding or wrapping up of data in a single unit.
C does not provide Constructor and Destructor.
Character set
A character set is a set of alphabets, letters and some special characters that
are valid in C language.
Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
0 1 2 3 4 5 6 7 8 9
Special Characters
, < > . _
( ) ; $ :
% [ ] # ?
^ ! * / |
- \ ~ +
C Keywords
Keywords are predefined, reserved words used in programming that have
special meanings to the compiler. Keywords are part of the syntax and they
cannot be used as an identifier. For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase.
Here is a list of all keywords allowed in ANSI C.
C Keywords
do if static while
All these keywords, their syntax, and application will be discussed in their
respective topics. However, if you want a brief overview of these keywords
without going further, visit List of all keywords in C programming.
C Identifiers
Identifier refers to name given to entities such as variables, functions,
structures etc.
int money;
double accountBalance;
1. A valid identifier can have letters (both uppercase and lowercase letters),
digits and underscores.
4. There is no rule on how long an identifier can be. However, you may run into
problems in some compilers if the identifier is longer than 31 characters.
You can choose any name as an identifier if you follow the above rule,
however, give meaningful names to identifiers that make sense.
Variables
In programming, a variable is a container (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name
(identifier). Variable names are just the symbolic representation of a memory
location. For example:
char ch = 'a';
// some code
ch = 'l';
1. A variable name can have only letters (both uppercase and lowercase letters),
digits and underscore.
Note: You should always try to give meaningful names to variables. For
example: firstName is a better variable name than fn .
C is a strongly typed language. This means that the variable type cannot be
changed once it is declared. For example:
Here, the type of number variable is int . You cannot assign a floating-point
(decimal) value 5.5 to this variable. Also, you cannot redefine the data type of
the variable to double . By the way, to store the decimal values in C, you need
to declare its type to either double or float .
Visit this page to learn more about different types of data a variable can store.
Literals
Literals are data used for representing fixed values. They can be used directly
in the code. For example: 1 , 2.5 , 'c' etc.
Here, 1 , 2.5 and 'c' are literals. Why? You cannot assign different values to
these terms.
1. Integers
octal (base 8)
For example:
2. Floating-point Literals
-2.0
0.0000234
-0.22E-5
4. Escape Sequences
Escape Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
Escape Sequences
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
For example: \n is used for a newline. The backslash \ causes escape from
the normal way the characters are handled by the compiler.
5. String Literals
Constants
If you want to define a variable whose value cannot be changed, you can use
the const keyword. This will create a constant. For example,
C Data Types
In this tutorial, you will learn about basic data types such as int, float,
char etc. in C programming.
int myVar;
Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.
Basic types
Here's a table containing commonly used types in C programming for quick
access.
char 1 %c
float 4 %f
double 8 %lf
signed char 1 %c
Type Size (bytes) Format Specifier
unsigned char 1 %c
int
Integers are whole numbers that can have both zero, positive and negative
values but no decimal values. For example, 0 , -5 , 10
int id;
The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states
from -2147483648 to 2147483647 .
float salary;
double price;
The size of float (single precision float data type) is 4 bytes. And the size
of double (double precision float data type) is 8 bytes.
char
Keyword char is used for declaring character type variables. For example,
void
void is an incomplete type. It means "nothing" or "no type". You can think of
void as absent.
For example, if a function is not returning anything, its return type should
be void .
If you need to use a large number, you can use a type specifier long . Here's
how:
long a;
long long b;
long double c;
Here variables a and b can store integer values. And, c can store a floating-
point number.
If you are sure, only a small integer ( [−32,767, +32,767] range) will be used,
you can use short .
short d;
You can always check the size of a variable using the sizeof() operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;
In C, signed and unsigned are type modifiers. You can alter the data storage of
a data type by using them. For example,
unsigned int x;
int y;
Here, the variable x can hold only zero and positive values because we have
used the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -
bool Type
Enumerated type
Complex types
C Output
In C programming, printf() is one of the main output function. The function
sends formatted output to the screen. For example,
Example 1: C Output
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Output
C Programming
All valid C programs must contain the main() function. The code execution
begins from the start of the main() function.
The printf() is a library function to send formatted output to the screen. The
function prints the string inside quotations.
To use printf() in our program, we need to include stdio.h header file using
the #include <stdio.h> statement.
The return 0; statement inside the main() function is the "Exit status" of the
program. It's optional.
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Output
Number = 5
We use %d format specifier to print int types. Here, the %d inside the
quotations will be replaced by the value of testInteger .
#include <stdio.h>
int main()
{
float number1 = 13.5;
double number2 = 12.4;
printf("number1 = %f\n", number1);
printf("number2 = %lf", number2);
return 0;
}
Output
number1 = 13.500000
number2 = 12.400000
#include <stdio.h>
int main()
{
char chr = 'a';
printf("character = %c.", chr);
return 0;
}
Output
character = a
C Input
In C programming, scanf() is one of the commonly used function to take input
from the user. The scanf() function reads formatted input from the standard
input such as keyboards.
#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Output
Enter an integer: 4
Number = 4
#include <stdio.h>
int main()
{
float num1;
double num2;
return 0;
}
Output
We use %f and %lf format specifier for float and double respectively.
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}
Output
Enter a character: g
You entered g.
When a character is entered by the user in the above program, the character
itself is not stored. Instead, an integer value (ASCII value) is stored.
And when we display that value using %c text format, the entered character is
displayed. If we use %d to display the character, it's ASCII value is printed.
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
Output
Enter a character: g
You entered g.
ASCII value is 103.
#include <stdio.h>
int main()
{
int a;
float b;
Output
%d for int
%f for float
%c for char
Here's a list of commonly used C data types and their format specifiers.
int %d
char %c
float %f
double %lf
unsigned int %u
signed char %c
unsigned char %c
long double
C Programming Operators
In this tutorial, you will learn about different operators in C programming
with the help of examples.
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).
* multiplication
/ division
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The modulo operator % computes the remainder. When a=9 is divided by b=4 ,
a/b = 2.5
a/d = 2.5
c/b = 2.5
c/d = 2
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can
also be used as postfixes like a++ and a-- . Visit this page to learn more about
how increment and decrement operators work when used as postfix.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
C Relational Operators
== Equal to 5 == 3 is evaluated to 0
return 0;
}
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
C Logical Operators
&& Logical AND. True only if all operands are true If c = 5 and d = 2 then, expr
|| Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expr
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
b) is 1 (true).
(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c <
b) are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b)
is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0
(false).
C Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof is a unary operator that returns the size of data (constants,
variables, array, structure, etc).
Example 6: sizeof Operator
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}
Output
C Introduction Examples
In this article, you will find a list of simple C programs such as:
displaying a line, adding two numbers, find ASCII value of a character,
etc.
Before you go through these examples, we suggest you to try creating these
programs on our own.
Examples
C program to print a sentence
C prog
C Program to Add Two Integers
In this example, the user is asked to enter two integers. Then, the sum of these
two integers is calculated and displayed on the screen.
To understand this example, you should have the knowledge of the following C
programming topics:
C Variables, Constants and Literals
C Data Types
C Input Output (I/O)
C Programming Operators
To understand this example, you should have the knowledge of the following C
programming topics:
C for Loop
C while and do...while Loop
The positive numbers 1, 2, 3... are known as natural numbers. The sum of natural
numbers up to 10 is:
sum = 1 + 2 + 3 + � + 10
In both programs, the loop is iterated n number of times. And, in each iteration, the
value of i is added to sum and i is incremented by 1.
Though both programs are technically correct, it is better to use for loop in this case. It's
because the number of iterations is known.
The above programs don't work properly if the user enters a negative integer. Here is a
little modification to the above program where we keep taking input from the user until a
positive integer is entered.
Visit this
C programs
C programs with output showing usage of operators, loops, functions,
arrays, performing operations on strings, files, pointers. Download
executable files and execute them without compiling the source file.
Code::Blocks IDE is used to write programs, most of these will work with
GCC and Dev C++ compilers. The first program, prints "Hello World."
#include <stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
Output of program:
"Hello World"
#include <stdio.h>
int main()
{
int x;
printf("Input an integer\n");
scanf("%d", &x); // %d is used for an integer
return 0;
}
Output:
Input an integer
7897
The integer is: 7897
#include <stdio.h>
int main()
{
int n;
printf("Enter a number?\n");
scanf("%d", &n);
if (n > 0)
printf("Greater than zero.\n");
else
printf("Less than or equal to zero.\n");
return 0;
}
Output:
Enter a number?
-45
Less than or equal to zero.
#include <stdio.h>
int main()
{
int c = 1; // Initializing variable
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
int main()
{
int n, c;
printf("Enter a number\n");
scanf("%d", &n);
if (n == 2)
printf("Prime number.\n");
else
{
for (c = 2; c <= n - 1; c++)
{
if (n % c == 0)
break;
}
if (c != n)
printf("Not prime.\n");
else
printf("Prime number.\n");
}
return 0;
}
Example 6 - command line arguments
#include <stdio.h>
int main(int argc, char *argv[])
{
int c;
return 0;
}
#include <stdio.h>
int main()
{
int array[100], n, c;
return 0;
}
int main()
{
printf("Main function.\n");
return 0;
}
#include <stdio.h>
int main()
{
// Single line comment in a C program
/*
* Multi-line comment syntax
* Comments help us to understand a program later
easily.
* Will you write comments while writing programs?
*/
#include <stdio.h>
#include <string.h>
struct game
{
char game_name[50];
int number_of_players;
}; // Note the semicolon
int main()
{
struct game g;
strcpy(g.game_name, "Cricket");
g.number_of_players = 11;
return 0;
}
#include <stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
return 0;
}
#include <graphics.h>
#include <conio.h>
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm,"C:\\TC\\BGI");
setcolor(BLUE);
getch();
closegraph( );
return 0;
}
How to compile C programs with GCC
compiler?
If you are using GCC on Linux operating system, then you may need to
modify the programs. For example, consider the following program that
prints the first ten natural numbers.
#include <stdio.h>
#include <conio.h>
int main()
{
int c;
getch();
return 0;
}
The program includes a header file <conio.h> and uses function getch,
but this file is Borland specific, so it works in Turbo C compiler but not in
GCC. The program for GCC must be like:
#include <stdio.h>
int main()
{
int c;
/* for loop */
return 0;
}
If you are using GCC, save the program in a file say "numbers.c" to compile
the program, open the terminal and enter the command "gcc numbers.c",
this compile the program and to execute it enter the command "./a.out" do
not use quotes while executing commands. You can specify the output file
name as "gcc numbers.c -o numbers.out", to run execute "./numbers.out"
in the terminal.
Continue Statement in C/C++
Continue is also a loop control statement just like the break statement. continue statement is
opposite to that of break statement, instead of terminating the loop, it forces to execute the next
iteration of the loop.
As the name suggest the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop following
the continue statement will be skipped and next iteration of the loop will begin.
Syntax:
continue;
Example:
Consider the situation when you need to write a program which prints number from 1 to 10 and
but not 6. It is specified that you have to do this using loop and only one loop is allowed to use.
Here comes the usage of continue statement. What we can do here is we can run a loop from 1 to
10 and every time we have to compare the value of iterator with 6. If it is equal to 6 we will use
the continue statement to continue to next iteration without printing anything otherwise we will
print the value.
Below is the implementation of the above idea:
C
C++
filter_none
edit
play_arrow
brightness_4
// C program to explain the use
// of continue statement
#include <stdio.h>
int main() {
// loop from 1 to 10
// If i is equals to 6,
// without printing
if (i == 6)
continue;
else
return 0;
Output:
1 2 3 4 5 7 8 9 10
The continue statement can be used with any other loop also like while or do while in a similar
way as it is used with for loop above.
Exercise Problem:
Given a number n, print triangular pattern. We are allowed to use only one loop.
Input: 7
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
Solution
Below is the implementation of the above idea:
C
C++
filter_none
edit
play_arrow
brightness_4
// C++ program to explain the use
// of continue statement
#include <iostream>
using namespace std;
int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {
// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;
else
// otherwise print the value of i
cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 5 7 8 9 10
The ladder if..else..if statement allows you to execute a block code among many
alternatives. If you are checking on the value of a single variable in ladder if..else..if,
it is better to use switch statement.
The switch statement is often faster than if...else (not always). Also, the syntax of switch
statement is cleaner and easier to understand.
C++ switch...case syntax
switch (n)
case constant1:
break;
case constant2:
break;
default:
When a case constant is found that matches the switch expression, control of the
program passes to the block of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler
will execute the block of code associated with the case statement until the end of switch
block, or until the break statement is encountered.
The break statement is used to prevent the code running into the next case.
The above figure shows how a switch statement works and conditions are checked
within the switch case clause.
Example: C++ switch Statement
1. // Program to built a simple calculator using switch Statement
2.
3. #include <iostream>
4. using namespace std;
5.
6. int main()
7. {
8. char o;
9. float num1, num2;
10.
11. cout << "Enter an operator (+, -, *, /): ";
12. cin >> o;
13.
14. cout << "Enter two operands: ";
15. cin >> num1 >> num2;
16.
17. switch (o)
18. {
19. case '+':
20. cout << num1 << " + " << num2 << " = " << num1+num2;
21. break;
22. case '-':
23. cout << num1 << " - " << num2 << " = " << num1-num2;
24. break;
25. case '*':
26. cout << num1 << " * " << num2 << " = " << num1*num2;
27. break;
28. case '/':
29. cout << num1 << " / " << num2 << " = " << num1/num2;
30. break;
31. default:
32. // operator is doesn't match any case constant (+, -, *, /)
33. cout << "Error! operator is not correct";
34. break;
35. }
36.
37. return 0;
38. }
Output
Enter an operator (+, -, *, /): +
-
Enter two operands: 2.3
4.5
2.3 - 4.5 = -2.2
The - o
In C++, there are two statements break; and continue; specifically to alter the normal
flow of a program.
Sometimes, it is desirable to skip the execution of a loop for a certain test condition or
terminate it immediately without checking the condition.
For example: You want to loop through data of all aged people except people aged 65.
Or, you want to find the first person aged 20.
In scenarios like these, continue; or a break; statement is used.
Syntax of break
break;
In real practice, break statement is almost always used inside the body of conditional
statement (if...else) inside the loop.
How break statement works?
C++ program to add all number entered by user until user enters 0.
Output
Enter a number: 4
Enter a number: 3.4
Enter a number: 6.7
Enter a number: -4.5
Enter a number: 0
Sum = 9.6
The user is asked to enter a number which is stored in the variable number. If the user
enters any number other than 0, the number is added to sum and stored to it.
Again, the user is asked to enter another number. When user enters 0, the test
expression inside if statement is false and body of else is executed which terminates
the loop.
1. #include <iostream>
2. using namespace std;
3.
4. int main()
5. {
6. for (int i = 1; i <= 10; ++i)
7. {
8. if ( i == 6 || i == 9)
9. {
10. continue;
11. }
12. cout << i << "\t";
13. }
14. return 0;
15. }
Output
1 2 3 4 5 7 8 10
The switch case statement is used when we have multiple options and we need to perform a
different task for each option.
#include <stdio.h>
int main()
{
int num=2;
switch(num+2)
{
case 1:
printf("Case1: Value is: %d", num);
case 2:
printf("Case1: Value is: %d", num);
case 3:
printf("Case1: Value is: %d", num);
default:
printf("Default: Value is: %d", num);
}
return 0;
}
Output:
Default: value is: 2
Explanation: In switch I gave an expression, you can give variable also. I gave num+2, where
num value is 2 and after addition the expression resulted 4. Since there is no case defined with
value 4 the default case is executed.
#include <stdio.h>
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
case 2:
printf("Case2 ");
case 3:
printf("Case3 ");
case 4:
printf("Case4 ");
default:
printf("Default ");
}
return 0;
}
Output:
#include <stdio.h>
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
}
return 0;
}
Output:
Case 2
Why didn’t I use break statement after default?
The control would itself come out of the switch after default so I didn’t use it, however if you
want to use the break after default then you can use it, there is no harm in doing that.
#include <stdio.h>
int main()
{
char ch='b';
switch (ch)
{
case 'd':
printf("CaseD ");
break;
case 'b':
printf("CaseB");
break;
case 'c':
printf("CaseC");
break;
case 'z':
printf("CaseZ ");
break;
default:
printf("Default ");
}
return 0;
}
Output:
CaseB
3) The expression provided in the switch should result in a constant value otherwise it would not
be valid.
For example:
Valid expressions for switch –
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions –
switch(ab+cd)
switch(a+b+c)
4) Nesting of switch statements are allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes program more
complex and less readable.
5) Duplicate case values are not allowed. For example, the following program is incorrect:
This program is wrong because we have two case ‘A’ here which is wrong as we cannot have
duplicate case values.
#include <stdio.h>
int main()
{
char ch='B';
switch (ch)
{
case 'A':
printf("CaseA");
break;
case 'A':
printf("CaseA");
break;
case 'B':
printf("CaseB");
break;
case 'C':
printf("CaseC ");
break;
default:
printf("Default ");
}
return 0;
}
6) The default statement is optional, if you don’t have a default in the program, it would run just
fine without any issues. However it is a good practice to have a default statement so that the
default executes if no case is matched. This is especially useful when we are taking input from
user for the case choices, since user can sometime enter wrong value, we can remind the user
with a proper error message that we can set in the default statement.
❮ PreviousNext ❯
Comments
Reply
o RizanaParvin says
MARCH 27, 2019 AT 9:52 AM
#include <stdio.h>
void main()
{
char operator;
int num1,num2;
printf(“\n Enter the operator (+, -, *, /):”);
scanf(“%c”,&operator);
printf(“\n Enter the Two numbers:”);
scanf(“%d%d”,&num1,&num2);
switch (operator)
{
case ‘+’:
printf(“%d+%d=%d”,num1,num2,num1+num2);
break;
case ‘-‘:
printf(“%d-%d=%d”,num1,num2,num1-num2);
break;
case ‘*’:
printf(“%d*%d=%d”,num1,num2,num1*num2);
break;
case ‘/’:
printf(“%d / %d = %d”,num1,num2,num1/num2);
break;
default:
printf(“\n Enter the operator only”);
break;
}
}
Reply
Reply
2. teboho says
Reply
Reply
4. Syed Minhaj Hussain says
Using Switch statement, write a program that displays the following menu for the food items
available to take order from the customer:
• B= Burger
• F= French Fries
• P= Pizza
• S= Sandwiches
The program inputs the type of food and quantity. It finally displays the total charges for the
order according to following criteria:
• Burger = Rs. 200
• French Fries= Rs. 50
• Pizza= Rs. 500
• Sandwiches= Rs. 150
Reply
5. FARZANA says
#include <stdio.h>
int main()
{
printf(“B=BURGER\nF=FRENCH FRY\nP=PIZZA\nS=SANDWICHES\n”);
char ss;
int n,x;
scanf(“%c”,&ss);
switch(ss)
{
case ‘B’:
scanf(“%d”,&n);
x= n*200;
printf(“Burger=Rs %d”,x);
case ‘F’:
scanf(“%d”,&n);
x= n*50;
printf(“Burger=Rs %d”,x);
case ‘P’:
scanf(“%d”,&n);
x= n*500;
printf(“Burger=Rs %d”,x);
case ‘S’:
scanf(“%d”,&n);
x= n*150;
printf(“Burger=Rs %d”,x);
}
}
Reply
int b,f,p,s,Burger,French,Pizza,Sandwiches;
char ch,B,F,P,S;
printf(“b1=Burger\n2=French Fries\n3=pizza\n4=Sandwiches\n”);
printf(“Enter your order \nplease Enter the choice 1,2,3,4\n”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“your order is Burger\n”);
printf(“please enter your quantity “);
scanf(“%d”,&b);
Burger=200*b;
scanf(“%d”,&f);
French=50*f;
scanf(“%d”,&p);
Pizza=500*p;
default:
printf(“invalid your choice”);
break;
}
}
/*D:\cp>a/.out
b1=Burger
2=French Fries
3=pizza
4=Sandwiches
Enter your order
please Enter the choice 1,2,3,4
4
your order is Sandwiches
please enter your quantity 6
your total charges is: 900
D:\cp>a/.out
b1=Burger
2=French Fries
3=pizza
4=Sandwiches
Enter your order
please Enter the choice 1,2,3,4
6
invalid your choice*/
Reply
7. dhruv says
SEPTEMBER 11, 2019 AT 4:44 PM
like
case 1:
Reply
Yes we can, see the point no 3 above in the important notes section. Expressions are
allowed in case.