Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit1-C

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 60

UNIT-1

1. EXPLAIN ABOUT PRINTF() FUNCTION IN C LANGUAGE?

In C programming language, printf() function is used to print the “character, string, float, integer,
octal and hexadecimal values” onto the output screen.

We use printf() function with %d format specifier to display the value of an integer variable.

Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for
double and %x for hexadecimal variable.

To generate a newline,we use “\n” in C printf() statement.

The printf() and scanf() functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file).

printf() function

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

2.EXPALIN ABOUT SCANF() FUNCTION IN C LANGUAGE?

In C programming language, scanf() function is used to read character, string, numeric data from
keyboard

Consider below example program where user enters a character. This value is assigned to the
variable “ch” and then displayed.

Then, user enters a string and this value is assigned to the variable “str” and then displayed.

The scanf() function is used for input. It reads the input data from the console.

scanf("format string",argument_list);
3.WHAT AR E THE Comments in C?

Comments in C language are used to provide information about lines of code. It is widely used
for documenting code. There are 2 types of comments in C language.

1. Single Line Comments


2. Multi Line Comments

 Single Line Comments:

Single line comments are represented by double slash \\. Let's see an example of single line
comment in C.

#include<stdio.h>
void main( )
{
//printing information
printf("Hello C");

Output:

Hello C

Even you can place comment after statement.

Example:

printf("Hello C");//printing information

Mult Line Comments:

Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code
but it can't be nested. Syntax:

/*
code
to be commented
*/
Example of multi line comment in C.

#include<stdio.h>
void main()
{
/*printing information
Multi Line Comment*/
printf("Hello C");

Output:

Hello C

3. DEFINE KEYWORDS IN C?

Keywords are preserved words that have special meaning in C language. The meaning of C

language keywords has already been described to the C compiler. These meaning cannot be

changed. Thus, keywords cannot be used as variable names because that would try to change the

existing meaning of the keyword, which is not allowed. C Keywords are also called as reserved

words.

32 Keywords in C Programming Language

Auto double int struct

Break else long switch

Case enum register typedef

Char extern return union

Const float short unsigned

continue for signed void


Auto double int struct

Default goto sizeof volatile

Do if static while

4. WHAT IS DATA TYPE AND EXPLAIN DIFFERENT DATA TYPES IN C?


Data types specify how we enter data into our programs and what type of data we enter. C
language has some predefined set of data types to handle various kinds of data that we can use in
our program. These data types have different storage capacities.
C language supports 2 different types of data types:

1. Primary data types:

o Integer types
o Floating type
o Character type

int - Integer data types

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

In C programming, keyword int is used for declaring integer variable. For example:

int id;

Here, id is a variable of type integer.

You can declare multiple variable at once in C programming. For example:

int id, age;


float - Floating types

Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc. You can declare a
floating point variable in C by using either float or double keyword. For example:

float accountBalance;

double bookPrice;

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. Floating point variables has a precision of 6 digits whereas
the precision of double is 14 digits.

char - Character types

Keyword char is used for declaring character type variables. For example:

char test = 'h';

Here, test is a character variable. The value of test is 'h'.

The size of character variable is 1 byte.

Memory Size Range


Data Types

char 1 byte −128 to 127

int 2 byte −32,768 to 32,767

Float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932


void type:
void type means no value. This is usually used to specify the type of functions which returns
nothing.

5. WHAT IS CONSTANT? AND DIFFERENT TYPES OF CONSTANTS?


Constant in C means the content whose value does not change at the time of execution of a
program.

A constant is a value or an identifier whose value cannot be altered in a program. For example: 1,
2.5, "C programming is easy", etc.

As mentioned, an identifier also can be defined as a constant.

Syntax:

const type constant_name;

const double PI = 3.14

Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.

 Constants are also called literals.


 Constants can be any of the data types.
 It is considered best practice to define constants using only upper-case names.

Example:

 #include<stdio.h>
 main()
 {
 const int SIDE = 10;
 int area;
 area = SIDE*SIDE;
 printf("The area of the square with side: %d is: %d sq. units"
 , SIDE, area);
 }

List of Constants in C:

Constant Type of Value Stored

Integer Constant Constant which stores integer value

Floating Constant Constant which stores float value

Character Constant Constant which stores character value

String Constant Constant which stores string value

1. Integer constants

An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:

 decimal constant(base 10)


 octal constant(base 8)
 hexadecimal constant(base 16)

For example:

Decimal constants: 0, -9, 22 etc

Octal constants: 021, 077, 033 etc

Hexadecimal constants: 0x7f, 0x2a, 0x521 etc

In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.
2. Floating-point constants

A floating point constant is a numeric constant 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. Character constants

A character constant is a constant which uses single quotation around characters. For example:
'a', 'l', 'm', 'F'.

4.String constants

String constants are the constants which are enclosed in a pair of double-quote marks. For
example:

"good" //string constant

"" //null string constant

" " //string constant of six white space

"x" //string constant having single character.

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


6. DESCRIBE DIFFERENT TYPES OF ESCAPE SEQUENCES?

Sometimes, it is necessary to use characters which 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 sequence is used.

For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the
characters are interpreted by the compiler.

Escape Sequences

Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? Question mark
Escape Sequences

Escape Sequences Character

\0 Null character

7. EXPLAIN ALL OPERATORS IN C PROGRAMMING?

C operators are symbols that are used to perform mathematical or logical manipulations. C
programming language is rich with built-in operators. Operators take part in a program for
manipulating data and variables and form a part of the mathematical or logical expressions.
C operators can be classified into following types:

 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Special operators

Arithmetic Operators:

1. C Programming Supports 5 Arithmetic Operators.

2. Arithmetic Operators are used for “Arithmetic Calculation“.

5 arithmetic operators are shown in the following table. Arithmetic operators are used to perform
arithmetic operations in c programming.
Operator Meaning Example

+ Addition Operator 10 + 20 = 30

- Subtraction Operator 20 – 10 = 10

* Multiplication Operator 20 * 10 = 200

/ Division Operator 20 / 10 = 2

% Modulo Operator 20 % 6 = 2

Example : C Program to Verify Arithmetic Operator and Operation

#include <stdio.h>

void main()
{
int num1,num2;
int sum,sub,mult,div,mod;

printf("\nEnter First Number :");


scanf("%d",&num1);
printf("\nEnter Second Number :");
scanf("%d",&num2);

sum = num1 + num2;


printf("\nAddition is : %d",sum);

sub = num1 - num2;


printf("\nSubtraction is : %d",sub);

mult = num1 * num2;


printf("\nMultiplication is : %d",mult);

div = num1 / num2;


printf("\nDivision is : %d",div);

mod = num1 % num2;


printf("\nModulus is : %d",mod);

Output :

Enter First Number : 10


Enter Second Number : 5

Addition is : 15
Subtraction is : 5
Multiplication is : 50
Division is : 2
Modulus is : 0

RELATIONAL OPERATOR:

Relational operators in c programming is used for specifying the relation between two operands
such as greater than, less than and equals.

In C Programming we can compare the value stored between two variables and depending on
the result we can follow different blocks using Relational Operator in C.

Relational operators are used in decision making and loops.


Operator Meaning of Operator Example

== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1

< Less than 5 < 3 returns 0

!= Not equal to 5 != 3 returns 1

Greater than or equal


>= 5 >= 3 returns 1
to

<= Less than or equal to 5 <= 3 return 0

#include <stdio.h>

void main()

int a, b;

a = 10;

b = 20;

/* Here we check whether a is equal to 10 or not */

if( a == 10 ) {

/* if a is equal to 10 then this body will be executed */

printf( "a is equal to 10\n");

/* Here we check whether b is equal to 10 or not */

if( b == 10 )
{

/* if b is equal to 10 then this body will be executed */

printf( "b is equal to 10\n");

/* Here we check if a is less b than or not */

if( a < b ) {

/* if a is less than b then this body will be executed */

printf( "a is less than b\n");

/* Here we check whether a and b are not equal */

if( a != b ) {

/* if a is not equal to b then this body will be executed */

printf( "a is not equal to b\n");

When the above program is executed, it produces the following result −

a is equal to 10
a is less than b
a is not equal to b
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 of Operator Example

Logial AND. True only if all If c = 5 and d = 2 then, expression ((c == 5)


&&
operands are true && (d > 5)) equals to 0.

Logical OR. True only if either If c = 5 and d = 2 then, expression ((c == 5) ||


||
one operand is true (d > 5)) equals to 1.

Logical NOT. True only if the


! If c = 5 then, expression ! (c == 5) equals to 0.
operand is 0

#include <stdio.h>

int main()

int a = 1;

int b = 0;

if ( a && b )

printf("This will never print because condition is false\n" );


}

if ( a || b )

printf("This will be printed print because condition is true\n" );

if ( !(a && b) )

printf("This will be printed print because condition is true\n" );

When you compile and execute the above program, it produces the following result −

This will be printed print because condition is true


This will be printed print because condition is true

BITWISE OPERATORS:
Bitwise operators perform manipulations of data at bit level. These operators also
perform shifting of bits from right to left. Bitwise operators are not applied to float or double

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift


Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

Assignment Operators

1. Assignment Operator is Used to assign value to an variable.

2. Assignment Operator is denoted by equal to sign

3. Assignment Operator is binary operator which operates on two operands.

4. Assignment Operator have Two Values – L-Value and R-Value.Operator copies R-Value

into L-Value.

5. Assignment Operator have lower precedence than all available operators but has higher

precedence than comma Operator.

Operator Description Example

= assigns values from right side operands to left side operand a=b

+= adds right operand to the left operand and assign the result to left a+=b is same as
a=a+b

-= subtracts right operand from the left operand and assign the result to a-=b is same as a=a-b
left operand
*= mutiply left operand with the right operand and assign the result to left a*=b is same as a=a*b
operand

/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
operand

%= calculate modulus using two operands and assign the result to left a%=b is same as a=a
operand %b

Conditional operator
The conditional operators in C language are known by two more names

1. Ternary Operator
2. ? : Operator

It is actually the if condition that we use in C language decision making, but using conditional
operator, we turn the if condition statement into a short and simple operator.
The syntax of a conditional operator is :
expression 1 ? expression 2: expression 3
A conditional operator is a ternary operator, that is, it works on 3 operands.

Conditional Operator Syntax

conditionalExpression ? expression1 : expression2

The conditional operator works as follows:

 The first expression conditionalExpression is evaluated first. This expression evaluates to


1 if it's true and evaluates to 0 if it's false.
 If conditionalExpression is true, expression1 is evaluated.
 If conditionalExpression is false, expression2 is evaluated.

Example #7: C conditional Operator


#include <stdio.h>
int main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);

// If test condition (February == 'l') is true, days equal to 29.


// If test condition (February =='l') is false, days equal to 28.
days = (February == '1') ? 29 : 28;

printf("Number of days in February = %d",days);


return 0;
}

Output

If this year is leap year, enter 1. If not enter any integer: 1

Number of days in February = 29

sizeof operator

The sizeof is an unary operator which returns the size of data (constant, variables, array, structure
etc).

Example #6: sizeof Operator

#include <stdio.h>
int main()
{
int a, e[10];
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));
printf("Size of integer type array having 10 elements = %lu bytes\n", sizeof(e));
return 0;
}

Output

Size of int = 4 bytes

Size of float = 4 bytes

Size of double = 8 bytes

Size of char = 1 byte

Size of integer type array having 10 elements = 40 bytes.

Comma operator:

It is special kind of operator which is widely used in programming to separate the declaration of
multiple variable.

We have listed some of the hidden secrets of Comma operator and how it can be used in
programming in efficient manner.

It is special kind of operator which is widely used in programming to separate the declaration of
multiple variable.
We have listed some of the hidden secrets of Comma operator and how it can be used in
programming in efficient manner.

Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to
left

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left


Comma , Left to right

CONDITIONAL STATEMENTS:

C conditional statements allow you to make a decision, based upon the result of a condition.

These statements are called as Decision Making Statements or Conditional Statements.

In c programming, decision making is used to specify the order in which statements are
executed.

Decision making structures require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.

C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
o switch statement

If Statement

The single if statement in C language is used to execute the code if condition is true.

if(expression)
{
statement inside;
}
statement outside;
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>

void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}

x is greater than y

example 2:

Sample Program Code :


void main()
{
int a=5,b=6,c;
c=a+b;

if (c==11)
printf("Execute me 1");

printf("Execute me 2");
}

Output :

Execute me 1

If Statement :

if(conditional)
{
Statement No 1
Statement No 2
Statement No 3
.
.
.
Statement No N
}

Note :

1. More than One Conditions can be Written inside If statement.


2. Opening and Closing Braces are required only when “Code” after if statement

occupies multiple lines.

if(conditional)
Statement No 1
Statement No 2
Statement No 3

In the above example only Statement 1 is a part of if Statement.

1. Code will be executed if condition statement is True.

2. Non-Zero Number Inside if means “TRUE Condition”

if(100)
printf("True Condition");

structure of if:
if (condition/expression)
{

Statement 1; (condition is true)


Statement 2;

Statement 3;

}
Statement n;

Condition false statement n will be executed.


If else:

An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.

or

The if...else statement executes some code if the test expression is true (nonzero) and some other code
if the test expression is false (0).

if(conditional)
{
//True code
}
else
{
//False code
}

Syntax of if...else

if (testExpression) {

// codes inside the body of if

else {

// codes inside the body of else

}
If test expression is true, codes inside the body of if statement is executed and, codes inside the
body of else statement is skipped.

If test expression is false, codes inside the body of else statement is executed and, codes inside
the body of if statement is skipped.

Example:

Consider Example 1 with Explanation :

Consider Following Example –

int num = 20;

if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}

If part Executed if Condition Statement is True.

if(num == 20)
{
printf("True Block");
}

True Block will be executed if condition is True.


Else Part executed if Condition Statement is False.

else
{
printf("False Block");
}

Example :

void main()
{
int marks=50;
if(marks>=40)
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}

Output :

Student is Pass

Example:

// Program to check whether an integer entered by the user is odd or even

#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);

// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}

Output

Enter an integer: 7
7 is an odd integer.

Example:

#include <stdio.h>

int main () {

/* local variable definition */

int a = 100;

/* check the boolean condition */

if( a < 20 ) {

/* if condition is true then print the following */

printf("a is less than 20\n" );

} else {

/* if condition is false then print the following */

printf("a is not less than 20\n" );

printf("value of a is : %d\n", a);

return 0;

When the above code is compiled and executed, it produces the following result −
a is not less than 20;
value of a is : 100

example:
Example:
#include <stdio.h>

void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}

y is greater than x

example:
#include<stdio.h>

main() {
int num;
printf("Enter the number:");
scanf("%d", num);
/* check whether the number is negative number */ if (num < 0)
printf("The number is negative.");
else
printf("The number is positive.");

Out put:

Enter the number 3

The number is positive

Example:

Give year is leap year or not?


#include <stdio.h>

int main()
{
int year;
printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);

if ( year%400 == 0)
printf("%d is a leap year.\n", year);

else if ( year%100 == 0)
printf("%d is not a leap year.\n", year);

else if ( year%4 == 0 )
printf("%d is a leap year.\n", year);

else
printf("%d is not a leap year.\n", year);

return 0;

2012

Leap year
example of even and odd number using if-else statement in C language.

#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
return 0;
}
Output
enter a number:4
4 is even number

Nested if...else statement (if...elseif....else Statement)

The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.

Syntax of nested if...else statement.

if (testExpression1)

// statements to be executed if testExpression1 is true


}

else if(testExpression2)

// statements to be executed if testExpression1 is false and testExpression2 is true

else if (testExpression 3)

// statements to be executed if testExpression1 and testExpression2 is false and testExpression3


is true

else

// statements to be executed if all test expressions are false

Example #3: C Nested if...else statement

// Program to relate two integers using =, > or <


#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}

return 0;
}

Output
Enter two integers: 12

23

Result: 12 < 23

Example:

if-else-if statement in C language is given below.

#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number==10){
printf("number is equals to 10");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

SWITCH:
The if..else..if ladder allows you to execute a block code among many alternatives. If you are
checking on the value of a single variable in if...else...if, it is better to use switchstatement. In
nested if else when n statements are there n-1 times condition has to be checked. To avoid this
we use switch statement.

The switch statement is often faster than nested if...else

Switch statement is a control statement that allows us to choose only one choice among the many
given choices. The expression in switch evaluates to return an integral value, which is then
compared to the values present in different cases. It executes that block of code which matches
the case value. If there is no match, then default block is executed(if present). The general form
of switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
Rules for using switch statement

1. The expression (after switch keyword) must yield an integer value i.e the expression should
be an integer or a variable or an expression that evaluates to an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
4. The next line, after the case statement, can be any valid C statement.

Points to Remember

1. We don't use those expressions to evaluate switch case, which may return floating point
values or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to use break after each
block, but if you do not use it, then all the consecutive blocks of code will get executed after
the matching block.
3. int i = 1;
4. switch(i)
5. {
6. case 1:
7. printf("A"); // No break
8. case 2:
9. printf("B"); // No break
10. case 3:
11. printf("C");
12. break;
}

ABC
The output was supposed to be only A because only the first case matches, but as there is
no break statement after that block, the next blocks are executed too, until it
a break statement in encountered or the execution reaches the end of the switch block.

13. default case is executed when none of the mentioned case matches the switch expression.
The default case can be placed anywhere in the switch case. Even if we don't include the
default case, switch statement works.
14. Nesting of switch statements are allowed, which means you can have switch statements
inside another switch block. However, nested switch statements should be avoided as it
makes the program more complex and less readable.

Example of switch statement


#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
/* Printing the available options */
printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
/* Taking users input */
scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}

Difference between switch and if

 if statements can evaluate float conditions. switch statements cannot


evaluate floatconditions.
 if statement can evaluate relational operators. switch statement cannot evaluate relational
operators i.e they are not allowed in switch statement.
EXAMPLE:

simple example of c language switch statement.

#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}

}
Output
enter a number:4
number is not equal to 10, 50 or 100

example:

#include<stdio.h>

main()

int a;

printf("Please enter a no between 1 and 5: ");

scanf("%d",&a);

switch(a)

case 1:

printf("You chose One");

break;

case 2:

printf("You chose Two");


break;

case 3:

printf("You chose Three");

break;

case 4:

printf("You chose Four");

break;

case 5:

printf("You chose Five.");

break;

default :

printf("Invalid Choice. Enter a no between 1 and 5");

break;

Example:
Example: switch Statement

// Program to create a simple calculator


// Performs addition, subtraction, multiplication or division depending the input from user

# include <stdio.h>

int main() {

char operator;
double firstNumber,secondNumber;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operator);

printf("Enter two operands: ");


scanf("%lf %lf",&firstNumber, &secondNumber);

switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber+secondNumber);
break;

case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
break;

// operator is doesn't match any case constant (+, -, *, /)


default:
printf("Error! operator is not correct");
}

return 0;
}

Output

Enter an operator (+, -, *,): -

Enter two operands: 32.5

12.4

32.5 - 12.4 = 20.1

Example

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

/* local variable definition */

char grade = 'B';

switch(grade) {

case 'A' :

printf("Excellent!\n" );

break;

case 'B' :

case 'C' :

printf("Well done\n" );

break;

case 'D' :

printf("You passed\n" );

break;

case 'F' :

printf("Better try again\n" );

break;

default :

printf("Invalid grade\n" );

printf("Your grade is %c\n", grade );


return 0;

When the above code is compiled and executed, it produces the following result −

Well done
Your grade is B

C Loops

The loops in C language are used to execute a block of code or a part of the program several
times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.
By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array

C supports following types of loops:

 while loops
 do while loops
 for loops

While loop:

while loop is a most basic loop in C programming. while loop has one control condition, and
executes as long the condition is true. The condition of the loop is tested before the body of the
loop is executed, hence it is called an entry-controlled loop.

The basic format of while loop statement is:

Syntax:
While (condition)

statement(s);

Incrementation;

#include<stdio.h>

int main ()
{
/* local variable Initialization */ int n = 1,times=5;

/* while loops execution */ while( n <= times )


{
printf("C while loops: %d\n", n);
n++;
}
return 0;

Out put : 1 2 3 4 5

Example: Program to print first 10 natural numbers


#include<stdio.h>

void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}

1 2 3 4 5 6 7 8 9 10

Example
Live Demo

#include <stdio.h>

int main () {

/* local variable definition */

int a = 10;
/* while loop execution */

while( a < 20 ) {

printf("value of a: %d\n", a);

a++;

return 0;

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

do...while loop

The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.

or

C do while loops are very similar to the while loops, but it always executes the code block at
least once and furthermore as long as the condition remains true. This is an exit-controlledloop.

The basic format of do while loop statement is:

Syntax:
do

statement(s);

}while( condition );

Note :

 It is Exit Controlled Loop.


 Initialization , Incrementation and Condition steps are on different Line.
 It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute
at least once ]

Example
Live Demo

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

/* local variable definition */

int a = 10;

/* do loop execution */

do {

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 20 );

return 0;

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Example #2: do...while loop

// Program to add numbers until user enters zero

#include <stdio.h>
int main()
{
double number, sum = 0;

// loop body is executed at least once


do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}

Output

Enter a number: 1.5

Enter a number: 2.4

Enter a number: -3.4

Enter a number: 4.2

Enter a number: 0

Sum = 4.70
Example:

#include<stdio.h>

void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}

5 10 15 20 25 30 35 40 45 50
for loop in C

for loop
for loop is used to execute a set of statements repeatedly until a particular condition is satisfied.
We can say it is an open ended loop.. General format is,
for(initialization; condition; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after the
condition. In this loop we can have more than one initialization or increment/decrement,
separated using comma operator. But it can have only one condition.
The for loop is executed as follows:

1. It first evaluates the initialization code.


2. Then it checks the condition expression.
3. If it is true, it executes the for-loop body.
4. Then it evaluates the increment/decrement condition and again follows from step 2.
5. When the condition expression becomes false, it exits the loop.

Example: Program to print first 10 natural numbers


#inlcude<stdio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}

1 2 3 4 5 6 7 8 9 10

Nested for loop


We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is,
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
Example: Program to print half Pyramid of numbers
#include<stdio.h>

void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}

1
21
321
4321
54321
Comparison Chart

BASIS FOR
WHILE DO-WHILE
COMPARISON

General Form while ( condition) { do{

statements; //body of loop .

} statements; // body of loop.

} while( Condition );

Controlling Condition In 'while' loop the controlling In 'do-while' loop the controlling

condition appears at the start of the condition appears at the end of the

loop. loop.

Iterations The iterations do not occur if, the The iteration occurs at least once

condition at the first iteration, even if the condition is false at the

appears false. first iteration.

Type casting or type conversion?


Type casting is a way to convert a variable from one data type to another data type. For

example, if you want to store a long value into a simple integer then you can typecast long to int.

You can convert values from one type to another explicitly using the cast operator.

New data type should be mentioned before the variable name or value in brackets which to be

typecast.

A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
 All the data types of the variables are upgraded to the data type of the variable with
largest data type.

 bool -> char -> short int -> int ->
 unsigned int -> long -> unsigned ->
 long long -> float -> double -> long double
 It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long
is implicitly converted to float).
Example of Type Implicit Conversion:
// An example of implicit conversion
#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

printf("x = %d, z = %f", x, z);


return 0;
}
1. Output:

x = 107, z = 108.000000

2. Explicit Type Conversion– This process is also called type casting and it is user defined.
Here the user can type cast the result to make it of a particular data type.
The syntax in C:

(type) expression

Type indicated the data type to which the final result is converted.
// C program to demonstrate explicit type casting
#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;
}

Output:

sum = 2

Advantages of Type Conversion


 This is done to take advantage of certain features of type hierarchies or type
representations.
 It helps us to compute expressions containing variables of different data types.

You might also like