0% found this document useful (0 votes)
24 views

C Programing

C was developed by Dennis Ritchie in 1972. It is a robust, low-level language close to machine language and is widely used in software development. C programs are compiled into machine-readable object files that are linked together and executed. Popular C compilers include Clang, MinGW, and Turbo C.

Uploaded by

fazal rahman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

C Programing

C was developed by Dennis Ritchie in 1972. It is a robust, low-level language close to machine language and is widely used in software development. C programs are compiled into machine-readable object files that are linked together and executed. Popular C compilers include Clang, MinGW, and Turbo C.

Uploaded by

fazal rahman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

History of C

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.

Where is C used? Key Applications


1. 'C' language is widely used in embedded systems.
2. It is used for developing system applications.
3. It is widely used for developing desktop applications.
4. Most of the applications by Adobe are developed using 'C' programming
language.
5. It is used for developing browsers and their extensions. Google's
Chromium is built using 'C' programming language.
6. It is used to develop databases. MySQL is the most popular database
software which is built using 'C'.
7. It is used in developing an operating system. Operating systems such
as Apple's OS X, Microsoft's Windows, and Symbian are developed
using 'C' language. It is used for developing desktop as well as mobile
phone's operating system.
8. It is used for compiler production.
9. It is widely used in IOT applications.

Why learn 'C'?


As we studied earlier, 'C' is a base language for many programming
languages. So, learning 'C' as the main language will play an important role
while studying other programming languages. It shares the same concepts
such as data types, operators, control statements and many more. 'C' can be
used widely in various applications. It is a simple language and provides faster
execution. There are many jobs available for a 'C' developer in the current
market.

'C' is a structured programming language in which program is divided into


various modules. Each module can be written separately and together it forms
a single 'C' program. This structure makes it easy for testing, maintaining and
debugging processes.

'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.

How 'C' Works?


C is a compiled language. A compiler is a special tool that compiles the
program and converts it into the object file which is machine readable. After
the compilation process, the linker will combine different object files and
creates a single executable file to run the program. The following diagram
shows the execution of a 'C' program

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.

Following is the list of popular compilers available online:

 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.

Uses of C Programming Language


In the beginning, C was used for developing system applications, e.g. :

 Database Systems
 Language Interpreters
 Compilers and Assemblers
 Operating Systems
 Network Drivers
 Word Processors

C Has Become Very Popular for Various Reasons


 One of the early programming languages.
 Still, the best programming language to learn quickly.
 C language is reliable, simple, and easy to use.
 C language is a structured language.
 Modern programming concepts are based on C.
 It can be compiled on a variety of computer platforms.
 Universities preferred to add C programming in their courseware.

Features of C Programming Language


 C is a robust language with a rich set of built-in functions and operators.
 Programs written in C are efficient and fast.
 C is highly portable; programs once written in C can be run on other machines with minor or no
modification.
 C is a collection of C library functions; we can also create our function and add it to the C library.
 C is easily extensible.
Advantages of C
 C is the building block for many other programming languages.
 Programs written in C are highly portable.
 Several standard functions are there (like in-built) that can be used to develop programs.
 C programs are collections of C library functions, and it's also easy to add functions to the C library.
 The modular structure makes code debugging, maintenance, and testing easier.

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.

C Keywords and Identifiers


In this tutorial, you will learn about keywords; reserved words in C
programming that are part of the syntax. Also, you will learn about
identifiers and how to name them.

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

C accepts both lowercase and uppercase alphabets as variables and


functions.
Digits

0 1 2 3 4 5 6 7 8 9

Special Characters

Special Characters in C Programming

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "

^ ! * / |

- \ ~ +

White space Characters


Blank space, newline, horizontal tab, carriage, return and form feed.

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

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

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.

Identifiers must be unique. They are created to give a unique name to an


entity to identify it during the execution of the program. For example:

int money;
double accountBalance;

Here, money and accountBalance are identifiers.


Also remember, identifier names must be different from keywords. You cannot
use int as an identifier because int is a keyword.

Rules for naming identifiers

1. A valid identifier can have letters (both uppercase and lowercase letters),
digits and underscores.

2. The first letter of an identifier should be either a letter or an underscore.

3. You cannot use keywords as identifiers.

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.

C Variables, Constants and Literals


In this tutorial, you will learn about variables and rules for naming a
variable. You will also learn about different literals in C programming
and how to create constants.

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:

int playerScore = 95;

Here, playerScore is a variable of int type. Here, the variable is assigned an


integer value 95 .

The value of a variable can be changed, hence the name variable.

char ch = 'a';
// some code
ch = 'l';

Rules for naming a variable

1. A variable name can have only letters (both uppercase and lowercase letters),
digits and underscore.

2. The first letter of a variable should be either a letter or an underscore.


3. There is no rule on how long a variable name (identifier) can be. However,
you may run into problems in some compilers if the variable name is longer
than 31 characters.

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:

int number = 5; // integer variable


number = 5.5; // error
double number; // error

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

An integer is a numeric literal(associated with numbers) without any fractional


or exponential part. There are three types of integer literals in C programming:

 decimal (base 10)

 octal (base 8)

 hexadecimal (base 16)

For example:

Decimal: 0, -9, 22 etc

Octal: 021, 077, 033 etc

Hexadecimal: 0x7f, 0x2a, 0x521 etc

In C programming, octal starts with a 0 , and hexadecimal starts with a 0x .

2. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an


exponent form. For example:

-2.0

0.0000234

-0.22E-5

Note: E-5 = 10-5


3. Characters

A character literal is created by enclosing a single character inside single


quotation marks. For example: 'a' , 'm' , 'F' , '2' , '}' etc.

4. Escape Sequences

Sometimes, it is necessary to use characters that cannot be typed or has


special meaning in C programming. For example: newline(enter), tab,
question mark etc.

In order to use these characters, escape sequences are used.

Escape Sequences

Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return

\t Horizontal tab
Escape Sequences

Escape Sequences Character

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? 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

A string literal is a sequence of characters enclosed in double-quote marks.


For example:

"good" //string constant


"" //null string constant

" " //string constant of six white space

"x" //string constant having a single character.

"Earth is round\n" //prints string with a newline

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,

const double PI = 3.14;

Notice, we have added keyword const .

Here, PI is a symbolic constant; its value cannot be changed.

const double PI = 3.14;


PI = 2.9; //Error

C Data Types
In this tutorial, you will learn about basic data types such as int, float,
char etc. in C programming.

In C programming, data types are declarations for variables. This determines


the type and size of data associated with variables. For example,

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.

Type Size (bytes) Format Specifier

int at least 2, usually 4 %d

char 1 %c

float 4 %f

double 8 %lf

short int 2 usually %hd

unsigned int at least 2, usually 4 %u

long int at least 4, usually 8 %li

long long int at least 8 %lli

unsigned long int at least 4 %lu

unsigned long long int at least 8 %llu

signed char 1 %c
Type Size (bytes) Format Specifier

unsigned char 1 %c

long double at least 10, usually 12 or 16 %Lf

int

Integers are whole numbers that can have both zero, positive and negative
values but no decimal values. For example, 0 , -5 , 10

We can use int for declaring an integer variable.

int id;

Here, id is a variable of type integer.


You can declare multiple variables at once in C programming. For example,

int id, age;

The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states
from -2147483648 to 2147483647 .

float and double

float and double are used to hold real numbers.

float salary;
double price;

In C, floating-point numbers can also be represented in exponential. For


example,

float normalizationFactor = 22.442e2;

What's the difference between float and double ?

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,

char test = 'h';

The size of the character variable is 1 byte.

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 .

Note that, you cannot create variables of void type.


short and long

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;

printf("size of short = %d bytes\n", sizeof(a));


printf("size of long = %d bytes\n", sizeof(b));
printf("size of long long = %d bytes\n", sizeof(c));
printf("size of long double= %d bytes\n", sizeof(d));
return 0;
}
signed and unsigned

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 -

231 to 231-1 , whereas variable x can hold values from 0 to 232-1 .

Other data types defined in C programming are:

 bool Type

 Enumerated type

 Complex types

Derived Data Types


Data types that are derived from fundamental data types are derived types.
For example: arrays, pointers, function types, structures, etc.

We will learn about these derived data types in later tutorials.


C Input Output (I/O)
In this tutorial, you will learn to use scanf() function to take input from
the user, and printf() function to display output to the user.

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

How does this program work?

 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.

Example 2: Integer Output

#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 .

Example 3: float and double Output

#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

To print float , we use %f format specifier. Similarly, we use %lf to


print double values.

Example 4: Print Characters

#include <stdio.h>
int main()
{
char chr = 'a';
printf("character = %c.", chr);
return 0;
}

Output

character = a

To print char , we use %c format specifier.

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.

Example 5: Integer Input/Output

#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

Here, we have used %d format specifier inside the scanf() function to


take int input from the user. When the user enters an integer, it is stored in
the testInteger variable.
Notice, that we have used &testInteger inside scanf() . It is
because &testInteger gets the address of testInteger , and the value entered
by the user is stored in that address.
Example 6: Float and Double Input/Output

#include <stdio.h>
int main()
{
float num1;
double num2;

printf("Enter a number: ");


scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);

printf("num1 = %f\n", num1);


printf("num2 = %lf", num2);

return 0;
}

Output

Enter a number: 12.523


Enter another number: 10.2
num1 = 12.523000
num2 = 10.200000

We use %f and %lf format specifier for float and double respectively.

Example 7: C Character I/O

#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.

Example 8: ASCII Value

#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);

// When %c is used, a character is displayed


printf("You entered %c.\n",chr);

// When %d is used, ASCII value is displayed


printf("ASCII value is % d.", chr);
return 0;
}

Output
Enter a character: g
You entered g.
ASCII value is 103.

I/O Multiple Values


Here's how you can take multiple inputs from the user and display them.

#include <stdio.h>
int main()
{
int a;
float b;

printf("Enter integer and then a float: ");

// Taking multiple inputs


scanf("%d%f", &a, &b);

printf("You entered %d and %f", a, b);


return 0;
}

Output

Enter integer and then a float: -3


3.4
You entered -3 and 3.400000

Format Specifiers for I/O


As you can see from the above examples, we use

 %d for int

 %f for float

 %lf for double

 %c for char

Here's a list of commonly used C data types and their format specifiers.

Data Type Format Specifier

int %d

char %c

float %f

double %lf

short int %hd

unsigned int %u

long int %li

long long int %lli

unsigned long int %lu

unsigned long long int %llu


Data Type Format Specifier

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.

An operator is a symbol that operates on a value or a variable. For


example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.

C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).

Operator Meaning of Operator

+ addition or unary plus


Operator Meaning of Operator

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)

Example 1: Arithmetic Operators

// Working of arithmetic operators


#include <stdio.h>
int main()
{
int a = 9,b = 4, 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("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 operators + , - and * computes addition, subtraction, and multiplication


respectively as you might have expected.
In normal calculation, 9/4 = 2.25 . However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is also
an integer. The compiler neglects the term after the decimal point and shows
answer 2 instead of 2.25 .

The modulo operator % computes the remainder. When a=9 is divided by b=4 ,

the remainder is 1 . The % operator can only be used with integers.


Suppose a = 5.0 , b = 2.0 , c = 5 and d = 2. Then in C programming,

// Either one of the operands is a floating-point number

a/b = 2.5

a/d = 2.5

c/b = 2.5

// Both operands are integers

c/d = 2

C Increment and Decrement Operators


C programming has two operators increment ++ and decrement -- to change
the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the
value by 1. These two operators are unary operators, meaning they only
operate on a single operand.
Example 2: Increment and Decrement Operators

// Working of increment and decrement operators


#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

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 =

Operator Example Same as

= 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

Example 3: Assignment Operators

// Working of assignment operators


#include <stdio.h>
int main()
{
int a = 5, c;

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

A relational operator checks the relationship between two operands. If the


relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.


Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1


Operator Meaning of Operator Example

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators

// Working of relational operators


#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

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

An expression containing logical operator returns either 0 or 1 depending


upon whether expression results true or false. Logical operators are
commonly used in decision making in C programming.
Operator Meaning Example

&& 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

! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(

Example 5: Logical Operators

// Working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a == b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", 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

Explanation of logical operator program


 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c >

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

During computation, mathematical operations like: addition, subtraction,


multiplication, division, etc are converted to bit-level which makes processing
faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Visit bitwise operator in C to learn more.


Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:
int a, c = 5, d;

The sizeof operator

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

Size of int = 4 bytes


Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

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.

We have learned about the following topics so far:

1. Variables and Constants


2. Data Types
3. Input and Output in C programming
4. Operators
To understand these topics better, we have created some examples.

Before you go through these examples, we suggest you to try creating these
programs on our own.

We understand that programming can by start If you are just a programming


newbie. In that case, go through each example below and see if you can
understand them. Once you do that, try writing these programs on your own.

Examples
C program to print a sentence

C program to print an integer entered by the user

C program to add two integers entered by the User

C program to multiply two floating-point numbers


C program to find ASCII value of a character entered by the user

C program to find quotient and remainder of Two Integers

C program to find the size of int, float, double and char

C program to demonstrate the working of keyword long

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.

Program to Add Two Integers


1. #include <stdio.h>
2. int main() {
3.
4. int number1, number2, sum;
5.
6. printf("Enter two integers: ");
7. scanf("%d %d", &number1, &number2);
8.
9. // calculating sum
10. sum = number1 + number2;
11.
12. printf("%d + %d = %d", number1, number2, sum);
13. return 0;
14. }
Output
Enter two integers: 12
11
12 + 11 = 23

C Program to Compute Quotient and


Remainder
In this example, you will learn to find the quotient and remainder when an integer
is divided by another integer.
To understand this example, you should have the knowledge of the following C
programming topics:
 C Data Types
 C Variables, Constants and Literals
 C Input Output (I/O)
 C Programming Operators

Program to Compute Quotient and Remainder


1. #include <stdio.h>
2. int main() {
3. int dividend, divisor, quotient, remainder;
4. printf("Enter dividend: ");
5. scanf("%d", ÷nd);
6. printf("Enter divisor: ");
7. scanf("%d", &divisor);
8.
9. // Computes quotient
10. quotient = dividend / divisor;
11.
12. // Computes remainder
13. remainder = dividend % divisor;
14.
15. printf("Quotient = %d\n", quotient);
16. printf("Remainder = %d", remainder);
17. return 0;
18. }
19.
Output
Enter dividend: 25
Enter divisor: 4
Quotient = 6
Remainder = 1
C Program to Multiply two Floating Point
Numbers
In this example, the product of the numbers (floating-point numbers) entered by
the user is calculated and printed 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

Program to Multiply Two Numbers


1. #include <stdio.h>
2. int main() {
3. double a, b, product;
4. printf("Enter two numbers: ");
5. scanf("%lf %lf", &a, &b);
6.
7. // Calculating product
8. product = a * b;
9.
10. // Result up to 2 decimal point is displayed using %.2lf
11. printf("Product = %.2lf", product);
12.
13. return 0;
14. }
15.
Output
1. Enter two numbers: 2.4
2. 1.12
3. Product = 2.69

C Program to Calculate the Sum of Natural


Numbers
In this example, you will learn to calculate the sum of natural numbers entered by
the user.

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

Sum of Natural Numbers Using for Loop


1. #include <stdio.h>
2. int main() {
3. int n, i, sum = 0;
4.
5. printf("Enter a positive integer: ");
6. scanf("%d", &n);
7.
8. for (i = 1; i <= n; ++i) {
9. sum += i;
10. }
11.
12. printf("Sum = %d", sum);
13. return 0;
14. }
15.
The above program takes input from the user and stores it in the variable n.
Then, for loop is used to calculate the sum up to n.

Sum of Natural Numbers Using while Loop


1. #include <stdio.h>
2. int main() {
3. int n, i, sum = 0;
4. printf("Enter a positive integer: ");
5. scanf("%d", &n);
6. i = 1;
7.
8. while (i <= n) {
9. sum += i;
10. ++i;
11. }
12.
13. printf("Sum = %d", sum);
14. return 0;
15. }
Output
Enter a positive integer: 100
Sum = 5050

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.

Read Input Until a Positive Integer is Entered


1. #include <stdio.h>
2. int main() {
3. int n, i, sum = 0;
4.
5. do {
6. printf("Enter a positive integer: ");
7. scanf("%d", &n);
8. } while (n <= 0);
9.
10. for (i = 1; i <= n; ++i) {
11. sum += i;
12. }
13.
14. printf("Sum = %d", sum);
15. return 0;
16. }
17.

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."

C programming examples with output


Example 1 - C hello world program
/** My first C program */

#include <stdio.h>

int main()
{
printf("Hello World\n");
return 0;
}
Output of program:
"Hello World"

Example 2 - C program to get input from a user using scanf

#include <stdio.h>
int main()
{
int x;

printf("Input an integer\n");
scanf("%d", &x); // %d is used for an integer

printf("The integer is: %d\n", x);

return 0;
}
Output:
Input an integer
7897
The integer is: 7897

Example 3 - using if else control instructions

#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.

Example 4 - while loop example

#include <stdio.h>

int main()
{
int c = 1; // Initializing variable

while (c <= 10) // While loop will execute till the


condition is true
{
printf("%d ", c); // Note the space after %d for
gap in the numbers we want in output
c++;
}

return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10

Example 5 - C program check if an integer is prime or not

#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;

printf("Number of command line arguments


passed: %d\n", argc);

for (c = 0; c < argc; c++)


printf("%d argument is %s\n", c + 1, argv[c]);

return 0;
}

This program prints the number of arguments and their contents.

Example 7 - Array program

#include <stdio.h>
int main()
{
int array[100], n, c;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d elements\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("The array elements are:\n");

for (c = 0; c < n; c++)


printf("%d\n", array[c]);

return 0;
}

Example 8 - function program


#include <stdio.h>
void my_function(); // Declaring a function

int main()
{
printf("Main function.\n");

my_function(); // Calling the function

printf("Back in function main.\n");

return 0;
}

// Defining the function


void my_function()
{
printf("Welcome to my function. Feel at home.\n");
}

Example 9 - Using comments in a program

#include <stdio.h>

int main()
{
// Single line comment in a C program

printf("Writing comments is very useful.\n");

/*
* Multi-line comment syntax
* Comments help us to understand a program later
easily.
* Will you write comments while writing programs?
*/

printf("Good luck C programmer.\n");


return 0;
}
Example 10 - using structures in C programming

#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;

printf("Name of game: %s\n", g.game_name);


printf("Number of
players: %d\n", g.number_of_players);

return 0;
}

Example 11 - C program for Fibonacci series

#include <stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;

printf("Enter the number of terms\n");


scanf("%d", &n);

printf("First %d terms of Fibonacci series


are:\n", n);
for (c = 0; c < n; c++)
{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n", next);
}

return 0;
}

Example 12 - C graphics programming

#include <graphics.h>
#include <conio.h>
int main()
{
int gd = DETECT, gm;

initgraph(&gd, &gm,"C:\\TC\\BGI");

outtextxy(10, 20, "Graphics programming is fun!");

circle(200, 200, 50);

setcolor(BLUE);

line(350, 250, 450, 50);

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;

for (c = 1; c <= 10; c++)


printf("%d\n", 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 */

for (c = 1; c <= 10; c++)


printf("%d\n", c);

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

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

printf("%d ", i);

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

C++ switch..case Statement


In this article, you will learn to create a switch statement in C++ programming (with an
example).

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:

// code to be executed if n is equal to constant1;

break;

case constant2:

// code to be executed if n is equal to constant2;

break;

default:

// code to be executed if n doesn't match any constant

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.

Flowchart of switch Statement

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

C++ break and continue Statement


In this article, you'll learn about C++ statements: break and continue. More specifically,
what are they, when to use them and how to use them efficiently.

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.

C++ break Statement


The break; statement terminates a loop (for, while and do..while loop) and a switch
statement immediately when it appears.

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?

Example 1: C++ break

C++ program to add all number entered by user until user enters 0.

1. // C++ Program to demonstrate working of break statement


2.
3. #include <iostream>
4. using namespace std;
5. int main() {
6. float number, sum = 0.0;
7.
8. // test expression is always true
9. while (true)
10. {
11. cout << "Enter a number: ";
12. cin >> number;
13.
14. if (number != 0.0)
15. {
16. sum += number;
17. }
18. else
19. {
20. // terminates the loop if number equals 0.0
21. break;
22. }
23.
24. }
25. cout << "Sum = " << sum;
26.
27. return 0;
28. }

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

In the above program, the test expression is always true.

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.

Finally, the sum is displayed.

C++ continue Statement


It is sometimes necessary to skip a certain test condition within a loop. In such
case, continue; statement is used in C++ programming.
Syntax of continue
continue;

In practice, continue; statement is almost always used inside a conditional statement.

Working of continue Statement

Example 2: C++ continue

C++ program to display integer from 1 to 10 except 6 and 9.

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

In above program, when i is 6 or 9, execution of statement cout << i << "\t"; is


skipped inside the loop using continue; statement.
C – switch case statement in C Programming
with example
BY CHAITANYA SINGH | FILED UNDER: C-PROGRAMMING

The switch case statement is used when we have multiple options and we need to perform a
different task for each option.

C – Switch Case Statement


Before we see how a switch case statement works in a C program, let’s checkout the syntax of it.

switch (variable or an integer expression)


{
case constant:
//C Statements
;
case constant:
//C Statements
;
default:
//C Statements
;
}
Flow Diagram of Switch Case

Example of Switch Case in C


Let’s take a simple example to understand the working of a switch case statement in C program.

#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.

Twist in a story – Introducing Break statement


Before we discuss more about break statement, guess the output of this C program.

#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:

Case2 Case3 Case4 Default


I passed a variable to switch, the value of the variable is 2 so the control jumped to the case 2,
However there are no such statements in the above program which could break the flow after the
execution of case 2. That’s the reason after case 2, all the subsequent cases and default
statements got executed.

How to avoid this situation?


We can use break statement to break the flow of control after every case block.

Break statement in Switch Case


Break statements are useful when you want your program-flow to come out of the switch body.
Whenever a break statement is encountered in the switch body, the control comes out of the
switch case statement.
Example of Switch Case with break
I’m taking the same above that we have seen above but this time we are using break.

#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.

Few Important points regarding Switch Case


1) Case doesn’t always need to have order 1, 2, 3 and so on. They can have any integer value
after case keyword. Also, case doesn’t need to be in an ascending order always, you can specify
them in any order as per the need of the program.

2) You can also use characters in switch case. for example –

#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

1. judith cherono says

FEBRUARY 15, 2016 AT 6:41 PM

write a c program using switch case statement to output the following


2*3=6
2+3=5
4+6=10
4/5=0.8

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

o Nana Percy says


JULY 12, 2019 AT 6:18 PM

Please can I get the soluton to this question?

Reply

2. teboho says

FEBRUARY 25, 2016 AT 1:07 AM

wow that’s a beautiful explanation

Reply

3. vikash tiwari says

APRIL 2, 2016 AT 8:17 AM

wow! how smoothly you explain it , it’s great.

Reply
4. Syed Minhaj Hussain says

APRIL 7, 2016 AT 6:42 AM

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

DECEMBER 12, 2018 AT 5:02 PM

#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

6. Nandlal Dnyaneshwar Patil says

AUGUST 3, 2019 AT 6:56 PM

Answer to the question asked by Syed Minhaj Hussain:


#include <stdio.h>
int main()
{

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;

printf(“your total charges is: %d”,Burger);


break;
case 2:
printf(“your order is French \n”);
printf(“please enter your quantity “);

scanf(“%d”,&f);
French=50*f;

printf(“your total charges is: %d”,French);


break;
case 3:
printf(“your order is Pizza\n”);
printf(“please enter your quantity “);

scanf(“%d”,&p);
Pizza=500*p;

printf(“your total charges is: %d”,Pizza);


break;
case 4:
printf(“your order is Sandwiches\n”);
printf(“please enter your quantity “);
scanf(“%d”,&s);
Sandwiches=150*s;

printf(“your total charges is: %d”,Sandwiches);


break;

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

can we write an expression in case

like
case 1:

so in case of 1 can we write an expression?

Reply

o Chaitanya Singh says

OCTOBER 7, 2019 AT 12:21 PM

Yes we can, see the point no 3 above in the important notes section. Expressions are
allowed in case.

You might also like