You are on page 1of 51

UNIT – I

Introduction - Algorithms, Pseudo code, flow charts, Introduction to C Language - Identifiers, Basic
data types, Variables, Constants, Input / Output, Operators. Expressions, Precedence and Associativity,
Type conversions, Simple C Programming examples. Selection Statements – if and switch statements,
Repetition statements – while, for, do-while statements, Loop examples, other statements related to
looping – break, continue.

INTRODUCTION TO COMPUTER
A Computer is an electronic device which performs operations such as accepts data as an input, store the
data, manipulate or process the data and produce the result as an output.

Von Neumann architecture


 The modern computers are based on a concept introduced by John Von Neumann.
 Fetch-Decode-Execute
o Fetching instructions from main memory to registers through operating system.
o Control unit decodes the instructions and gives to ALU to operate.
o These instructions are executed.

COMPUTER LANGUAGES:
To write a program (tells what to do) for a computer, we must use a computer language. Over the years
computer languages have evolved from machine languages to natural languages. The following is the
summary of computer languages
1940’s -- Machine Languages
1950’s -- Symbolic Languages
1960’s -- High Level Languages
1. Machine Language:
In the earliest days of computers, the only programming languages available were machine languages.
Each computer has its own machine language which is made of streams of 0’s and 1’s. The instructions
in machine language must be in streams of 0’s and 1’s. This is also referred as binary digits. These are
so named as the machine can directly understood the programs
Advantages:
1) High speed execution
2) The computer can understood instructions immediately
3) No translation is needed.
Disadvantages:
1) Machine dependent
2) Programming is very difficult
3) Difficult to understand
4) Difficult to write bug free programs
5) Difficult to isolate an error
Example: Addition of two numbers
2 0010
+ 3 0011
--- ---------------
5 0101
--- ---------------

2. Symbolic Languages (or) Assembly Language:


In the early 1950‟s Admiral Grace Hopper, a mathematician and naval officer, developed the concept of
a special computer program that would convert programs into machine language. These early
programming languages simply mirrored the machine languages using symbols or mnemonics to
represent the various language instructions. These languages were known as symbolic languages.
Because a computer does not understand symbolic language it must be translated into the machine
language. A special program called an Assembler translates symbolic code into the machine language.
Hence they are called as Assembly language.
Advantages:
1) Easy to understand and use
2) Easy to modify and isolate error
3) High efficiency
4) More control on hardware
Disadvantages:
1) Machine Dependent Language
2) Requires translator
3) Difficult to learn and write programs
4) Slow development time
5) Less efficient
Example:
PUSH 2, A
PUSH 3, B
ADD A, B
PRINT C

3. HIGH-LEVEL Languages:
The symbolic languages greatly improved programming efficiency they still required programmers to
concentrate on the hardware that they were using working with symbolic languages was also very
tedious because each machine instruction had to be individually coded. The desire to improve
programmer efficiency and to change the focus from the computer to the problems being solved led to
the development of high-level languages.
High-level languages are portable to many different computers allowing the programmer to concentrate
on the application problem at hand rather than the intricacies of the computer.
C A systems implementation Language
C++ C with object oriented enhancements
JAVA Object oriented language for internet and general applications using basic C syntax
Advantages:
1) Easy to write and understand
2) Easy to isolate an error
3) Machine independent language
4) Easy to maintain
5) Better readability
6) Low Development cost
7) Easier to document
8) Portable
Disadvantages:
1) Needs translator
2) Requires high execution time
3) Poor control on hardware
4) Less efficient
Example: C language
#include<stdio.h>
void main()
{
int a,b,c;
scanf("%d%d%",&a,&b);
c=a+b;
printf("%d",c);
}

LANGUAGE TRANSLATORS
These are the programs which are used for converting the programs in one language into machine
language instructions, so that they can be executed by the computer.
1) Compiler: It is a program which is used to convert the high level language programs into machine
language
2) Assembler: It is a program which is used to convert the assembly level language programs into
machine language
3) Interpreter: It is a program, it takes one statement of a high level language program, translates it into
machine language instruction and then immediately executes the resulting machine language instruction
and so on.

CREATING, COMPILING AND RUNNING PROGRAM


The process of converting a C program into machine Language is presented in a straightforward, linear
fashion but we should recognize that these steps are repeated many times during development to correct
errors and make improvements to the code.
The following are the four steps in this process
1) Writing and editing the program
2) Compiling the program
3) Linking the program with the required modules
4) Executing the program
Writing and Editing Programs
The software used to write programs is known as a text editor. A text editor helps us enter, change and
store character data. Once we write the program in the text editor we save it using a filename stored with
an extension of .C. We refer this file as source code.
Compiling the Programs
The code in a source file stored on the disk must be translated into machine language. This is the job of
the compiler. The Compiler is a computer program that translates the source code written in a high- level
language into the corresponding object code of the low-level language. This translation process is called
compilation. The entire high level program is converted into the executable machine code file. The
Compiler which executes C programs is called as C Compiler. Example Turbo C, Borland C, GC etc.,
Linking the Programs
The Linker assembles all functions, the program’s functions and system’s functions into one
executable program.
Executing the Programs
To execute a program we use an operating system command, such as run, to load the program into
primary memory and execute it. Getting the program into memory is the function of an operating system
program known as the loader. It locates the executable program and reads it into memory. When
everything is loaded the program takes control and it begins execution.
INTRODUCTION TO ALGORITHMS
Algorithm
Algorithm is a systematic logical approach which is a well-defined, step-by-step procedure that allows
a computer to solve a problem. This is the first step to solve a mathematical or computer problem. A
sequence of activities to be processed for getting desired output from a given input. A
computer program can be viewed as an elaborate algorithm.
While writing algorithms we will use following symbol for different operations:
o ‘+’ for Addition
o ‘-’ for Subtraction
o ‘*’ for Multiplication
o ‘/’ for Division and
o ‘←’ for assignment
The properties of an algorithm are:
1. Input: Algorithm should be accepting 0 or more inputs supplied externally.
2. Output: Algorithm should be generating at least one output.
3. Definiteness: Each step of an algorithm must be precisely defined. Meaning the step should perform
a clearly defined task without much complication.
4. Finiteness: An algorithm must always terminate after a finite number of steps.
5. Effectiveness: The efficiency of the steps and the accuracy of the output determine the effectiveness
of the algorithm.
6. Correctness: Each step of the algorithm must generate a correct output.
Examples:
1. Algorithm to make a cup of tea
Step 1: Start
Step 2: Place the fresh water in a saucepan or a kettle.
Step 3: Boil the water to match your style of tea.
Step 4: Put the black tea leaves in that pot
Step 5: After that add some milk into that pot.
Step 6: Add some sugar.
Step 7: Boil for some time.
Step 8: Stop
And it is ready to serve.

2. Algorithm to add two numbers


Step 1: Start
Step 2: Read values num1 and num2.
Step 3: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 4: Write/ Display sum
Step 5: Stop.

3. Convert temperature Fahrenheit to Celsius


Step 1: Start
Step 2:Read Temperature in Fahrenheit F
Step 3: convert temperature to celsius
C← 5/9*(F-32)
Step 4: Print Temperature in Celsius: C
Step 5: Stop

4. Algorithm to find the largest among two different numbers


Step 1: Start
Step 2: Declare variables a and b.
Step 3: Read values of a and b.
Step 4(a): If a greater than b then
Write/ Display a is the largest number.
Step 4(b): Else
Write/ Display b is the largest number.
Step 5: Stop

5. Algorithm to find the sum of individual digits of a given positive integer


Step 1: start
Step 2: read a positive integer called num
Step 3: declare and initialize variables:
sum←0, dig←0
Step 4: repeat steps 4.1, 4.2, 4.3 until num greater than zero
4.1: dig ← num mod 10
4.2: sum ← sum + dig
4.3: num ← num/10
Step 5: write/ display sum
Step 6: stop

Pseudo code
Pseudo code is a simpler version of a programming code in plain English which uses short phrases to
write code for a program before it is implemented in a specific programming language. Pseudo code is
an informal way of writing a program. It is not exactly a computer program. It represents the algorithm
of the program in natural language and mathematical notations. Usually, there is no particular code
syntax to write a pseudo code. Therefore, there is no strict syntax as a usual programming language. It
uses simple English language.
Examples:
1. Pseudo code for addition of 2 numbers:
Begin
Declare num1,num2,Sum
WRITE “Please enter two numbers to add”
READ num1, num2
Sum = num1+num2
WRITE Sum
End

2. Pseudo code to convert temperature Fahrenheit to Celsius


Begin
Declare Fahrenheit, Celsius
Read Fahrenheit
Set Celsius = 5/9*(Fahrenheit -32)
Write Celsius
End

3. Pseudo Code to find the largest among two different numbers


Begin
Declare a, b
Read a and b
if a>b then
Write a is largest
else
Write b is largest
end if
End

4. Pseudo code to find the sum of individual digits of a given positive integer
Begin
Declare num and Set sum=0, dig=0
Read num
While num>0 then
dig = num % 10
sum = sum + dig
num = num/10
End while
Write sum
End

Flow chart
A flowchart is a schematic representation of an algorithm or the diagrammatic representation of way to
solve the given problem.
Flowcharts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals and
small circles. These symbols are connected by arrows called flow lines.
Flowcharts can be used to describe all sorts of processes: business, educational, personal and of course
algorithms.
So, flowcharts are often used as a program planning tool to visually organize step-by-step process of a
program.
The following are the most common symbols used in drawing flowcharts:

Examples:
1. Flow chart to find the sum of two numbers
2. Flow chart to convert temperature Fahrenheit to Celsius

3. Flow chart to find the largest among two different numbers


4. Flow chart to find the sum of individual digits of a given positive integer
INTRODUCTION TO C
History of C
C language was developed by Dennis Ritchie in the early 1970’s at Bell telephone laboratory of AT&T
(American Telephone & Telegraph), located in the U.S.A. It was developed to overcome the problems
of previous languages such as B, BCPL, etc. C is a general purpose, structured programming language.
The first standard for C was published by ANSI (American National Standards Institute). Initially, C
language was developed to be used in UNIX operating system. It inherits many features of previous
languages such as B and BCPL.

WHY WE LEARN C?
 C language is the most commonly used programming language.
 It is used for writing operating systems.
 UNIX was the first operating system written in C.
 Later Microsoft Windows, Mac OS X, and GNU/Linux were all written in C.
 Not only is C the language of operating systems, it is the precursor and inspiration for almost all of
the most popular high-level languages available today.
 In fact, Perl, PHP, Python and Ruby are all written in C.

FEATURES OF C LANGUAGE
1. Simple: C is a simple language in the sense that it provides a structured approach (to break a problem
into parts), the rich set of library functions, data types, etc.
2. Machine Independent or Portable: Unlike assembly language, c programs can be executed on
different machines with some machine specific changes. Therefore, C is a machine independent
language.
3. Mid-level programming language: Although, C is intended to do low-level programming. It is used
to develop system applications such as kernel, driver, etc. It also supports the features of a high-level
language. That is why it is known as mid-level language.
4. Structured programming language: C is a structured programming language in the sense that we
can break the program into parts using functions. So, it is easy to understand and modify. Functions also
provide code reusability.
5. Rich Library: C provides a lot of inbuilt functions that make the development fast.
6. Memory Management: It supports the feature of dynamic memory allocation. In C language, we can
free the allocated memory at any time by calling the free() function.
7. Speed: The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
8. Pointer: C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.
9. Recursion: In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.
10. Extensible: C language is extensible because it can easily adopt new features.

STRUCTURE OF A C-PROGRAM

A simple C program to print “Hello world”


#include<stdio.h>
void main()
{
printf("Hello, World! \n");
}
Output:
Hello, World!
DATA TYPES
Data type determines the type of data a variable will hold. C language has some predefined set of data
types to handle various kinds of data that we can use in our program.
• Primary data types:
– void: Has no values and no operations.
– Character (char): Used to store character value.
– Integer (int): Used to store whole numbers.
– Floating point (float, double): Used to store real numbers.
• Derived data types are
– array
– pointer
• User Defined Data types
– structure
– union
– enum
– typedef

Data type ranges and their format specifiers


Type Storage size Value range Format specifier

unsigned char 1 byte 0 to 255 %c

signed char 1 byte -128 to 127 %c

short int 2 bytes -32,768 to 32,767 %d

unsigned short int 2 bytes 0 to 65,535 %u

long int 4 bytes -2,147,483,648 to %ld


2,147,483,647

unsigned long int 4 bytes 0 to 4,294,967,295 %lu

float 4 bytes 3.4*E-38 to 3.4*E+38 %f

double 8 bytes 1.7*E-308 to 1.7*E+308 %lf

long double 10 bytes 3.4*E-4932 to 1.1*E+4932 %Lf

KEYWORDS
 Keywords are reserved words of the C language.
 There are 32 keywords in C. All the keywords are in small case.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
IDENTIFIERS
An Identifier is a sequence of letters and digits, but must start with a letter. Identifiers are case sensitive.
Identifiers specifies the names to the particular entity such as name of variables, functions etc.
Valid identifiers: Root, _getchar, __sin, x1, x2, x3, x_1, If
Invalid identifiers: 324, short, price$, My Name

VARIABLES
Variable indicates the name of the data value. We can store data in a memory space and name it, so that
it becomes easier to access memory space. The naming of an address is known as variable. Unlike
constant, variables are changeable; we can change value of a variable during execution of a program.
Rules to name a variable:
• The name of a variable can be composed of letters, digits, and the underscore character.
• Variable name must not start with a digit.
• Blank spaces are not allowed in variable name.
• Keywords are not allowed as variable name.
• C is case-sensitive, so it is suggested to keep the variable names in lower case.

Declaration of variables must be done before they are used in the program.
Syntax of variable declaration:
datatype variable;
 Single variable declaration:
Ex: int a;
 Multiple variables declaration of same data type
Ex: float b, c;

Initializing a variable means to provide it with a value.


Example 1:
int a;
a = 10;
Example 2:
int a=10;
CONSTANTS
It refers to fixed values that do not change during the execution of program. We have Numeric constants
(integer and float) and Character constants (single character and strings). A constant is a value or
variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc. There
are two ways to define constant in C:
• const keyword: The const keyword is used to define constant in C programming.
Ex: const float PI=3.14;
• #define preprocessor: The #define preprocessor is also used to define constant.

String Literals: A sequence of characters enclosed in double quotes as “…”. For example “13” is a
string literal and not number 13. ‘a’ and “a” are different.
Ex: “GfG”, “hello world” etc.,
White Spaces: Spaces, new lines, tabs. These are used to separate the adjacent identifiers, keywords and
constants.

INPUT & OUTPUT


• 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).
• The printf() function is used for output. It prints the given statement to the console.
• Syntax: printf("format string",argument_list);
• The format string can be %d (integer), %c (character), %s (string), %f (float) etc.
• The scanf() function is used for input. It reads the input data from the console.
• Syntax: scanf("format string",argument_list);

Example: C program to take input from user and print


#include <stdio.h> //preprocessor directive command
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
printf("You entered: %d", number);
return 0; // exit status
}
Output:
Enter a integer: 25
You entered: 25

ERROR
Error is an unexpected output. Error is an illegal operation which results in abnormal working of the
program. It is also known as bug. For the successful execution of the programs, it is necessary to remove
all types of errors.
Debugging: It is the process of finding and removing errors from the program.

Types of Error:
1. Syntax errors
• Reason: It occurs due to the violation of writing C syntax rules, such as missing statement
terminator(;), missing parenthesis({,}), misspelled Keyword.
• Detector: Compiler detects during compilation. It can easily specifies the location and type of error.
Easy to locate and remove them.
• Outcome: The program having syntax error cannot be compiled/translated.
Example: C program to illustrate syntax error
#include<stdio.h>
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}
Output: error: expected ';' before '}' token

2. Runtime errors
• Reason: Occurs due to performing an illegal operation. Such as, Number when divided by zero or
Accessing memory that is not available
• Detector: Computer detects errors at the time of running the program. These types of error are hard
to find as the compiler doesn’t point to the line at which the error occurs.
• Outcome: Running program is stopped or crashed and a diagnostic message is displayed on screen
causing that error
• Example: C program to illustrate run-time error
#include<stdio.h>
void main()
{
int n = 9, div = 0;
// wrong logic number is divided by 0,
// so this program abnormally terminates
div = n/0;
printf("resut = %d", div);
}
Output: warning: division by zero [-Wdiv-by-zero] div = n/0

3. Logical errors
• Reason: Occurs due to following a faulty algorithm. provide incorrect output but appears to be error
free
• Detector: Programmer find their errors by checking the whole program statement by statement.
Comparatively difficult to detect this error
• Outcome: Running program does not stop or crash but the wrong output is generated.
Example: Program to find modulus
#include<stdio.h>
int main()
{
int a=10,b=2;
int mod;
mod = a/b; // Logical Error. Correct statement “mod=a%b;”
return 0;
}
Output: 5
Expected 0, Output which you were expecting will not be shown.
OPERATORS IN C
• C operators are symbols that are used to perform mathematical or logical manipulations. The 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 programming language offers various types of operators having different functioning capabilities.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations.

Example: C program to find sum of 2 numbers


#include <stdio.h>
void main()
{
int i=3,j=7,k;
k=i+j;
printf("sum of two numbers is %d\n", k);
}
Output: sum of two numbers is 10
Assignment Operators
• Assign right hand side value (Rvalue) to the left hand side variable (Lvalue).
• The assignment operator is used in different variants along with arithmetic operators.
• Assignment operators applied to assign the result of an expression to a variable. C has a collection of
shorthand assignment operators.

Increment & Decrement Operators


• The increment and decrement operators are called as unary operators.
• Increment and Decrement Operators are useful operators generally used to minimize the calculation,
i.e. ++x and x++ means x=x+1 or --x and x−−means x=x-1.
• But there is a slight difference between ++ or −− written before or after the operand.
• pre-increment: first add one to the operand and then the result is assigned to the variable on the left.
Ex: ++x
• post-increment: first assigns the value to the variable on the left and then increment the operand. Ex:
x++
• pre-decrement: first substract one to the operand and then the result is assigned to the variable on the
left. Ex: --x
• post-decrement: first assigns the value to the variable on the left and then decrement the operand.
Ex: x--
Example: program to perform Pre-Increment and Pre-Decrement
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf(“++i = %d, --j = %d",++i,--j);
}
Output:
++i = 6, --j = 4

Example 2: program for Post-Increment or Post-Decrement


#include <stdio.h>
void main()
{
int i = 5,j=5;
printf("i++ = %d, j-- = %d\n",i++,j--);
printf(“i = %d, j = %d\n” ,i,j);
}
Output:
i++ = 5, j-- = 5
i = 6, j = 4

Relational Operators
• They are used to compare or check the relationship between two values.
• Every relational operator has two results TRUE or FALSE.
• Relational operators are used to define conditions and take decisions in a program.
Logical Operators
• The logical operators are used to combine multiple conditions into one condition.

exp-1 exp-2 exp-1 && exp-2 exp-1 || exp-2


non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0
exp-1 !exp-1
non-zero zero
zero non-zero

Conditional operator
• It is also called as ternary operator. This operator is used for decision making.
• Syntax: Condition? TRUE Part : FALSE Part ;
• In this operator,
– First it verifies a condition
– If the condition is TRUE the first option is performed,
– If the condition is FALSE the second option is performed.
Example: C program to find largest of 2 different numbers
#include<stdio.h>
main()
{
int i,j,large;
printf("Enter two numbers ");
scanf("%d%d",&i,&j);
large=(i>j)?i:j;
printf("Largest = %d",large);
}
Output:
Enter two numbers 25 36
Largest 36

Bitwise Operators
• This operator perform bit level operations.
• The operations are performed based on the binary values.
• For example: A = 25 (11001) and B = 20 (10100)
Special operators
1. sizeof operator: This operator is used to find the size of the memory (in bytes) allocated for a
variable. This operator is used with the following syntax...
Syntax: sizeof(variableName);
Example:
int A;
printf(“%d”, sizeof(A));
Output: 2
2. Comma operator (,): This operator is used to separate variables while they are declaring, separate the
expressions in function calls etc.
Example: float a=2.5,b;
3. Pointer operator (*): This operator is used to define pointer variables in c programming language.
Example: int *p;
4. Dot operator (.): This operator is used to access members of structure or union.
Example: printf(“%d”, emp.num);

The precedence and associativity of operators:


Operator precedence determines which operator is performed first in an expression with more than
one operator with different precedence.
Operators Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left.
EXPRESSION
• An expression is a collection of operators and operands that represents a specific value.
• operator is a symbol which performs tasks like arithmetic operations, logical operations and
conditional operations etc.,
• Operands are the values on which the operators perform the task.
• Here operand can be a direct value or variable or address of memory location.
• In C programming language, expression is evaluated based on the operator precedence and
associativity.
Expression Types in C
1. Infix Expression: The expression in which operator is used between operands is called as infix
expression.
Example: 10 + 4 * 3 / 2
The above expression is evaluated as
4 * 3 => 12
12 / 2 => 6
10 + 6 => 16
2. Postfix Expression: The expression in which operator is used after operands is called as postfix
expression.
Example: 4 5*8+
The above expression is evaluated as
4*5 =>20
20+8 =>2
3. Prefix Expression: The expression in which operator is used before operands is called as prefix
expression.
Example: + * 2 3/ 10 2
The above expression is evaluated as
2*3 => 6
10/2 =>5
6+5 =>11

TYPE CONVERSION
• Type Conversion: Conversion from one data type to another.
• Two ways of type conversion are:
 Implicit Type Conversion
 Explicit Type Conversion

Implicit Type conversion


• It is also known as ‘automatic type conversion’.
• Done by the compiler on its own, without any external trigger from the user.
• All the variables are upgraded to the data type of the variable with largest data type. This is also
known as type promotion.
• bool -> char-> short int-> int -> unsigned int-> long-> unsigned long-> float -> double-> long
double
Example:
#include<stdio.h>
void main()
{
char c='a';
int x=5;
x = x+c; //char is converted to int
float y=6.45;
y = y+x; //int is converted to float
printf("x=%d\n",x);
printf("y=%.2f\n",y);
}
Output:
x=102
y=108.45

Explicit Type Conversion


• This process is also called type casting and is user defined.
• Here the user can type cast the result to make it of a particular data type.
• Syntax: (type) expression
• Type indicated the data type to which the final result is converted.
Example:
#include<stdio.h>
void main()
{
int a=8;
float b=a/3;
printf("8/3 = %f\n",b);
b=(float)a/3;
printf("8/3 = %.2f",b);
}
Output:
8/3 = 2.00000000
8/3 = 2.67

Sample C programs:
Program 1: C program to swap 2 values with 3rd variable
#include<stdio.h>
void main()
{
int a,b,temp;
printf("Enter 2 values:");
scanf("%d %d",&a,&b);
printf("Before swapping:\n");
printf("a=%d and b=%d\n",a,b);
temp=a;
a=b;
b=temp;
printf("After swapping:\n");
printf("a=%d and b=%d\n",a,b);
}
Output:
Program 2: C program to swap 2 values without 3rd variable
#include<stdio.h>
void main()
{
int a,b,temp;
printf("Enter 2 values:");
scanf("%d %d",&a,&b);
printf("Before swapping:\n");
printf("a=%d and b=%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After swapping:\n");
printf("a=%d and b=%d\n",a,b);
}
Output:

Program 3: C program to swap 2 values with bitwise operator


#include<stdio.h>
int main()
{
int a,b,temp;
printf("Enter 2 values:");
scanf("%d %d",&a,&b);
printf("Before swapping:\n");
printf("a=%d and b=%d\n",a,b);
a=a^b;
b=a^b;
a=a^b;
printf("After swapping:\n");
printf("a=%d and b=%d\n",a,b);
}
Output:

Program 4: C program to convert temperature from Celsius to Fahrenheit


#include <stdio.h>
int main()
{
float celi, far;
printf("Write the temperature in Celcius: ");
scanf("%f", &celi);
far = (celi * 9 / 5) + 32;
printf("The temperature in Farenheit is: %f", far);
return 0;
}

Program 5: C program to calculate simple interest & compound interest


#include <stdio.h>
#include <math.h>
int main()
{
float p, r, t, ci, si;
printf("Enter principle value: ");
scanf("%f", &p);
printf("Enter rate of interest: ");
scanf("%f", &r);
printf("Enter time period: ");
scanf("%f", &t);
si = (p*r*t)/100;
printf("The simple interest is %.2f\n", si);
ci = p * pow(1 + r/100, t) - p;
printf("Compound interest is %.2f\n", ci);
return 0;
}

Selection Statements

if statement

The if statement checks whether the text expression inside parenthesis () is true or not. If the
test expression is true, statement/s inside the body of if statement is executed but if test is false,
statement/s inside body of if is ignored.

Syntax is,

if (test_expression)
{
Staements to be executed if test expression is true;
}
Flow of if statement

Example :
Program to check whether the given number is lessthan 0 or not

#include<stdio..h>
#include<conio.h>
void main()
{

int num;;
printf(“\n enter a number to check : ”);
scanf(“%d”,&num);
if(num<0) /* checking whether number is less than 0 or not. */
{
printf(“\n Number =%d”,num);
}
/*If test condition is true, statement above will be executed, otherwise it
will not be executed */
printf(“The if statement in C programing is easy “);
getch();
}

Output 1
Enter a number to check.
-2
Number = -2

The if statement in C programming is easy.


When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2 is displayed
in the screen.

Output 2
Enter a number to check.
5

The if statement in C programming is easy.


When the user enters 5 then, the test expression (num<0) becomes false. So, the statement/s inside
body of if is skipped and only the statement below it is executed.

if – else statement
The if...else statement is used if the programmer wants to execute some statement/s
when the test expression is true and execute some other statement/s if the test expression is
false.

Syntax is,

if (test expression)
{
statements to be executed if test expression is true;
}
else
{
statements to be executed if test expression is false;
}
Flow chart of if-else statement

Example:

Write a C program to check whether a number entered by user is even or odd


#include<stdio.h>
Int main(){
int num;
printf("Enter a number you want to check.\n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return0;
}
Output 1

Enter a number you want to check. 25


25 is odd.
Output 2
Enter a number you want to
check. 2
2 is even.

Nested if –else statement (if – else if )


The nested if...else statement is used when program requires more than one test expression.
Syntax is
if (test expression1)
{
statement/s to be executed if test expression1 is true;
}
else if(test expression2)
{
statement/s to be executed if test expression1 is false and 2 istrue;
}
else if (test expression 3)
{
statement/s to be executed if text expression1 and 2 are false and 3 is true;
}
.
.
.
else
{
statements to be executed if all test expressions are false;
}

How nested if...else works?


The nested if...else statement has more than one test expression. If the first test expression is
true, it executes the code inside the braces{ } just below it. But if the first test expression is
false, it checks the second test expression. If the second test expression is true, it executes the
statement/s inside the braces{ } just below it. This process continues. If all the test
expression are false, code/s inside else is executed and the control of program jumps below the
nested if...else

The ANSI standard specifies that 15 levels of nesting may be continued.


Example:
Write a C program to relate two integers entered by user using = or > or < sign.
#include<stdio.h>
int main(){
int numb1, numb2;
printf("Enter two integers to check\n");
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d = %d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d > %d",numb1,numb2);
else
printf("Result: %d > %d",numb2,numb1); return0;
}

Output 1
Enter two integers to check. 5
3
Result: 5 > 3

Output 2

Enter two integers to check.


-4
-4
Result: -4 = -4

switch Statement
Decision making are needed when, the program encounters the situation to choose a
particular statement among many statements. If a programmer has to choose one block of
statement among many alternatives, nested if...else can be used but, this makes programming
logic complex. This type of problem can be handled in C programming using switch
statement.
Syntax of switch statement is,
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;

The value of n is either an integer or a character in above syntax. If the value of n


matches constant in case, the relevant codes are executed and control moves out of the
switch statement. If the ndoesn't matches any of the constant in case, then the default codes are
executed and control moves out of switch statement.
Example:
Write a program that asks user an arithmetic operator('+','-','*' or '/') and twooperands and
perform the corresponding calculation on the operands.

/* C program to demonstrate the working of switch...case statement */


/* C Program to create a simple calculator for addition, subtraction, multiplication and division */

# include <stdio.h>

int main(){
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o)
{
case'+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case'-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case'*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case'/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return0;
}

Output
Enter operator either + or - or * or /
*
Enter two operands: 2.3 4.5
2.3 * 4.5 = 10.3
The break statement at the end of each case cause switch statement to exit. Ifbreak statement is
not used, all statements below that case statement are also executed.

Repetitive statements (Iterative statements)

There may be a situation, when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.Programming languages provide various control structures that
allow for more complicated execution paths.A loop statement or repetitive statement allows us to
execute a statement or group of statements multiple times.

C programming language provides the following types of loop to handle looping requirements.
Click the following links to check their detail.

Loop Type Description

while loop Repeats a statement or group of statements while a given


condition is true. It tests the condition before executing the
loop body.

for loop Execute a sequence of statements multiple times and


abbreviates the code that manages the loop variable.

do...while loop Like a while statement, except that it tests the condition at the
end of the loop body

nested loops You can use one or more loop inside any another while, for or
do..while loop.

while loop
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.
Syntax of while loop,
while (test expression)
{
statement/s to be executed.
}
Flow of while loop,

Example :

Write a C program to find the factorial of a number, where the number is enteredby 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);
return0;
}

Output
Enter a number. 5
Factorial=120

do-while loop
In C, do...while loop is very similar to while loop. Only difference between thesetwo
loops is that, in while loops, test expression is checked at first but, in do...while loop code is
executed at first then the condition is checked. So, the code are exec uted atleast once in
do...while loops.
Syntax of do-while loop is,
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.

Example

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

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.

for loop

For loop is also used for the similar purpose like while & do-while. It has three statements.
(i) initialization statements (ii) condition statements (iii) update statements.

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.

Syntax of for loop is,

for(initialization statement; test expression; update statement)


{
code/s to be executed;
}
Flow of for loop is,

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

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(;).

break, continue and goto statements

break

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 is,

break;

The break statement can be used in terminating all three loops for, while and do...while loops.
The figure below explains the working of break statement in all three type of loops.
Example:

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, ifuser
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.0sum=sum+num;
}
average=sum/(i-1);

printf("Average=%.2f",average);
return0;
}

Output
Maximum no. of inputs4
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 is,

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 by passes some code/s inside loops using continue statement.
Example:
Write a C program to find the product of 4 integers entered by a user. If user enters0 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)
continue;
/ *In this program, when num equals to zero, it skips the statement product*=num
and continue the loop. */
product*=num;
}
printf("product=%d",product);
return0;
}

Output

Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30

goto statement
goto label;
.............
.............
.............
label:
statement;

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 is,

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
/* 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 andcalculates
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.

You might also like