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

M1-PDF Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

MODULE 1

INTRODUCTION TO C LANGUAGE: PRE-PROCESSOR DIRECTIVES, HEADER FILES, DATA


TYPES AND QUALIFIERS. OPERATORS AND EXPRESSIONS. DATA INPUT AND OUTPUT,
CONTROL STATEMENTS.

INTRODUCTION TO C

The C is a general purpose,procedural, imperative computer programming language developed in


1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.
The C is the most widely used computer language, it keeps fluctuating at number one scale of
popularity along with Java programming language, which is also equally popular and most widely
used among modern software programmers.
The UNIX operating system, the C compiler, and essentially all UNIX applications programs have
been written in C. The C has now become a widely used professional language for various reasons.

 Easy to learn
 Structured language
 It produces efficient programs.
 It can handle low-level activities.
 It can be compiled on a variety of computer platforms.

Facts about C

 C was invented to write an operating system called UNIX.


 C is a successor of B language which was introduced around 1970
 The language was formalized in 1988 by the American National Standard Institute (ANSI).
 The UNIX OS was totally written in C by 1973.
 Today C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art softwares have been implemented using C.
 Today's most popular Linux OS and RBDMS MySQL have been written in C.

Why to use C?

C was initially used for system development work, in particular the programs that make-up the
operating system. C was adopted as a system development language because it produces code that runs
nearly as fast as code written in assembly language. Some examples of the use of C might be:

 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities

C Programs

A C program can vary from 3 lines to millions of lines and it should be written into one or more text
files with extension ".c"; for example, hello.c. You can use "vi", "vim" or any other text editor to write
your C program into a file.

Basic concepts of a c program

Before we study basic building blocks of the C programming language, let us look a bare minimum C
program structure so that we can take it as a reference in upcoming chapters.

C Hello World Example

A C program basically consists of the following parts:


 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments

Let us look at a simple code that would print the words "Hello World":

#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}

Let us look various parts of the above program:

1. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to
include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in
the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "Hello, World!" to
be displayed on the screen.
5. The next line return 0; terminates main()function and returns the value 0.

Compile & Execute C Program:

Lets look at how to save the source code in a file, and how to compile and run it. Following are the
simple steps:
1. Open a text editor and add the above-mentioned code.
2. Save the file as hello.c
3. Open a command prompt and go to the directory where you saved the file.
4. Type gcc hello.c and press enter to compile your code.
5. If there are no errors in your code the command prompt will take you to the next line and would generate
a.out executable file.
6. Now, type a.out to execute your program.
7. You will be able to see "Hello World" printed on the screen.

C PREPROCESSOR DIRECTIVES

 Before a C program is compiled in a compiler, source code is processed by a program called


preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol.
Below is the list of some important preprocessor directives that C programming language.

Preprocessor Syntax/Description

Syntax: #define
This macro defines constant value and can be any of the basic data
Macro types.

Syntax: #include <file_name>


The source code of the file “file_name” is included in the main
Header file inclusion program at the specified place.

HEADER FILES IN C
Pre-processor statements begin with a # character. In this case, the pre-processor statement we
have is a #include statement. #include tells the pre-processor to "glue in" another bit of C source code
here. Included files are known as header files and by convention have the extension .h. The angle
brackets surrounding the file name tell you that the file being included is part of the C libraries on this
machine. In this case, it is the standard library header stdio.h which contains information about standard
input and output routines.

The Four Basic Data Types


In Standard C there are four basic data types. They are int, char, float, and double.

The int type

The int type stores integers in the form of "whole numbers". An integer is typically the size of one machine
word, which on most modern home PCs is 32 bits (4 octets). Examples of literals are whole numbers
(integers) such as 1,2,3, 10, 100... When int is 32 bits (4 octets), it can store any whole number (integer)
between -2147483648 and 2147483647. A 32 bit word (number) has the possibility of representing any one
number out of 4294967296 possibilities (2 to the power of 32).
int numberOfStudents, i, j=5;
In this declaration we declare 3 variables, numberOfStudents, i and j, j here is assigned the literal 5.

The char type

The char type is capable of holding any member of the execution character set. It stores the same kind of
data as an int (i.e. integers), but typically has a size of one byte. The size of a byte is specified by the macro
CHAR_BIT which specifies the number of bits in a char (byte). In standard C it never can be less than 8 bits.
A variable of type char is most often used to store character data, hence its name.

Examples of character literals are 'a', 'b', '1', etc., as well as some special characters such as '\0' (the null
character) and '\n' (newline, recall "Hello, World"). Note that the char value must be enclosed within single
quotations.
char letter1 = 'a';
This is good programming practice in that it allows a person reading your code to understand that letter1 is
being initialized with the letter 'a' to start off with.
char letter2 = 97; /* in ASCII, 97 = 'a' */
This is considered by some to be extremely bad practice, if we are using it to store a character, not a small
number, in that if someone reads your code, most readers are forced to look up what character corresponds
with the number 97 in the encoding scheme. In the end, letter1 and letter2 store both the same thing the letter
'a', but the first method is clearer, easier to debug, and much more straightforward.

The float type

float is short for floating point. It stores real numbers also, but is only one machine word in size.
Therefore, it is used when less precision than a double provides is required. float literals must be suffixed with
F or f, otherwise they will be interpreted as doubles. Examples are: 3.1415926f, 4.0f, 6.022e+23f. float
variables can be declared using the float keyword.

The double type

The double and float types are very similar. The float type allows you to store single-precision floating
point numbers, while the double keyword allows you to store double-precision floating point numbers – real
numbers, in other words, both integer and non-integer values. Its size is typically two machine words, or 8
bytes on most machines. Examples of double literals are 3.1415926535897932, 4.0, 6.022e+23 (scientific
notation). If you use 4 instead of 4.0, the 4 will be interpreted as an int.

Qualifiers
Qualifiers are the keywords just using to alter the meaning of basic data types to yield a new data type.
Following are the important qualifiers in c.

 Size qualifiers
 Sign qualifiers
 Constant qualifiers
 Volatile qualifiers

Size Qualifiers

Size qualifiers are the keywords using to alter the size of basic data types. They are long and short. For
integer data types, there are three sizes: int, and two additional sizes called long and short, which are
declared as long int and short int. The keywords long and short are called sub-type qualifiers.
The long is intended to provide a larger size of integer, and short is intended to provide a smaller size of
integer. However, not all implementations provide distinct sizes for them. The requirement is
that short and int must be at least 16 bits, long must be at least 32 bits, and that short is no longer than int,
which is no longer than long. Typically, short is 16 bits, long is 32 bits, and int is either 16 or 32 bits.

Eg:- long int, long float, short double etc.

Sign Qualifiers

Sign qualifiers are two signed and unsigned. signed is default one, i.e., declaring

int a;

Is same as

signed int a;

both can store both +ve and –ve numbers. Declaring a variable

unsigned int a;

can only store +ve values.

Constant Qualifier

If you are declaring a variable as:

cost int a=2;

then you can never change the value of a in the program.

Volatile Qualifiers

If you are declaring a variable as:

Volatile int a=3;

means you can change the value of variable a whenever needed. Normally all variables are by default
volatile in C.
OPERATORS AND EXPRESSIONS
arithmetic operators

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

C Program to Verify Arithmetic Operator and Operation

#include <stdio.h>
int 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);
return(0);
}

Output :

Enter First Number : 10


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

Precedence Power : Which Operator have Highest Priority ?


If we consider all the arithmetic operators then we can say that Multiplication and division operator have
highest priority than addition and subtraction operator. Following table clearly explains the priority of all
arithmetic operators in C programming –

Priority Rank Operator Operator Associativity


Description
1 Multiplication * Left to Right
1 Division / Left to Right
1 Modulo % Left to Right
2 Addition + Left to Right
2 Subtraction - Left to Right

C‟s Relational Operators

 The relational operators are binary operators -- they work between two values
 The relational operators and their meanings:

== equal to
> greater than
>= greater than or equal
< less than
<= less than or equal
!= not equal to

Use of the Relational Operators

 A relational operator tests data values against one another


 You can only compare similar data types. (It makes no sense to compare a char to a float.)
 All relational operators return either a 1 (meaning true) or a 0 (false.)
 You will use the relational operators to test whether a condition is true or false and act accordingly.

Some Examples

Given the following C declarations:

int a =1, b = 2, c = 3, d = 1;
 a == d is true
 c > b is true
 c >= b is true
 a >= c is false
 a != d is false
 a <= d is true

Summary

 Be sure to use the double equal sign (= =) when testing for equality.
 If you use the assignment operator (=) by mistake, C will accept that assignment as valid and test the result
as false (zero) or true (non-zero).

One use of relational operators

commission = 0.10*sales + (sales > 1000.00) * 0.05 * (sales - 1000.00);


 In this example, a sales person is paid a commission of 10% on the first $1000 of sales and an extra 5% on
sales above $1000
 This code uses a "trick" to code what would normally be a few lines with one line
 Strive to maintain readability instead of getting the shortest code possible
 Example: Printing the results of relational operators.

Logical Operators

 You can combine relational operators using logical operators


 C‟s logical operators are:
 && (AND) returns true if and only if both operands are true
 || (OR) returns true if one or both operands are true
 ! (NOT) returns true if operand is false and false if operand is true

Precedence of operators

 (dept < 1 || dept > 5) is interpreted as ((dept < 1)||(dept > 5))

 The relational operators have higher precedence that the logical operators
It is usually best to include the extra parentheses

Using logical operators


if ( x == 0 || x == 1) {
do one thing
} else {
do another thing
}

 Important: don‟t say


if (x == 0 || 1)
 Don‟t overuse the ! operator
 Better to say (x >= y) than !(x < y)
 Use if for a simple decision, if-else if you need to determine one of two course of action, and logical
operators if you need to combine two or more relational operators.

Type conversion in C

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 type cast long to int. You can convert values
from one type to another explicitly using the cast operator as follows:

(type_name) expression

Consider the following example where the cast operator causes the division of one integer variable by
another to be performed as a floating-point operation:

#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}

When the above code is compiled and executed, it produces the following result:
Value of mean : 3.400000

It should be noted here that the cast operator has precedence over division, so the value of sum is first
converted to type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be specified
explicitly through the use of the cast operator. It is considered good programming practice to use the cast
operator whenever type conversions are necessary.

Increment and decrement operators

Increment and decrement operators are unary operators that add or subtract one from their operand,
respectively. They are commonly implemented in imperative programming languages. C-like languages
feature two versions (pre- and post-) of each operator with slightly different semantics.
In languages syntactically derived from B (including C and its various derivatives), the increment operator
is written as ++ and the decrement operator is written as --.
The increment operator increases the value of its operand by 1. The operand must have an arithmetic or
pointer data type, and must refer to a modifiable data object. Similarly, the decrement operator decreases the
value of its modifiable arithmetic operand by 1. Pointers values are increased (or decreased) by an amount
that makes them point to the next (or previous) element adjacent in memory.
In languages that support both versions of the operators, the pre-increment and pre-decrement operators
increment (or decrement) their operand by 1, and the value of the expression is the resulting incremented (or
decremented) value.
The following C code fragment illustrates the difference between the pre and post increment and
decrement operators:

int x;
int y;
// Increment operators
x = 1;
y = ++x; // x is now 2, y is also 2
y = x++; // x is now 3, y is 2
// Decrement operators
x = 3;
y = x--; // x is now 2, y is 3
y = --x; // x is now 1, y is also 1
The post-increment operator is commonly used with array subscripts. For example:
// Sum the elements of an array
float sum_elements(float arr[], int n)
{
float sum = 0.0;
int i = 0;
while (i < n)
sum += arr[i++]; // Post-increment of i, which steps
// through n elements of the array
return sum;
}
Assignment Operators

There are following assignment operators supported by C language:


Show Examples

Operator Description Example

= Simple assignment operator, C = A + B will assign value of


Assigns values from right side A + B into C
operands to left side operand

+= Add AND assignment C+=A is equivalent to C=C+A


operator, It adds right operand
to the left operand and assign
the result to left operand

-= Subtract AND assignment C-=A is equivalent to C=C-A


operator, It subtracts right
operand from the left operand
and assign the C result to left
operand.

*= Multiply AND assignment C*=A is equivalent to C=C*A


operator, It multiplies right
operand with the left operand
and assign the result to left
operand.

/= Divide AND assignment C/=A is equivalent to C=C/A


operator, It divides left
operand with the right operand
and assign the result C to left
operand.

%= Modulus AND assignment C%=A is equivalent to


operator, It takes modulus C=C%A.
using two operands and assign
the result to left operand

The Conditional Operator in C

The conditional operator in C is also known as ternary operator. It is called ternary operator
because it takes three arguments. The conditional operator evaluates an expression returning a value
if that expression is true and different one if the expression is evaluated as false.
condition ? result1 : result2;
10==5 ? 11: 12; // returns 12, since 10 not equal to 5.
10!=5 ? 4 : 3; // returns 4, since 10 not equal to 5.
12>8 ? a : b; // returns the value of a, since 12 is greater than 8.
/*Conditional operator*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, b = 11;
int c;
c = (a < b)? a : b;
printf(“%d”, c);
}

Precedence and order of evaluation in c

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* Right to left
& sizeof
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

Example
Try the following example to understand the operator precedence available in C programming language:
#include <stdio.h>
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
When you compile and execute the above program it produces the following result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

Expressions

An expression in a programming language is a combination of explicit values, constants, variables,


operators, and functions that are interpreted according to the particular rules of precedence and of
association for a particular programming language, which computes and then produces (returns, in a
stateful environment) another value. This process, like for mathematical expressions, is called evaluation.
The value can be of various types, such as numerical, string, and logical.
For example, 2+3 is an arithmetic and programming expression which evaluates to 5. A variable is an
expression because it denotes a value in memory, so y+6 is an expression. An example of a relational
expression is 4≠4, which evaluates to false.
In C and most C-derived languages, a call to a function with a void return type is a valid expression,
of type void. Values of type void cannot be used, so the value of such an expression is always thrown
away.

C - Input & Output

When we are saying Input that means to feed some data into program. This can be given in the form
of file or from command line. C programming language provides a set of built-in functions to read given
input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file. C
programming language provides a set of built-in functions to output the data on the computer screen as
well as you can save that data in text or binary files.
The scanf() and printf() functions

The int scanf(const char *format, ...) function reads input from the standard input stream stdin and
scans that input according to format provided.
The int printf(const char *format, ...) function writes output to the standard output stream stdout
and produces output according to a format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read
strings, integer, character or float respectively. There are many other formatting options available which
can be used based on requirements. For a complete detail you can refer to a man page for these function.
For now let us proceed with a simple example which makes things clear:

#include <stdio.h>
int main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
return 0;
}

When the above code is compiled and executed, it waits for you to input some text when you enter a
text and press enter then program proceeds and reads the input and displays it as follows:
$./a.out
Enter a value : seven 7
You entered: seven 7

Here, it should be noted that scanf() expect input in the same format as you provided %s and %d,
which means you have to provide valid input like "string integer", if you provide "string string" or
"integer integer" then it will be assumed as wrong input. Second, while reading a string scanf() stops
reading as soon as it encounters a space so "this is test" are three strings for scanf().

C provides two sytles of flow control:


· Branching
· Looping
Branching is deciding what actions to take and looping is deciding how many times to take a
certain action.

BRANCHING:

Branching is so called because the program chooses to follow one branch or another.
if statement
This is the most simple form of the branching statements.
It takes an expression in parenthesis and an statement or block of statements. if the expression
is true then the statement or block of statements gets executed otherwise these statements are
skipped.
NOTE: Expression will be assumed to be true if its evaulated values is non-zero.
if statements take the following form:

SYNTAX

if (expression)
statement;
or
if (expression)
{
Block of statements;
}

Flow Chart of Simple if

Meaning of If Statement :
o It Checks whether the given Expression is Boolean or not !!
o If Expression is True Then it executes the statement otherwise jumps to
next_instruction

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");

Program flow of If Statement :


If-else Statement in C Programming
We can use if-else statement in c programming so that we can check any condition
and depending on the outcome of the condition we can follow appropriate path.
We have true path as well as false path.
Syntax :

if(expression)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}
next_statement;

Explanation :
· If expression is True then Statement1 and Statement2 are executed
· Otherwise Statement3 and Statement4 are executed.

Sample Program on if-else Statement :

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

Output :
Student is Pass
Flowchart : If Else Statement

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");
}

Consider Example 2 with Explanation :


More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;
if(num1 == 20 && num2 == 40)
{
printf("True Block");
}
Opening and Closing Braces are required only when “Code” after if statement
occupies multiple lines. Code will be executed if condition statement is True. Non-
Zero Number Inside if means “TRUE Condition”

If-Else Statement :
if(conditional)
{
//True code
}
else
{
//False code
}

Note :
Consider Following Example -
int num = 20;
if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
1. If part Executed if Condition Statement is True.
if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True.
2. Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}

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


int num1 = 20;
int num2 = 40;
if(num1 == 20 && num2 == 40)
{
printf("True Block");
}
4. Opening and Closing Braces are required only when “Code” after if statement
occupies multiple lines.
5. Code will be executed if condition statement is True.
6. Non-Zero Number Inside if means “TRUE Condition”

Program Flow of If-Else Statement :

Else if Ladder :
Suppose we need to specify multiple conditions then we need to use multiple if
statements like this –

void main ( )
{
int num = 10 ;
if ( num > 0 )
printf ("\n Number is Positive");
if ( num < 0 )
printf ("\n Number is Negative");
if ( num == 0 )
printf ("\n Number is Zero");
}
which is not a right or feasible way to write program. Instead of this above syntax
we use if-else-if statement.

Consider the Following Program –


void main ( )
{
int num = 10 ;
if ( num > 0 )
printf ("\n Number is Positive");
else if ( num < 0 )
printf ("\n Number is Negative");
else
printf ("\n Number is Zero");
}

Explanation :
In the above program firstly condition is tested i.e number is checked with zero. If
it is greater than zero then only first if statement will be executed and after the
execution of if statement control will be outside the complete if-else statement.
else if ( num < 0 )
printf ("\n Number is Negative");
Suppose in first if condition is false then the second condition will be tested i.e if
number is not positive then and then only it is tested for the negative.
else
printf ("\n Number is Zero");
and if number is neither positive nor negative then it will be considered as zero.
Compound If Statement in C Programming :

void main ( )
{
int num = 10 ;
if(num > 0)
{
printf ("\nNumber is Positive");
printf ("\nThis is The Example of Compound Statement");
}
}

Output of Program :
Number is Positive
This is The Example of Compound Statement
Explanation of Compound If Statement :

In C Programming, Any block of the code is written or embedded inside the pair of
the curly braces. If condition specified inside the „if block‟ is true then code block
written inside the pair of curly braces will be executed.
printf ("\nNumber is Positive");
printf ("\nThis is The Example of Compound Statement");

Why we should use Switch Case ?

1. One of the classic problem encountered in nested if-else / else-if ladder is


called problem of Confusion.
2. It occurs when no matching else is available for if .
3. As the number of alternatives increases the Complexity of program
increases drastically.
4. To overcome this , C Provide a multi-way decision statement called „Switch
Statement‟

See how difficult is this scenario ?

if(Condition 1)
Statement 1
else
{
Statement 2
if(condition 2)
{
if(condition 3)
statement 3
else
if(condition 4)
{
statement 4
}
}
else
{
statement 5
}
}
First Look of Switch Case
switch(expression)
{
case value1 :
body1
break;
case value2 :
body2
break;
case value3 :
body3
break;
default :
default-body
break;
}
next-statement;

Flow Diagram

*Steps are Shown in Circles.


How it works ?
· Switch case checks the value of expression/variable against the list of case
values and when the match is found , the block of statement associated with
that case is executed
· Expression should be Integer Expression / Character
· Break statement takes control out of the case.
· Break Statement is Optional.
#include<stdio.h>
void main()
{
int roll = 3 ;
switch ( roll )
{
case 1: printf ( " I am Pankaj ");
break;
case 2: printf ( " I am Nikhil ");
break;
case 3: printf ( " I am John ");
break;
default : printf ( "No student found");
break;
}
}
explained earlier -
1 3 is assigned to integer variable „roll„
2. On line 5 switch case decides – “We have to execute block of code specified
in 3rd case“.
3. Switch Case executes code from top to bottom.
4. It will now enter into first Case [i.e case 1:]
5. It will validate Case number with variable Roll. If no match found then it
will jump to Next Case..
6. When it finds matching case it will execute block of code specified in that
case.

See how Switch Case works using Graphical Picture


Rules of Using Switch Case in C Programming

1. Case Label must be unique


2. Case Labels must ends with Colon
3. Case labels must have constants / constant expression
4. Case label must be of integral Type ( Integer,Character)
5. Case label should not be „floating point number „
6. Switch case should have at most one default label
7. Default label is Optional
8. Default can be placed anywhere in the switch
9. Break Statement takes control out of the switch
10.Two or more cases may share one break statement
11.Nesting ( switch within switch ) is allowed.
12.Relational Operators are not allowed in Switch Statement.
13.Macro Identifier are allowed as Switch Case Label.
14.Const Variable is allowed in switch Case Statement.
15.Empty Switch case is allowed.

Syntax of Switch Case :


switch ( expression )
{
case label1 :
body1
break;
case label2 :
body2
break;
case label3 :
body3
break;
default :
default-body
break;
}
next-statement;
Rule 1 : Case Label must be unique
int id = 3 ;
switch(id)
{
case 1:
printf("C Programming Language");
break;
case 2:
printf("C++ Programming Language");
break;
case 2:
printf("Web Technology");
break;
default :
printf("No student found");
break;
}

Rule 2 : Case Labels must ends with Colon


case 1 :
printf("C Programming Language");
break;

Rule 3 : Case labels must have constants / constant expression


case 1+1:
case 'A':
case 67:
these are allowed examples of switch case labels , however variables are not
allowed in switch case labels.
case var :
case num1 :
case n1+n2 :

Rule 4 : Case label must be of integral Type (Integer,Character) whereas


Case label should not be „floating point number „
case 10:
case 20+20:
case 'A':
case 'a':
these are allowed examples and following are illegal examples -
case 10.12:
case 7.5:

Rule 5 : Switch case should have at most one default label


switch(roll)
{
case 1:
printf("C Programming Language");
break;
case 2:
printf("C++ Programming Language");
break;
case 2:
printf("Web Technology");
break;
default :
printf("Default Version 1");
break;
default :
printf("Default Version 2");
break;
}
It violets first rule.

Rule 6 : Default label is Optional


switch(roll)
{
case 1 :
printf("C Programming Language");
break;
case 2 :
printf("C++ Programming Language");
break;
case 2 :
printf("Web Technology");
break;
}
default statement is optional. It can be neglected.

Rule 7 : Default can be placed anywhere in the switch


switch(roll)
{
case 1 :
printf("C Programming Language");
break;
default:
printf("No Student Found");
break;
case 2 :
printf("C++ Programming Language");
break;
case 2 :
printf("Web Technology");
break;
}

Rule 8 : Break Statement takes control out of the switch


Rule 9 : Two or more cases may share one break statement
switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
break;
case 'b':
case 'B':
printf("Alphabet B");
break;
}

Rule 10 : Nesting ( switch within switch ) is allowed


switch(alpha)
{
case 'a':
case 'A':
printf("Alphabet A");
break;
case 'b':
case 'B':
switch(alpha)
{
}
break;
}
nesting of switch case is allowed in C.

Rule 11 : Relational Operators are not allowed in Switch


Statement.
switch(num)
{
case >15:
printf("Number > 15");
break;
case =15:
printf("Number = 15");
break;
case <15:
printf("Number < 15");
break;
}
relational operators are not allowed as switch label.

Rule 12 : Macro Identifier are allowed as Switch Case Label.


#define MAX 2
switch(num)
{
case MAX:
printf("Number = 2");
break;
}
as preprocessor will replace occurrence of MAX by constant value i.e 2 therefor it
is allowed.

Rule 13 : Const Variable is allowed in switch Case Statement.


int const var = 2;
switch(num)
{
case var:
printf("Number = 2");
break;
}

LOOPING
Loops provide a way to repeat commands and control how many times they are repeated. C
provides a number of looping way.
Loops cause program to execute the certain block of code repeatedly until test condition is
false. Loops are used in performing repetitive task in programming. Consider these scenarios:
o You want to execute some code/s 100 times.
o You want to execute some code/s certain number of times depending upon input
from user.
To Perform any looping we need to consider 3 parameters
1. Initialization
2. Condition
3. Update
Initialization means what should be the starting point of looping
condition means till where i need to loop the statements
update means what should be the incremental steps for loop
Looping can be broadly classified in to 2 categories
· Pre test Loop / Entry controlled loop : here before performing looping
test for the validity of condition if its valid then perform looping of
statements.
Ex While (); and for( ); loops
· Post test Loop / Exit controlled loop: Here first execute the body of
loop for 1st time and at the last test for the validity of condition, if
condition is valid then perform looping of statements.
Ex : do while ();
In c programming we have 3 types of Loops
1. while loop
2. for loop
3. do while loop

While loop
Syntax of while loop
while (test expression) {
statement/s to be executed.
}
The while loop checks whether the test expression is true or not. If it is true, code/s inside
the body of while loop is executed,that is, code/s inside the braces { } are executed. Then
again the test expression is checked whether test expression is true or not. This process
continues until the test expression becomes false.

Flow chart of while

of while loop
Write a C program to find the factorial of a number, where the number is entered by
user. (Hints: factorial of n = 1*2*3*...*n
/*C program to demonstrate the working of while loop*/
#include <stdio.h>
int main(){
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0){ /* while loop continues util test condition
number>0 is true */
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}

Output
Enter a number.
5
Factorial=120

for loop
for Loop Syntax
for(initialization statement; test expression; update statement)
{
code/s to be executed;
}
How for loop works in C programming?
The initialization statement is executed only once at the beginning of the for loop. Then the
test expression is checked by the program. If the test expression is false, for loop is
terminated. But if test expression is true then the code/s inside body of for loop is executed
and then update expression is updated. This process repeats until test expression is false.
This flowchart describes the working of for loop in C programming.
or loop example
Write a program to find the sum of first n natural numbers where n is entered by user.
Note: 1,2,3... are called natural numbers.
#include <stdio.h>
int main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter the value of n.
19
Sum=190
In this program, the user is asked to enter the value of n. Suppose you entered 19 then, count
is initialized to 1 at first. Then, the test expression in the for loop,i.e., (count<= n)
becomes true. So, the code in the body of for loop is executed which makes sum to 1. Then,
the expression ++count is executed and again the test expression is checked, which becomes
true. Again, the body of for loop is executed which makes sum to 3 and this process
continues. When count is 20, the test condition becomes false and the for loop is terminated.
Note: Initial, test and update expressions are separated by semicolon(;).

do while loop
Syntax of do...while loops
do {
some code/s;
}
while (test expression);
At first codes inside body of do is executed. Then, the test expression is checked. If it is true,
code/s inside body of do are executed again and the process continues until test expression
becomes false(zero).
Notice, there is semicolon in the end of while (); in do...while loop.
Flowchart of do while loop

Example of do...while loop


Write a C program to add all the numbers entered by a user until user enters 0.
/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
int main(){
int sum=0,num;
do /* Codes inside the body of do...while loops are at least
executed once. */
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}
Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
In this C program, user is asked a number and it is added with sum. Then, only the test
condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to
0, the body of do...while loop is again executed until num equals to zero.

Nested Loops in C
C programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.

Syntax:
The syntax for a nested for loop statement in C is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows:
do
{
statement(s);
{
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type of
loop. For example, a for loop can be inside a while loop or vice versa.

Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<100; i++) {
for(j=2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime

89 is prime
97 is prime

JUMP STATEMENTS
The other statements related to Looping are unconditional jumps
Jump statements are classified in to following
1. break;
2. continue;
3. return
4. go to
There are two statements built in C programming, break; and continue; to alter the normal
flow of a program. Loops perform a set of repetitive task until text expression becomes false
but it is sometimes desirable to skip some statement/s inside loop or terminate the loop
immediately without checking the test expression. In such cases, break and continue
statements are used. The break; statement is also used in switch statement to exit switch
statement.
break Statement
In C programming, break is used in terminating the loop immediately after it is encountered.
The break statement is used with conditional if statement.
Syntax of break statement
break;
The break statement can be used in terminating all three loops for, while and do...while loops.
Example of break statement
Write a C program to find average of maximum of n positive numbers entered by user.
But, if the input is negative, display the average(excluding the average of negative input)
and end the program.
/* C program to demonstrate the working of break statement by
terminating a
loop, if user inputs negative number*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Output
Maximum no. of inputs
4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07
In this program, when the user inputs number less than zero, the loop is terminated using
break statement with executing the statement below it i.e., without executing sum=sum+num.
In C, break statements are also used in switch...case statement. You will study it in C
switch...case statement chapter.
continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statements are used.
Syntax of continue Statement
continue;
Just like break, continue is also used with conditional if statement.
For better understanding of how continue statements works in C programming.
Analyze the figure below which bypasses some code/s inside loops using continue
statement.

Example of continue statement


Write a C program to find the product of 4 integers entered by a user. If user enters 0
skip it.
//program to demonstrate the working of continue statement in C
programming
# include <stdio.h>
int main(){
int i,num,product;
for(i=1,product=1;i<=4;++i){
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
c o ntinue; / *In this program, when num equals to zero, it
skips the statement product*=num and continue the loop. */
product*=num;
}
printf("product=%d",product);
return 0;
}
Output
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30

go to statements
In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
Syntax of goto statement
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement,
the control of the program will jump to the label: and executes the code below it.

Example of goto statement


/* C program to demonstrate the working of goto statement. */
/* This program calculates the average of numbers entered by
user. */
/* If user enters negative number, it ignores that number and
calculates the average of number entered before it.*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program moves to label jump
*/
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}

Output
Maximum no. of inputs: 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average: 7.07
Though goto statement is included in ANSI standard of C, use of goto statement should be
reduced as much as possible in a program.
Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto
statement makes the logic of the program complex and tangled. In modern programming,
goto statement is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue
statements. In fact, any program in C programming can be perfectly written without the use
of goto statement. All programmer should try to avoid goto statement as possible as they can.

return statements
return statements in c are used to return some value to the main program.
int main()
{
int a,b,c;
------ - - - -
--
return 0;
}
Here in the program return 0 indicates that program has successfully executed. where as
return 1 indicates program has exited due to error.
Here return 1 works same as exit(0).

You might also like