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

UNIT 1 Notes

Uploaded by

kasithangamcse92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

UNIT 1 Notes

Uploaded by

kasithangamcse92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

UNIT I BASICS OF C PROGRAMMING

Introduction to Problem Solving: Algorithm, Flowchart, Pseudocode. Programming Basics:


Applications of C Language-Structure of C program -Identifiers-Data Types – Variables-
Constants – Keywords – Operators – Input/output statements, Decision making statements -
Looping statements - Expressions-Precedence and Associativity – Expressions- Evaluation-
Type Conversions

INTRODUCTION TO PROGRAMMING PARADIGMS:


Programming paradigms are a way to classify programming languages based on their features.
Languages can be classified into multiple paradigms.
Major programming paradigms are:
1. Imperative
2. Logical
3. Functional
4. Object-Oriented
Imperative programming paradigms:
- In imperative programming paradigm , Computations are performed through a guided
sequence of steps, in which the variables are referred to or changed.
- The order of the steps is crucial, because a given step will have different consequences
depending on the current values of variables when the step is executed.
- Popular programming languages are imperative more often than they are any other
paradigm studies in this course. There are two reasons for such popularity:
 The imperative paradigm most closely resembles the actual machine itself, so the
programmer is much closer to the machine;
 Because of such closeness, the imperative paradigm was the only one efficient
enough for widespread use until recently.
Advantages
o Efficient
o close to the machine
o Popular
o Familiar.
Disadvantages
o The semantics of a program can be complex to understand or prove.
o Side effects also make debugging harder;
o Abstraction is more limited than with some paradigms;
o Order is crucial, which doesn't always suit itself to problems.
Logical programming paradigms:
- The Logical Paradigm takes a declarative approach to problem-solving.
- Various logical assertions about a situation are made, establishing all known facts.
- Then queries are made. The role of the computer becomes maintaining data and logical
deduction.

1
- A logical program is divided into three sections:
 a series of definitions/declarations that define the problem domain
 statements of relevant facts
 statement of goals in the form of a query
Advantages:
The advantages of logic oriented programming are
o The system solves the problem, so the programming steps themselves are kept to a
minimum;
o Proving the validity of a given program is simple.
3. Functional programming paradigms:
- The Functional Programming paradigm views all subprograms as functions in the
mathematical sense-informally, they take in arguments and return a single solution.
- The solution returned is based entirely on the input, and the time at which a function is
called has no relevance.
- The computational model is therefore one of function application and reduction.
Advantages:
o Higher level of abstraction
o The lack of dependence on assignment operations
o Possess referential transparency.
Disadvantages
o Perhaps less efficiency
o Problems involving many variables or a lot of sequential activity are sometimes easier
to handle imperatively or with object-oriented programming.
4. Object-Oriented
- Object Oriented Programming (OOP) is a paradigm in which real-world objects are
each viewed as separate entities having their own state which is modified only by built
inprocedures, called methods.
- Because objects operate independently, they are encapsulated into modules which
contain both local environments and methods. Communication with an object is done
by message passing.
- Objects are organized into classes, from which they inherit methods and equivalent
variables. The object-oriented paradigm provides key benefits of reusable code and
code extensibility.
Benefits and Features:
o A new class (called a derived class or subclass) may be derived from another class
(called a base class or superclass) by a mechanism called inheritance. The derived
class inherits all the features of the base class: its structure and behavior(response to
messages.
o Inheritance gives OOP its chief benefit over other programming paradigms - relatively
easy code reuse and extension without the need to change existing source code.Also,
encapsulation and information hiding are inherent benefits of OOP.

2
INTRODUCTION TO C PROGRAMMING:
- C is a general-purpose computer programming language developed in 1972 by Dennis
M. Ritchie at the Bell Telephone Laboratories to develop the UNIX Operating System.
- C is also called mother Language of all programming Language. It is the most widely
use computer programming language.
- All other programming languages were derived directly or indirectly from C
programming concepts.
- This language is used for develop system software and Operating System.
Features of C:

Simplicity:
- It is very easy to understand.
Portability:
- It is the concept of carrying the instruction from one system to another system
Powerful:
- C is a very powerful programming language, it have a wide verity of data types,
functions, control statements, decision making statements, etc
Structure oriented:
- Structure oriented programming language aimed on clarity of program, reduce the
complexity of code, using this approach code is divided into sub-program/subroutines.
These programming have rich control structure.
Modularity
- In c programming we can break our code in subprogram.
Middle level language:
- C programming language can supports two level programming instructions with the
combination of low level and high level language that's why it is called middle level
programming language
Compiler based:
- C is a compiler based programming language that means without compilation no C
program can be executed

3
Syntax based language
- C is a strongly tight syntax based programming language.
Efficient use of pointers
- Pointers is a variable which hold the address of another variable, pointer directly direct
access to memory address of any variable due to this performance of application is
improve
Uses(Applications) of C language:
 To Design Operating system
 To Design Language Compiler and Interpreter
 To Design Database
 Language Interpreters
 Utilities
 Network Drivers
 Assemblers
 UNIX Kernel is completely developed in C Language.

STRUCTURE OF A ‘C’ PROGRAM


Simple C Program:
/* Simple C program to display the text */
#include<stdio.h>:
int main()
{
printf(“good morning\n”);
return(0);
}
/*……..*/
A comment starts with star and asterisk /* and ends with asterisk and start */ .
comment lines used to give description and it is ignored by compiler during execution.
#include<stdio.h>
This <stdio.h> is called header file that has functions used for reading input and
generating output.
In order to use printf function, we need to include the required file in our program
using #include preprocessor.
int main()
C program consists of functions with required main() function as a entry point of
program. It is where, actual execution starts.
A program can have only one main function and any number of sub functions.
Curly brackets { …. }
Indicates block of code.
we can have statements inside the brackets to determine what the function does when
executed.

4
printf(“good morning\n”);
printf is a build-in functions which is used to display output in the screen.
\n is called escape sequence to go to next line It always begin with \ (back slash).
Semicolon(;)
It is used to terminate the statement.
return(0);
- This statement terminates the main function.
- Returns the value 0 to the operating system indicating Successful completion of
program.
- Any other number indicates that the program is failed.

Fig, Structure of C program


Documentation Section
o This section consists of set of comment lines which gives the name of programmer and
other details like time and date of writing the program.
o Comment lines used to give description and it is ignored by compiler during
execution.
o Documentation section helps anyone to get an overview of the program.
There are two types of comments.
Single line comment (// program for addition)
Multiple line comment(/* ……..*/)
Link Section
- The link section consists of the header files of the functions that are used in the
program.
- It provides instructions to the compiler to link functions from the system library.
- Some of the header files are,
#include<stdio.h>
#include<conio.h>
#include<math.h>

5
Here, #include is the preprocessor directive.
Definition Section
All the symbolic constants are written in definition section.
Macros are known as symbolic constants.
Ex: #define PI 3.14
Global Declaration Section
The variables that are used in more than one function throughout the program are called
global variables. Global variables declared outside of all the functions.
main() Function Section
Every C program must have one main() function, which specifies the starting point of ‘C’
program.
Main function contains two parts,
i. Declaration part
ii. Executable part
 The declaration part contains all the variables that are used in executable part.
 These two parts must be written in between the opening and closing braces.
 Each statement in the declaration and executable part must end with a semicolon (;).
 The execution of program starts at opening braces“{”and ends at closing braces“}”.
Subfunction(Sub program) Section
Subprogram section contains all the user defined functions that are placed after the main
function.

‘C’ CHARACTER SET


Character set is a set of alphabets, letters and some special characters that are valid in C
language.
The basic character set of C language includes,
2 types :
(i)Source Character Set :
Uppercase letters: A, B,C….Z.
Lowercase letters: a, b, c……z.
Digits: 0 to 9.
Special characters: , . : ; “ # % & ( ) { } [ ] | \/ _ ^~ +,-,~&,!,/,\,*@,etc.
White spaces characters int age; // balnk space between int and age is ignored by
compiler. It is used to distinguish the aqw.
(ii)Execution Character set:
Horizontal tab \t
Vertical Tab \v
New line character \n
Null Character \0

6
C TOKENS:
 C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.

IDENTIFIERS:
Identifiers are the name used to identify entities like variable, function, array, structure or any
other user-defined item.
Identifier must be unique.
They are created to give unique name to an entity to identify it during the execution of the
program.
Rules for naming an Identifier
 Identifier name in C can have letters, digits or underscore(_).
 The first character of an identifier name must be a alphabet (a-z, A-Z),underscore( _ ).
 The first character of an identifier cannot be a digit.
 Keywords are not allowed to be used as Identifiers.
 No special character (except underscore) blank space and comma can be used in
Identifier name.
KEYWORDS
 Keywords are reserved words that have a particular meaning in C language.
 The meaning of key word is predefined. These meaning of the keyword cannot be
changed.
 There are total 32 keywords in C language.

VARIABLES:
 It is a name given to the memory location.
 In programming, a variable is a container (storage area) to hold data.
 To indicate the storage area, each variable should be given a unique name called
identifier.

7
Rules to define variable name
 Variable name in C can have letters ( A – Z ), ( a – z ), numbers and underscore (_),
Digits ( 0 – 9 )
 No Special Symbols like blank space and Commas are allowed in variable name.
 First Character should be alphabet or underscore and not a number.
 Variable name should not be keyword.
 The maximum number of character(31 characters) is allowed in a variable and it
depends on a compiler.
2 steps:
(i)variable declaration
- Declaration of variables must be done before they are used in the program.
- Declaration does two things.
It tells the compiler , the name of the variable.
It specifies what type of data the variable will hold.
Syntax:
datatype variable;
Example:
int number;
char a;
float price;
char name[20];
(ii)variable initialization
- Initialization is done using assignment operator(=). Also, we can assign the value to the
variable during declaration itself.
If no input values are assigned(initialized) by the user , then the system will give a
default value to the allocated memory which is called garbage value.
Example,
int a=20;

L-Value: R-Value
L- Value Is An Object Locator. R-value refers to ‘Read Value’.
L-Value Stands For Left Value
The L-Value Could Legally Stand On The Left Side R-value can be anything of following:
Of An Assignment Operator. 1.Variable
For Example: Mark=20; // 2.Function
The L- Value Should Be A Variable. 3. Constant
Eg,
num=20; //constant R value

8
num=20+20; //constant R value
Expression

L value cannot be a constant and cannot be a datatype.


Eg, 5=num; //Error
int=num;
Example:
Addition of two numbers: Output:
#include< stdio.h> Sum is 100
int main()
{
int a,b,c; //Variable declaration
a=50; //Assigning values to variables
b=50;
c=a+b;
printf("sum is %d",c);
return(0);
}
Variable definition=variable declaration + memory reservation

Scope of variable(Types of variable):


Variable Scope is a region in a program where a variable is declared and used.
i. Local Variable - Variables that are declared inside a function or a block are
called local variables and are said to have local scope.
We can use (or access) a local variable only in the block or function in which it is
declared. It is invalid outside it.
ii. Global Variable:- Variables that are defined outside of all the functions and are
accessible throughout the program are global variables.
It is declared above the main function.
Example:(program using local and gloab Output:
variable) Value of a : 10
#include<stdio.h> Value of b : 20
int a=10; // global variable
int main()
{
int b=20; // local variable
printf("Value of a : %d\n",a);
printf("Value of b : %d\n",b);return(0);}

9
DATA TYPES :
 Data types determines the possible values that an identifier can have and the valid
operations that can be applied on it.
 The type of a data determines how much space it occupies in storage.
 In C Language, data types are broadly classified as

Basic/Primitive data types:


1. Character – char
2. Integer - int
3. Floating point – float
4. Double– double
5. No value available – void

1.Basic(Primitive) data types


Integer type:
 Integers are whole numbers that can have both positive and negative values but
no decimal values.
 Keyword for integer is int.
 Size of en integer is 2 bytes or 4 bytes.
 Size of the datatype change with respect to the processor used.
Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Floating type
 Float data type is used to store real numbers.

10
 Key word is float. The size of floating point number is 4 bytes.
 If the accuracy is not sufficient in floating point, the double data type can be used to
define the number.
 Eg, float height=5.5
Range values are given for 16 bit processor.
Type Size(bytes) Range
Float 4 3.4E-38 to3.4E+38
Double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Character type
- Character denotes any alphabet, digit or special symbol to represent information.
- Key word is char.
- Size of character is 1 byte. Eg, char a=‘h’;
Type Size(bytes) Range
char or signed char 1 -128 to127
unsigned char 1 0 to 255
void type
- void means no value.
- This is usually used to specify the type of functions.
Data type modifiers:
It is nothing but modifying the memory space allocated to the variable.
Types:
1. Signed(signed)
2. Unsigned(unsigned)
3. Short(short)
4. Long(long)
Integers and floating point variables can hold both negative and positive values.
Sign modifiers Size modifiers
Signed Unsigned short long
signed keyword unsigned keyword In general int data type It is used to increase
accepts both negative accepts only occupies different the size of the current
or positive value. positive values. memory spaces for a data type to 2 more
.(It is the default different operating bytes.
integer data type). system;
To allocate fixed
memory space short
keyword can be used.
Example: Example: For example: For Example:
signed int number; unsigned int rate; short int a; long int a;
or
int number;
11
2. User-defined Data Types
The C language provides flexibility to the user to create new data types. These newly created
data types are called user-defined data types. The use-defined data types in c can be created by
using:
1. typedef
2. Enumeration
typedef:
- typedef keyword is used to give new name to the existing data type..
Syntax:
typedef datattype
variable
In the below program, rollno is the variable name (alias)given to the existing datatype int. So,
after this type definition, roll no can be used instead of datatype int.
Example (using typedef): Output:
#include<stdio.h> Roll number1 is 4001
int main() Roll number2 is 4002
{
typedef int rollno;
rollno num1 = 4001,num2 = 4002;
printf("Roll number1 is %d\n",num1);
printf("Roll number2 is %d\n",num2); return(0); }

Enumerated data type:


- enum is a keyword used.
- It is mainly used to assign the names to integral constants ,as the names make a program
easy to read and maintain.
- The compiler assigns integer values starting from 0 and further increments by 1 for all
enum values(contants values ).
- We can also assign value to the enum constants if we need.
Syntax:
enum variable {value1, value2,.... Value n};
Default Numeric value assigned to first enum value is “0”.
Example: Example(using enum Example 2:
datatype): #include<stdio.h>
#include<stdio.h> main()
main() {
{ enum
enum month{JAN, FEB, month{JAN,FEB=5,MARCH,A
MARCH, APRIL, MAY}; PRIL=2, MAY,JUNE=3,
enum month m1; JULY};
m1=APRIL; enum month m1;
12
printf("%d",m1);} m1=MAY;printf("%d",m1);}
Output: Output:
3 3
Explanation: Explanation:
In this example, we Integers are assigned to enum
declared “m1” as the constants.
variable and the value of
“APRIL” is allocated to
m1, which is 3.
3.Derived data types
These data types are derived from the basic data types. Derived data types available in c are:
Array
Structure
Union
Pointer
Type conversion (Type casting):
- A type cast is basically a conversion from one type to another.
There are two types of type conversion:
Implicit Type Conversion (Also known as ‘automatic type conversion’):
- This Implicit conversion is done by the compiler on its own, without any
knowledge to the user.
- Generally type casting takes place when in an expression is having more than one
data type in it.
- Here, It is best practice to convert lower data type to higher data type to avoid
data loss. Because, Data will be truncated when the higher data type is converted
to lower. For example, if a float is converted to int, data which is present after
the decimal point will be lost.
- Hence, Compiler convers all operands into datatype of the largest operand.
bool-> char-> short int -> int -> unsigned int -> long -> unsigned -> long long ->float ->
double -> long double
Example 1:(implicit typecasting) Example 2: :(implicit typecasting)
#include<stdio.h> #include <stdio.h>
main() main() {
{ int i = 17;
int a=10; char c = 'c';
float b=6.1; float sum;
float c; sum = i + c; /* ascii value is 99 */
c=a+b; /*integer value 10 is converted to float value as printf("%f\n", sum );
10.0 automatically*/ }
printf("%f",c); Output:
} 116.000000

13
Output:
16.100000
Explicit Conversion(Type casting):
The type conversion performed by the programmer by specifying the data type in the
expression.
Data type should be mentioned before the variable name or value.
Syntax:
(data type)expression
Example1: Example2: :(Explicit typecasting)
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int x=13, y=5 ; int x=13, y=5 ;
float z; float z;
z=x/y; // here, quotient is int datatype and it is z=(float)x/y; // int data type is converted to
stored in float variable float and float value(quotiemt) is stored in
printf("%f",z); float variable
} printf("%f",z);
Output: }
2.000000 Output:
2.600000

STORAGE CLASS:
A storage class defines the scope (visibility) and life-time of variables.
Scope - Where to store a variable (Storage area of variable)
Lifetime- How long the variable can be stored in the memory( alive)
The following storage classes are most often used in C programming.
1.auto 2.static
3.extern 4.register
A variable should be declared in any one of these four storage class.
1.auto storage class:
- auto is the default storage class.
- It is stored in RAM(main memory)
Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It will be alive only inside the block of code where it is declared.
Default value is Garbage Value

Syntax: Example:
auto data_type variablename; (or) auto int a;

14
data_type variable; int a;
(both are same since auto is
default storage class )
To print the value using auto storage Output:
class: Value of a is: 11
#include<stdio.h> Value of a is: 11
int main() Value of a is: 11
{
increment();
increment();
increment();
}
int increment()
{
auto int a=10;
a++;
printf("Value of a is: %d\n", a);
}

2.Static Storage class:


Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It can be used throughout the program. That means, the variable will be alive
until the program completes its execution.
Default value is 0.
Syntax: Example:
static data_type variablename; static int a;
To print the value using static storage Output:
class: Value of a is: 11
#include<stdio.h> Value of a is: 12
int main() Value of a is: 13
{
increment();
increment();
increment();
}
int increment()
{
static int a=10;
a++;
printf("Value of a is: %d\n", a);
}
3.Extern Storage Class:
- This process is similar to storing global variable.
- When extern keyword is used, the compiler will come to know that somewhere in the
program , variable is declared or initialized(may be outside or inside the function,etc).
15
Scope: Variable can be accessed from anywhere in the program.
Lifetime: It can be used throughout the program. That means, the variable will be alive
until the program completes its execution.
Default Value is 0.
Note: Memory occupied by the variable will be released only after completion of the program.
Syntax: Example:
extern datatype variablename; extern a=10;
Printing the value of the variable using extern storage class.
#include<stdio.h> Output:
int main() 3
{ 10
int a=3;
extern int b;
printf("%d\n",a);
printf("%d\n",b);
}
b=10;

4.Register Storage Class:


- Register variables are also local variables, but stored in register memory.
Whereas, auto variables are stored in main CPU memory.
- These data objects will have a local life time.
- They have to be initialized implicitly otherwise they will have a garbage value.
Advantages: The register variables are faster than remaining variables, because register
variable are stored in register memory in the processor and not in main memory..
Limitation: But, only limited variables can be used as register since register size is very low.
(16 bits, 32 bits or 64 bits).
Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It will be alive only inside the block of code where it is declared.
Default value is Garbage Value
Only difference between auto and register the storage place(RAM/Register)

Syntax: Example:
register data_type variablename; register int a;
Printing the value of the variable using register storage class Output:
#include<stdio.h> Value of a is 11
int main() Value of a is 11
{ Value of a is 11
increment();
increment();
increment();

16
}
int increment()
{
register int a=10;
a++;
printf("Value of a is: %d\n", a);
}
Properties of Storage Class:

CONSTANTS (LITERALS):
Constants are the values that cannot be changed during the execution of a program.
Constant is a fixed value which may be an integer, floating point number, character or a string.
Types of constants:

 Integer constants:
- Integer constants are integer values like -1, 2, 8 without any decimal point.
- It can be either positive or negative. If no sign proceeds an integer is assumed to be
positive.
There are three types of integer constants in C language:
- Decimal constant (base 10)
- Octal constant (base 8)
- Hexadecimal constant (base 16)
17
 Floating-point constants:
- Floating point constants can be written in fractional form or exponential form. Floating
point constant are values like -23.1, 12.8, -1.8e12.
- The floating point constant in an exponential form has two parts: The mantissa part
and the exponent part. Both parts are separated by e or E.

 Character constants:
- Character constants can have one character enclosed within single quotes.
- For example: 'a', 'l', 'Y', 'A' etc.
Escape Sequences
- C supports some special character constants that are used in output functions.
- Escape sequence consists of a backward slash (\) followed by a character.

Escape Sequences Character


\n Newline
\a Alert
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
 String constants
- String constant can have group of characters enclosed within double quotes.
For example: “hai”, “welcome”
Declaring a variable as constant:
Syntax:
const datatype variable = constant
Example:
const float PI=3.14;
Program using const Output To find area of rectangle Output
keyword: error using const keyword. area : 70
#include<stdio.h> [const value #include <stdio.h>
int main() cannot be changed. int main()
{ {
18
const int a=10; const int LENGTH = 10;
printf("%d",a); const int WIDTH = 5;
a=20; int area;
return(0); area = LENGTH * WIDTH;
} printf("area : %d", area);
return(0);
}

OPERATORS IN C:
Operands:
 An operand specifies an entity on which an operation is to be performed.
 An operand can be a variable name, constant, a function call.
Operators:
 Operators are special symbol that tells the compiler to perform specific mathematical or
logical operations.
 Operator specifies the operation to be applied to its operands.
CLASSIFICATION OF OPERATORS:
The operators in c are classified on the basis of the following criteria:
1. The number of operands on which an operator operates.
2. The role of an operator.
Classification based on Number of Operands
Based upon the number of operands on which an operator operates,operators are classified
as,
Unary operator: Binary operator ternary operator
A unary operator operates Binary operator operates Ternary operator operates on three
on only one operand. on two operands. operands. (Conditional operator)
Eg, Eg: Eg,
-3. Here the – is an unary 2-3. Here (-) acts as a ?: is a ternary operator
minus operator. binary operator.
Classification based on role of operator
Based upon their role operators are classified as:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bitwise operators
6. Increment /Decrement operators
7. Conditional operator
8. Special operators
Arithmetic operators
Arithmetic operations like addition, subtraction, multiplication, divisions, etc. The arithmetic
operators available in c are given here.
19
Operato Description Eg Program Output:
r
+ adds two operands a+b #include<stdio.h> 13
- subtract second operands from a-b int main() -3
first { 40
* multiply two operand a*b int a=5,b=8; 0
/ divide numerator by denominator, a/b printf("%d\n",a+b); 40
gives quotient as result printf("%d\n",a-b);
% divide numerator by denominator, a%b printf("%d\n",a*b);
gives remainder as result printf("%d\n",a/b);
printf("%d\n",a*b);
}
Assignment Operators
A variable can be assigned a value by using an assignment operator. The assignment operators
are available in c are given below.
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 a+=b is same as
left a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as a=a-b
result to left operand
*= multiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=b is same as a=a/b
result to left operand
%= calculate modulus using two operands and assign the a%=b is same as
result to left operand a=a%b
Example: Output:
#include <stdio.h> c=5
int main() c=10
{ c=5
int a = 5, c;
c=25
c = a;
printf("c=%d \n", c); c=5
c += a; c=0
printf("c=%d \n", c);
c -= a;
printf("c=%d \n", c);
c *= a;
printf("c=%d \n", c);
c /= a;
printf("c=%d \n", c);
20
c %= a;
printf("c=%d \n", c); return 0;
}

Relational operators:
- Relational operators are used to check the conditions.
- If the relation is true, it returns 1; if the relation is false, it returns value 0.
- The operand may be variables, constants or expressions.
Operator Description Example program Output
:
== Check if two operand are equal #include<stdio.h> 0
!= Check if two operand are not equal. int main() 0
> Check if operand on the left is { 1
greater than operand on the right int a=5,b=8; 0
< Check operand on the left is smaller printf("%d\n",a==b); 1
than right operand printf("%d\n",a>b); 1
>= check left operand is greater than or printf("%d\n",a<b);
equal to right operand printf("%d\n",a>=b);
<= Check if operand on left is smaller printf("%d\n",a<=b);
than or equal to right operand printf("%d\n",a!=b);
}
Logical operators:
- Logical operators are used to combine the results of two or more conditions. C has the
following logical operators.
Op Description Example a=5, b=2
erator
&& Logial AND. True only if all operands are true ((a == 5) && (b > 5)) equals to 0.
|| Logical OR. True only if either one operand is true ((a == 5) || (b > 5)) equals to 1.
! Logical NOT. True only if the operand is 0 ! (a == 5) equals to 0.
Note: 1 represents true and 0 represents false.
Example: Output:
#include <stdio.h> 0
int main() 1
{ 1
int a=5,b=7,c=2;
printf("%d\n",((a==b)&&(a==c)));
printf("%d\n",((a==b)||(a>c)));
printf("%d\n",(!(a==b)));
}
Bitwise operators:
- Bitwise operators perform manipulations of data at bit level.
- It operates on individual bits of the operands.
- Bitwise operators are not applicable for float or double data types.

21
- The Truth table for &, | and ^ operation.
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
Assume A = 60 and B = 13 .
In binary format, A= 0011 1100 and B = 0000 1101
Operator Description A= 0011 1100 and B = 0000 1101
& Bitwise AND (A & B) = 12, i.e., 0000 1100
| Bitwise OR (A | B) = 61, i.e., 0011 1101
^ Bitwise exclusive OR (A ^ B) = 49, i.e., 0011 0001
~ Bitwise Complement (~A ) = -60, i.e,. 1100 0100 in 2's
complement form.
<< left shift A << 2 = 240 i.e., 1111 0000
>> right shift A >> 2 = 15 i.e., 0000 1111

Increment operator/decrement operator:


Increment operator:
- Increment operator is used to increment the value by adding 1.
- The value of i++ is equal to i=i+1.
Syntax:

Increment operator can be classified into two types.


pre increment operator
post increment operator
Pre increment operator: Post increment operator:
First the value of operand is The value of operand is used for the
incremented by 1 and then it is used evaluation of the expression and then it
for evaluation of the expression. is incremented.
For example: ++i For example: i++.
Decrement operator:
- Decrement operator is used to decrement the value by subtracting 1.
- The value of i-- is equal to i=i-1.
Decrement operator can be classified into two types.
pre decrement operator
post decrement operator

22
Pre decrement operator: .Post decrement operator:
First the value of operand is The value of operand is used for the
decremented by 1 and then it is used evaluation of the expression and then it
for evaluation of the expression. is decremented.
For example: --i For example: i--.

Example: Preincrement: Postincrement:


#include <stdio.h> #include<stdio.h> #include<stdio.h>
int main() int main() main()
{ { {
int i=10; int x,i; int x,i;
printf("%d\n",i++); i=10; i=10;
printf("%d\n",++i); x=++i; x=i++;
printf("%d\n",i--); printf("x:%d\n",x); printf("x: %d\n",x);
printf("%d\n",--i); printf("i:%d\n",i); printf("i: %d\n",i);
} return(0); return(0);
Output: } }
10 Output: Output:
12 x:11 x: 10
12 i:11 i: 11
10

Special Operator:
Operator Description Example
Sizeof Returns the size of an variable sizeof(x);
& Returns the address of an variable &x ;
* Pointer to a variable *x ;

Example: Output:
#include <stdio.h> Size of integer is 2
int main() Size of Float value is 4
{ Size of character is 1
int a;float b;char c;
printf("Size of integer is %d\n", sizeof(a));
printf("Size of Float value is %d\n", sizeof(b));
printf("Size of character is %d\n", sizeof(c));
}
Conditional operator:
Conditional operator is the ternary operator.
Syntax:
Condition? Expression 1: Expression 2
Condition: condition is checked first. This expression evaluates to 1 if it's true and evaluates
to 0 if it's false.
23
Expression1: If the condition is true, this expression is evaluated and return the result of
Expression1.
Expression2: If the condition is false, this expression is evaluated.
Advantages of ternary operator:
Using ?: reduce the number of line codes and improve the performance of application.
Example 1: Use of ternary Example 2: Use of ternary operator
operator
#include <stdio.h> #include<stdio.h>
int main() main()
{ {
int a=89,b; int a=10,b=20,small;
b=(a ==100?1:2); printf((a<b ? printf("a is less") : printf("a is greater")));
printf("%d\n",b);return(0); return(0);
} }
Output: Output:
2 a is less

PRECEDENCE OF OPERATORS:(Associativity)
 Each operator in c has a precedence associated with it..
 High precedence operator *, /,%.
 Low precedence operator +, -.
Precedence rule: This rule decides the order in which different operators are applied.
Associativity rule: This rule decides the order in which multiple occurrence of the same level
operators are applied.
 Several operators of the same precedence appear together, the operator are evaluated
according their associativity.
 If the operators are left-to-right associative, they are applied in left-to –right
order.
 If the operators are right-to-left associative, they are applied in right-to-left order.
 This table lists C operators in order of precedence (highest to lowest) and their
associativity.
Operator Description Associativity
() Parentheses (function call) left-to-right
[] Brackets (array subscript)
Increment right-to-left
++
decrement
--
Unary plus
+
unary minus
-
Address of operator
&
Determine size in bytes on this
sizeof
implementation

24
* Multiplication left-to-right
/ Division
% Modulus
+ Addition left-to-right
- Subtraction
< Relational less than operator left-to-right
<= less than or equal to operator
> Relational greater than
>= greater than or equal to
== Relational is equal to left-to-right
!= is not equal to
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Simple Assignment right-to-left
+= assign addition
-= Assign subtraction
*= Assign multiplication
/= Assign division
%= Assign modulus
, Comma operator left-to-right
Examples:
a=9-12/3+3*2-1 int a; a=2*3+4%5-3/2+6 int a= 5+7*4-9*(3,2)
a=? a=2*3.25+((3+6)/2) a=? a=?
a=9-4+3*2-1 a=? a=6+4-3/2+6 a= 5+7*4-9*2
a=9-4+6-1 a=2*3.25+9/2 a=6+4+1+6 a=5+28-18
a=5+6-1 a=6.50+4 a=10-1+6 a=33-18
a=11-1 a=10.50 a=9+6 a=15
a=10 a=10 a=15
(because ‘a’ is an integer)

25
b=4*6+3*4<3?4:3 a=2,b=12,c=1 find m=?
b=? d=a<b>c m=-43||8&&0||-2
b=24+3*4<3?4:3 d=2<12>1 d=1>1 m=-43||0||-2
b=24+12<3?4:3 d=0 m=1||-2
b=36<3?4:3 m=1
b=3

EXPRESSIONS:
Expressions:
An expression is a sequence of operands and operators.
The meaningful expression consists of one or more operands or operators that specify
the operations to be performed on operands.
Example: a+b, a-b.
Operands:
An operand specifies an entity on which an operation is to be performed.
Operators:
Operators are special symbol that tells the compiler to perform specific mathematical or logical
operations.
Operator specifies the operation to be applied to its operands.
Based on the number of operators present in an expression, expressions are classified as
simple expression and compound expressions.
Simple expressions:
An expression that has only one operator is known as a simple expression
For example: a+2;
Compound Expressions:
An expression that has more than one operator is known as compound expressions.
For example: b= 2+3*5;
INPUT AND OUTPUT STATEMENTS:
In c language two types of input/output statements are available. They are
1. Formatted input/output statements
2. Unformatted input/output statements

26
FORMATTED INPUT AND OUTPUT STATEMENTS:
Formatted input and output refers to input and output, that has been arranged in a particular
format.
It read and writes all types of data values.

scanf() statement:
 scanf() is a built-in library function in c.
 It is a standard input function used to read inputs from the user during execution of the
program.
Syntax:
scanf(“control strings”,&variable1,&variable2….&variable);
Control strings(Format Specifier):
- Control string is the type of data that the input statement going to accept, this
always preceded with a % sign.
- Each variable name must be preceded by an ampersand (&).
- & is the address of operator which gives the address of variable.
- It is built in function defined in the <stdio.h> header file.
- The given table lists some control strings with its meaning.
Format specifier Meaning
%c Single character
%s String
%d Integer
%f Float
%ld Double
scanf() for integer data type(%d)
Example:
scanf(“%d”,&a);
- here, a is a variable holding integer value.
- %d is the integer format specifier to represent integer data.
- ‘&’ symbol is used to represent the memory address of the variable.
scanf() for float data type(%f)
Example:
scanf(“%f”,&b);
- here, b is a variable holding float or fractional value.
- The format specifier %f indicates floating or fractional data.
scanf for character data type(%c)
Example:
scanf(“%c”,&ch);
27
- here ch is the character datatype.
- %c is the character format specifier to represent character.
scanf for string(%s)
Example:
scanf(“%s”,name);
- here name is the string datatype.
- %s is the string format specifier to represent string data.
Rules for writing scanf function:
o scanf() statement should end with a semi colon (;). This indicates the compiler that it is
the end of the statement..
o The format specifiers should always be placed in between double quotes (“ ”).
o Separate the variables using comma (,)
o Always use a right format specifier while using scanf() function in C.
o Always use the exact data type of the variable for reading the data.
o As C is a case sensitive language, capital letters are not used while writing scanf()
function.
printf() statement:
 It is used to display the output to the screen.
 printf is used to print the message or value.
 It is builtin function defined in the stdio.h header file.
2 ways of using printf statement:
(i) printf() can print text on the screen without using any format specifier.
Syntax:
printf(“string”);
Example:
printf(“hello my dear friend”);
(ii) printf() is used to print the value of the variable and results of the expressions.Using
format specifier
Syntax:
printf(“control string”, variable1,variable2..);
Example:
printf(“my age is %d”, age)
Control strings(Format Specifier):
- Control string is the type of data that the input statement going to accept, this always
preceded with a % sign.
printf() for integer datatype:
Example:
printf(“%d%d”,a,b); // here a and b variables holding integers.
printf() for float datatype:
Example:
printf(“%f%f”,a,b); //here a and b are variables holding float values.
28
printf for character datatype:
Example:
printf(“%c”,ch); //here ch is the character datatype.
printf for string:
Example:
printf(“%s”,name); //here name is the string datatype.
Rules for writing printf statement:
1. The message which is to be printed should be placed in between double quotes (“ ”).
2. The printf() function should follow a semi colon at the end.
3. Separate the format specifiers and variables using comma (,).
Use of printf() and scanf() functions in C: Output:
#include<stdio.h> Enter any character:
int main() s
{ Entered character is s
char ch; Enter any string:
char str[100]; anitha
int num; Entered string is anitha
printf("Enter any character:\n"); Enter the number
scanf("%c", &ch); 301
printf("Entered character is %c \n", ch); entered number is 301
printf("Enter any string: \n");
scanf("%s", str);
printf("Entered string is %s \n", str);
printf("Enter the number\n");
scanf("%d",&num);
printf("entered number is %d:",num);
return(0);
}
Program to add two numbers:
#include<stdio.h
int main() Output:
{ Enter two numbers:
int a,b,c; 2
printf("Enter two numbers:\n"); 2
scanf("%d%d",&a,&b); Sum of entered
c = a + b; numbers is 4
printf("Sum of entered numbers is %d\n",c);
return(0);
}
Program to print student details:
#include<stdio.h> Output:
int main() enter the roll no,mark1,
{ mark2,mark3,name
int rollno,m1,m2,m3; 1001 95 85 95 george
char name[20]; Roll no is 1001
float total,percentage; Name is george
29
printf("enter the roll no,mark1,mark2,mark3,name\n"); Marks Obtained is 958595
scanf("%d%d%d%d%s",&rollno,&m1,&m2,&m3,name total marks is 275.000000
); percentage is 91.666664
total=(m1+m2+m3);
percentage=total/3;
printf("Roll no is %d\n",rollno);
printf("Name is %s\n",name);
printf("Marks Obtained is %d%d%d\n",m1,m2,m3);
printf("%total marks is %f\n",total);
printf("percentage is %f\n",percentage);
return(0);
}
Swapping of 2 values using temporary variable: Output:
#include <stdio.h> Enter the value of a and b
int main() 4
{ 5
int a,b,temp; Before Swapping value of a
printf("Enter the value of a and b\n"); and b is: 4 5
scanf("%d%d", &a, &b); After Swapping value of a
printf("Before Swapping value of a and b is: %d and b is: 5 4
%d\n",a,b);
temp=a;
a=b;
b=temp;
printf("After Swapping value of a and b is: %d
%d\n",a,b);
return(0);
}
Swapping of 2 numbers without using temporary variable: Output:
#include <stdio.h> Enter the value of a and b
int main() 4
{ 5
int a,b,temp; Before Swapping value of a
printf("Enter the value of a and b\n"); and b is: 4 5
scanf("%d%d", &a, &b); After Swapping value of a
printf("Before Swapping value of a and b is: %d and b is: 5 4
%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After Swapping value of a and b is: %d
%d\n",a,b);
return(0);
}
Program to convert Celsius to Fahrenheit: Output:
#include<stdio.h> Enter the Temperature in
int main () Celcius:10

30
{ The Temperature in
float celsius, fahrenheit; Fahrenheit is:50.000000
printf ("Enter the Temperature in Celsius:");
scanf ("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf ("The Temperature in Fahrenheit is:%f", fahrenheit);
return(0);
}
Program to find slope and midpoint of a line: Output:
#include<stdio.h> Enter the first point x1,y1:
int main () 10
{ 20
float xmp,ymp,x1,y1,x2,y2,slope; Enter the second point
printf ("Enter the first point x1,y1:\n"); x2,y2:
scanf ("%f %f", &x1,&y1); 30
printf ("Enter the second point x2,y2:\n"); 40
scanf ("%f %f", &x2,&y2); Slope is:1.000000
slope=(y2-y1)/(x2-x1); midpoint is:20.000000
xmp=(x1+x2)/2; 30.000000
ymp=(y1+y2)/2;
printf ("Slope is:%f\n", slope);
printf("midpoint is:%f %f",xmp,ymp);
return(0);
}

UNFORMATTED INPUT AND OUTPUT STATEMENTS:


Unformatted I/O functions work only with character data type (char). This is also called
character oriented I/O functions.
There are 2 different types:
o Character I/O
o String I/O
o File I/O
Various functions are,

Input Function Output Function


getchar() putchar()
This function reads one character at a time till This function prints one character on the
the user presses the enter key. screen at a time, which is read by standard

31
input.
Syntax: Syntax:
variable name=getchar(); putchar(variable_name);
Example Example:
char c; char c;
c=getchar(); putchar(c );
Program using getchar and putchar function:
#include<stdio.h>
int main()
{
char a;
printf("enter any key");
a=getchar(); // read input and store it in variable ‘a’
putchar(a); //display the output on screen
}
Output:
enter any key
s
s
getch() putch()
- getch() accepts only single character It displays any alphanumeric characters to the
from keyboard. standard output device. It displays only one
- getch() function will just wait for any character at a time.
keyboard input (and press ENTER). It won’t Syntax:
display the given input character in output putch(variable_name)
screen. Example:
Syntax: char a;
variable_name=getch(); putch(a);
Example:
char x;
x=getch();
Program using getch() function:
#include <stdio.h>
int main()
{
printf("Hello World! ");
getch();
return 0;
}
Output:
Hello World!

32
getche()
Like getch(), getche() also accepts only single character, but getche() displays the entered input
character in the screen.
Syntax:
Variable_name=getche();
Example:
char x;
x=getche();
To use getch(), getche() functions, you need to include #include <conio.h> header file
which is a non-standard header file.
gets() puts()
- gets() accepts any line of string including puts displays a single / paragraph of text to the
spaces from the standard Input device standard output device.
(keyboard). Syntax:
-gets() stops reading character from keyboard puts(variable_name);
only when the enter key is pressed. Example:
Syntax: char name[25];
gets(variable_name); puts(name);
Example:
char name[25];
gets(name);
Program to read and print the string using
gets and puts:
#include<stdio.h>
main()
{ Output:
char name[20]; enter the string
printf("enter the string\n"); hello my friend
gets(name); hello my friend
puts(name);
return(0);
}

Character Build-in functions:


isalnum(ch)
isalpha(ch)
isdigit(ch)
islower(ch)
isupper(ch)
tolower(ch)
toupper(ch)

33
Program to convert character from lower case to uppercase and vice versa:
#include<stdio.h> Output 1:
int main() enter the character
{ g
char a; G
printf("enter the character\n"); Output 2:
a=getchar(); enter the character
if(islower(a)) G
putchar(toupper(a)); g
}
else
{
putchar(tolower(a));
} return(0);
}
Difference Between Formatted And Unformatted Input/Output Functions:
Formatted Unformatted
1. These are standard input output library These are console input output library function.
function.
2. Formatted input and output functions can Unformatted input/output can deal with one
deals with all kind of data types. character at a time and string function for array
of characters (string).
3. Unformatted Input / Output functions Formatted Input / Output functions are several
have fixed format to give the input and standard library functions
obtain the output.

DECISION MAKING( BRANCHING STATEMENTS) IN C:


- Decision making and branching statements are used to decide the order of execution of
statements based on certain conditions.
- Decision making and branching statements are used to transfer the program control from
one point to another.
- They are categorized as
 Conditional statements
 Unconditional statements
Conditional statements:
Conditional statements also known as Selection statements. In this, the program control is
transferred from one point to another based upon the outcome of certain condition. The
following conditional statements are available in C:
1. if statement
2. if-else statement
3. nested if statement
4. else-if ladder
5. switch statements
34
1. if statement
 If the condition is true, the statements inside if statement will be executed.
 If the condition is false, the control will be transferred to the statements outside of if.

Program to check the given number is positive Output


#include<stdio.h> Enter the number
int main() 6
{ number is positive
int num;
printf("Enter the number\n");scanf("%d",&num);
if(num>0)
{
printf("number is positive");
}
}
Program to find the purchase value. If >1000, price 200
will deducted from purchase. Output
#include<stdio.h> enter the purchase value50000
int main() deducted amount is 49800
{
int purchase;
printf("enter the purchase value");
scanf("%d",&purchase);
if(purchase>1000)
{
purchase=purchase-200;
}
printf("deducted amount is %d", purchase);
}
2. if...else statement
 In this, else statement can be combined with if statement.
 If Condition is checked first.
 If the condition is true, statements inside the if part is executed
 When the condition is false, statements in else part is executed.

35
Program to check vote eligibility Output:
#include<stdio.h> enter your age
int main() 5
{ not eligible to vote
int age;;
printf("enter your age\n"); scanf("%d",&age);
if(age>18)
printf("eligible to vote");
else
printf("not eligible to vote");return(0);
}
Program to find odd or even number Output
#include<conio.h> enter the number
int main( ) 6
{ 6 is even
int n; enter the number
printf("enter the number\n");scanf("%d",&n); 5
if(n%2==0) 5 is odd
printf("%d is even",n);
else
printf("%d is odd",n);return(0);
}
Greatest of 2 numbers: Output
#include<stdio.h> enter the 2 numbers
int main( ) 4
{ 100
int a,b; 100 is greater
printf("enter the 2 numbers\n");scanf("%d%d",&a,&b);
if(a>b)
printf("%d is greater",a);
else
printf("%d is greater",b);return(0);
}

36
Leap year or not:
#include <stdio.h> Output:
int main()
{ Enter a year
int year; 2016
printf("Enter a year\n"); leap year
scanf("%d", &year);
if ((year%4 == 0) && (year%100!=0)|| (year%400==0))
printf("leap year.\n");
else
printf("not a leap year.\n");
return(0);
}
Note:
A year is leap year if following conditions are satisfied
1) Year is multiple of 400
2) Year is multiple of 4 and not multiple of 100.
3. Nested if-else statement
 Nested if-else is used to check more than one conditions.
 If there are more than two alternatives to select, then the nested-if statements are used.
 The conditions are executed from top to bottom.
 Enclosing an if statement within another if statement is called nested-if statement.

If 'expression' is false the 'statement-3' will be executed, otherwise it continues to check the
condition for 'expression 1' .
If the 'expression 1' is true the 'statement-1' is executed otherwise 'statement-2' is executed

37
Program to find greatest of three number. Output
#include<stdio.h>
int main( )
{ enter 3 numbers
int a,b,c; 6
printf("enter 3 numbers\n"); 8
scanf("%d%d%d",&a,&b,&c); 1
if(a>b) 8 is greatest
{
if( a > c)
printf("%d is greatest",a);
else
printf("c is greatest");
}
else
{
if( b> c)
printf("b is greatest");
else
printf("c is greatest");
}return(0);
}

4.else-if ladder :
 If there are more than three alternatives, we can go for else if ladder.
 Once a true condition(if) is satisfied, the other statements in the ladder will be skipped.
 When all conditions became false, then the final else part which contains default statement will
be executed.

38
Program to print class obtained based on percentage of marks Output:
#include <stdio.h> Enter the percentage of marks
int main() obtained by student:
{ 53
int marks; Grade E
printf("Enter the percentage of marks obtained by student:\n");
scanf("%d",&marks);
if(marks>=90)
printf("Grade S");
else if(marks>=80)
printf("Grade A");
else if(marks>=70)
printf("Grade B");
else if(marks>=60)
printf("Grade C");
else if(marks>=55)
printf("Grade D");
else if(marks>=50)
printf("Grade E");
else
printf("Grade U");return(0);
}
Program to find Quadratic Equation: Output:
#include <stdio.h> enter the value of a,b & c
#include<math.h> -1
int main() 2
{ 4
int a,b,c,d; Both roots are real and diff
float x1,x2; First Root x1= -1.236068
printf("enter the value of a,b & c\n"); Second Root x2= 3.236068
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if(d==0)
{
printf("Both roots are equal\n");
x1=-b/(2.0*a);
x2=x1;
printf("First Root x1= %f\n",x1);
printf("Second Root x2= %f\n",x2);
}
else if(d>0)
{
printf("Both roots are real and diff-2\n");
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("First Root x1= %f\n",x1);
printf("Second Root x2= %f\n",x2);

39
}
else
printf("Root are imaginary\n");
}
Program to find the entered key is an alphabet or numeric Output:
or alphanumeric(using character Build-in functions) Enter any key
#include<stdio.h> 8
int main() Entered key is number
{
char a;
printf("Enter any key\n");
a=getchar();
if(isdigit(a))
printf(" Entered key is number");
else if(isalpha(a))
printf("Entered key is alphabet");
else
printf("Entered key is alphanumeric");
return(0);
}
Program to find the entered key is an alphabet or numeric or Output:
alphanumeric(using print, scanf statements) enter a single character or
#include<stdio.h> value
int main() [
{ Alphanumeric
char ch;
printf("enter a single character or value \n"); scanf("%c",&ch);
if((ch>='a')&&(ch<='z'))
printf("Alphabet\n");
else if((ch>='0')&&(ch<='9'))
printf("Number\n");
else
printf(("Alphanumeric\n")); return(0);
}
Note:
In if statement, a single statement can be written without using curly braces { }
Eg, int x=2;
if(x > 4)
printf("welcome");
In the above case, no curly braces are required, but if we have more than one statement
inside if condition, then we must use curly braces.
Other than 0(zero), all other values are considered as true.
Eg, if(9)
printf("welcome");
In above example, hello will be printed, because the integer 9 is a non zero value.

40
Switch statement:
 C provides a multi way decision statement called switch statement.
 It allows the user to make a decision from number of choices.
 The expression(condition) in switch case return an integer value or character constant,
which is compared with the values in different cases.
 When the condition matches with the case ,that block of statement is executed.
 If there is no match, then default statement is executed.

Note:
It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of
codes will get executed after the matching block.
int i = 1;
switch(i)
{
case 1:
printf("A"); // No break case 2:
printf("B"); //No break case 3:
printf("C");
break;
}
Output : A B C
- The output was supposed to be only A because only the first case matches, but as there is no break
statement aftertheblock, thenext blocksareexecuted, untilthe cursor encounters a break.
Rules for switch Statement:
o Default case is optional and can be placed anywhere in the switch case. But Usually we place itattheend.

41
o Case keyword must terminate with colon(:)
o Case order execution is from top to bottom.
o No two case constant should be same.
Example: To print month using switch case Output:
#include<stdio.h> Enter any number
int main() from 1 to 4 to
{ represent month
int ch; 3
printf("Enter any number from 1 to 4 to represent month\n"); March
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("january");
break;
case 2:
printf("february");
break;
case 3:
printf("march");
break;
case 4:
printf("april");
break;
}
return(0);
}
Arithmetic operations using switch: Output:
#include<stdio.h> 1.Addition
int main() 2.Subtraction
{ 3.Multiplication
int a,b,op; 4.Division
printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n"); Enter the values of a
printf("Enter the values of a & b: "); & b: 20 5
scanf("%d %d",&a,&b); Enter your Choice :
printf("Enter your Choice : ");scanf("%d",&op); 3
switch(op) Multiplication is :
{ 100
case 1 :
printf("Sum is : %d",a+b);
break;
case 2 :
printf("Difference is : %d",a-b);
break;
case 3 :
printf("Multiplication is : %d",a*b);

42
break;
case 4 :
printf("Division is %d : ",a/b);
break;
default :
printf(" Enter Your Correct Choice.");
break;
}
return(0);
}
Printing student GPA details using switch case:
#include<stdio.h> Output:
int main() Enter three subject
{ Marks95
int m1,m2,m3,gpa; 94
float tot, avg; 96
printf("Enter three subject Marks"); grade=A
scanf("%d%d%d",&m1,&m2,&m3);
tot=m1+m2+m3;avg=tot/3; gpa=avg/10;
switch(gpa)
{
case 10: printf("grade=S"); break;
case 9 : printf("grade=A"); break;
case 8 : printf("grade=B"); break;
case 7 : printf("grade=C"); break;
case 6 : printf("grade=D"); break;
case 5 : printf("grade=E"); break;
default : printf("grade=F");
}
return(0);
}
LOOPING STATEMENTS / ITERATIVE STATEMENTS:
 In Loop, sequence of statements are executed until a specified condition is true.
 This sequence of statements to be executed is kept inside the curly braces { } known as the Loop
body.
 After every execution of loop body, condition is verified, and if it is found to be true the loop body is
executed again. When the condition check returns false, the loop body is not executed.
 There are 3 type of Loops in C language
for loop
while loop
do-while loop
Entry controlled loop Exit controlled loop
The test condition is checked first before The loop is executed first and then condition
the loop is executed. is checked.

43
Example The loop is executed at least once, even
while loop when the condition is false.
for loop Example
do-while loop

while Loop:
 It is an entry controlled looping statement.
 Statements are executed repeatedly until the while condition is true.
 It is completed in 3 steps.
 Variable initialization. ( e.g int x=0; )
 Condition Checking ( e.g while( x<=10) )
 Variable increment or decrement ( x++ or x-- or x=x+2)
Description:
Step 1: The while condition is checked first.
Step 2: If the condition is true, the statements inside the loop will be executed, then the variable
value is incremented or decremented at the end of the looping statement.
Step 3: If the condition is false, the loop body will be skipped and the statements after the while
loop will be executed.

Sum of n natural numbers using while loop Output:


#include<stdio.h> Enter a number
int main() 5
{ The sum of nos: 15
int n,i=1,sum = 0;
printf("Enter a number\n"); scanf("%d",&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf("The sum of nos: %d\n",sum);return(0);
}

44
Sum of Digits of given number using while loop: Output:
#include <stdio.h> enter the number
int main() 555
{ sum of digits of given no is: 15
int n,dig,sum1=0;
printf("enter the number\n");scanf("%d",&n);
while(n>0)
{
dig=n%10;
sum1=sum1+dig;
n=n/10;
}
printf("sum of digits of given no is: %d",sum1);
return(0);
}
To reverse the given number Output:
#include <stdio.h> Enter a no to reverse
int main() 523
{ Reverse of entered no=325
int n,dig,rev=0;
printf("Enter a no to reverse\n"); scanf("%d",&n);
while(n>0)
{
dig=n%10;
rev=(rev*10)+dig;
n=n/10;
}
printf("Reverse of entered no=%d",rev); return(0);
}
To check the given number is palindrome or not: Output:
#include <stdio.h> Enter a number to check
int main() palindrome:
{ 1221
int n,rev=0,temp,dig; It is a palindrome no.
printf("Enter a number to check palindrome:\n");
scanf("%d",&n);
temp=n;
while(temp != 0 )
{
dig=temp %10;rev=rev*10 + dig; temp=temp/10;

45
}
if(rev == n )
printf("It is a palindrome no.\n"); else
printf("it is not a palindrome no.\n"); return(0);
}
To Check Armstrong number or not: Output:
#include <stdio.h> Enter a number
int main() 153
{ Its an Armstrong number
int n, arm = 0, dig, temp;
printf("Enter a number\n");
scanf("%d", &n);
temp=n;
while (temp != 0)
{
dig = temp %10;arm= arm + (dig*dig*dig);
temp = temp/10;
}
if(arm==n)
printf("Its an Armstrong number"); else
printf("Its an not Armstrong number"); return(0);
}

do while loop:
 It is an exit controlled looping statement.
 The do-while loop checks its condition at the bottom of the loop whereas for and while loops,
the loop condition is checked at the top of the loop.
 do-while loop is guaranteed to execute the statement at least one time.

46
While Do while
Condition is tested first and then statements are Statements are executed at least
executed. once. then the conditions are tested.
While loop is entry controlled loop Do wile loop is exit control
loop.

Sum of 10 natural no’s using do while loop: Output:


#include<stdio.h> Enter a number
int main() 10
{ The sum of digits: 55
int n,i=0,sum = 0;
printf("Enter a number\n"); scanf("%d",&n);
do
{
sum=sum+i;
i++;
}while(i<=n);
printf("The sum of digits: %d\n",sum);return(0);
}
Program to print multiples of 5: Output:
#include<stdio.h> 5
int main() 10
{ 15
int a=5,i=1; 20
do 25
{ 30
printf("%d\n",a*i); 35
i++; 40
} 45
while(i <= 10); 50
}
Program to print the squares of number from 1 to 10: Output:
#include<stdio.h> numbers squares
#include<math.h> 1 1
int main() 2 4
{ 3 9
int num=1,sq; 4 16
printf("numbers squares\n"); 5 25
do 6 36
{ 7 49
sq=pow(num,2); 8 64
printf("%d%20d\n",num,sq); 9 81
num++; 10 100
}while(num<=10);
return(0);
}

47
for loop:
for loop is used to execute a set of statements repeatedly until a particular condition is satisfied.

Flow of Execution:
i.The initialization step is executed first, and only once. This step allows to declare and
initialize any loop control variables.
ii.Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop will not be executed and flow of control jumps to the next
statement just after the for loop.
iii.After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows to update any loop control variables.
iv.The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). When the
condition becomes false, the for loop terminates.
Different ways of implementing for loop:
Form Comment

for(i=0;i<10;i++)
Single Statement
Statement1;

for ( i=0 ;i <10; i++) Multiple Statements within for


{
Statement1;
Statement2;
Statement3;
}

for ( i=0 ; i < 10;i++) ; For Loop with no Body ( Carefully Look
at the Semicolon )

48
for(i=0,j=0;i<100;i++,j++) Multiple initialization & Multiple
Statement1; Update Statements Separated by Comma

for ( ; i<10 ; i++) Initialization not used

for ( ; i<10 ; ) Initialization & Update not used

for ( ; ; ) Infinite Loop, Never Terminates


Simple Programs using for loop:
Printing n natural numbers: Output:
#include <stdio.h> enter the maximum no to be
int main() printed:10
{ 1
int n,i; 2
printf("enter the maximum no to be printed:"); 3
scanf("%d",&n); 4
for(i=1;i<=n;i++) 5
{ 6
printf("%d\n",i); // 7
} 8
return(0); 9
} 10
Printing n even numbers: Output:
#include <stdio.h> Enter the number:10
int main() 0
{ 2
int n,i,sum=0; 4
6
printf("Enter the number:"); 8
scanf("%d", &n); 10
for (i = 0; i <= n; i=i+2)
printf("%d\n",i);
return(0);
}
Sum of n Odd numbers: Output:
#include <stdio.h> Enter the number
int main() 10
{ Sum of entered odd number is
int n,i,sum=0; 25
printf("Enter the number\n");scanf("%d", &n);
for (i = 1; i <= n; i=i+2)
sum = sum + i;
printf("Sum of entered odd number is %d",sum);
return(0);
}

49
Sum of Squares of a number: Output:
#include <stdio.h> Enter the number:4
int main() sum is 30:
{
int n,i,sum=0;
printf("Enter the number:");scanf("%d", &n);
for (i = 1; i <= n; i=i+1)
{
sum=sum+(i*i);
}
printf("sum is %d:\n",sum);return(0);
}
To find Factorial of the given number: Output:
#include <stdio.h> Enter the number:5
int main() sum is 120:
{
int n,i,fact=1;
printf("Enter the number:");scanf("%d", &n);
for (i = 1; i <= n; i=i+1)
fact=fact*i;
printf("sum is %d:\n",fact);return(0);
}
Sum of series 1+1/2+1/3+…….. + 1/n Output:
#include <stdio.h> Enter the number
int main() 5
{ Sum of the series =2.283333
double sum=0.0,n,i;
printf("Enter the number\n"); scanf("%lf", &n);
for (i = 1; i <= n; i++)
sum = sum + (1/i);
printf("Sum of the series =%lf ",sum);return(0);
}
Sum of series 1/1!+1/2!+1/3!+…….. + 1/n! Output:
#include <stdio.h> Enter the number
int main() 5
{ Sum of the series =0.008333
double sum=0.0,n,i,fact=1;
printf("Enter the number\n"); scanf("%lf", &n);
for (i = 1; i <= n; i++)
fact=fact*i;
sum = sum + (1/fact);
printf("Sum of the series =%lf ",sum);return(0);
}
Fibonacci Series: Enter the number of terms: 10
#include <stdio.h> 0,1,1,2,3,5,8,13,21,34,
int main()

50
{
int i, n, a = 0, b = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
printf("%d,",a);
next=a+b;
a=b;
b=next;
}return 0;
}
To find Factors of a given number: Output:
#include<stdio.h> Enter a number to find
int main() its factors
{ 10
int n,i; factors are: 1
printf("Enter a number to find its factors\n"); factors are: 2
scanf("%d",&n); factors are: 5
for (i=1;i<=n;i++) factors are: 10
{
if(n%i==0)
printf("factors are: %d\n",i);
}
return(0);
}
Program to check the number is prime or not: Output:
#include<stdio.h> enter the no
int main() 11
{ number is prime
int n,i,flag; printf("enter the no\n");
scanf("%d",&n);
for(i=2;i<n;i++) Note:
{ Flag is a Boolean variable that
if(n%i==0) has only 2 states (0 and 1)
{ Eg, On/Off, True/False,
flag=0; Yes/No
break;
}
}
if(flag==0)
printf("number is not prime \n");
else
printf("number is prime\n");
return(0);
}

51
Nested for loop:
- One for loop inside another for loop.

Flowchart:

Program to multiply numbers using nested for: Output:


#include <stdio.h> 1
int main() 2
{ 2
int i,j; 4
for(i=1;i<3;i++)
{
for(j=1;j<3;j++)
{
printf("%d\n",i*j);
}
}
return(0);
}

52
Loop Control Statements:
C language allows jumping from one statement to another within a loop as well as
jumping out of the loop.
1. break
2. continue
3. goto
4. return
1) break statement
 When break statement is encountered inside a loop, the loop is immediately
terminated and program control comes out of the loop and executes the
statement immediately following the loop.
 It can be used in iteration only(looping statements).
 Cannot be used in conditional statements(if, else, else if).
Syntax:
break;

2) continue statement:
C Continue statement are used to skips the rest of the current iteration in a loop and returns to
the top of the loop.
Syntax:
continue;

53
Example:
Use of break statement to Output: Use of continue statement to Output:
print numbers: print numbers:
#include <stdio.h> enter the enter the
int main() #include <stdio.h>
number: 10 number: 10
{ int main()
int i,num; 1 { 1
printf("enter the number: "); 2 int i,num; 2
scanf("%d",&num); 3 printf("enter the number: "); 3
for(i=1;i<=num;i++) 4 scanf("%d",&num); 4
{ for(i=1;i<=num;i++) skipped
if(i==5) { 6
{ if(i==5)
7
printf("stop"); {
break; printf("skipped\n"); 8
} continue; 9
printf("%d\n",i); } 10
} printf("%d\n",i);
return(0); }
} return(0);
}
Break Continue
Break statement is used to transfer the Continue is used to skip some statement of
control of the program to outside loop or the loop and moves to the next iteration in
switch case statement. the loop.
It is used in loop as well as switch case. It is used only within the loop.
Syntax: break; Syntax: continue;

3) goto statement:
 The goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
 When a goto statement is encountered in a C program, the control jumps directly to the
label mentioned in the goto statement.
 It us used when loops are deeply nested and simple break statement cannot work
effieciently.
Syntax:
goto label_name;


label_name

54
Flowchart: Program to print sum
of no’s using goto
statement:
#include <stdio.h>
int main()
{
int sum=0,i;
for(i = 0; i<=10; i++)
{
sum = sum+i;
if(i==5)
{
goto addition;
}
}
addition:
printf("sum is %d",
sum);
return(0);
}
Output:
sum is 15

Preprocessor Directives:
 Preprocessor is a program which will be executed automatically before passing the source
program to compiler. This process is called pre-processing.
 The preprocessor provides the ability for the inclusion of header files, macro expansions,
conditional compilation, and line control.
 Commands used in preprocessor are called preprocessor directives.
 They begin with "#" symbol and should be not ended with (;)
 Proprocessor Directive can be place any where in the program, but generally it place top of the
program before defining the first function.
Preprocessor directives in C:
 Macro substitution directives. example: #define
 File inclusion directives. example: #include
 Conditional compilation directive. example: #if, #else, #ifdef, #undef, #endif
 Miscellaneous directive. example: #error, #line

55
(i)Macro preprocessor:
Example: To print PI value
#include<stdio.h>
#define PI 3.14
int main()
{
printf("%f",PI);
}
Three types of macros are
Simple macros Augmented macros Nested macros
Define symbolic It is used to define more The macro defined within another
constants complex expressions macro is called nested macro.
Example: Example: Example:
#define A 100 #define sqr(n) (n*n) #define sq(n) (n*n)
#define tablesize 10 #define cube(n) (n*n*n)

(ii)File Inclusion:
This is used to include an external file which contains functions into the program. It enables code
reusability.
Syntax Example
#include "filename" #include"example.c"
#include <filename> #include<stdio.h>
 The filename is quoted in quotes (“ ”), then it searches that file in current directories.
 When the filename is quoted in angle brackets (< >), then it searches the file in standard
directories only.
(iii)Conditional Directives:
#if, #else and #endif:
If given condition is true, "If" clause statement is included in source file . Otherwise, else clause
statement is included in source file for compilation and execution.

56
Example: Tocheck the Vote eligibility using #if, #else and #endif
#include<stdio.h> Output:
#define AGE 5 Not eligible
int main()
{
#if (AGE>=18)
{
printf("Eligible for voting");
}
#else
{
printf("\n Not eligible");
}
#endif
return(0);
}
#ifdef, #else and #endif:
- #ifdef" directive checks whether particular macro is defined or not.
- If it is defined, "If" clause statements are included in source file. Otherwise, "else" clause
statements are included in source file for compilation and execution.
- In the below example1 macro is not defined. So, else part is executed.
Example: Example:
#include<stdio.h> #include<stdio.h>
int main() #define AGE 1
{ int main()
#ifdef AGE {
{ #ifdef AGE
printf("Eligible for voting\n"); {
} printf("Eligible for voting\n");
#else }
{ #else
printf("Not eligible\n"); {
} printf("Not eligible\n");
#endif }
return(0); #endif
} return(0);
}
Output: Output:
Not eligible Eligible for voting
undef
This directive undefines existing macro in the program.
In below program we first undefine age variable and again it is defined with new value.
Example: Undefining the macro Output:
#include<stdio.h> First define value for age is:
#define age 20 20

57
int main() Age after undef redefine is:
{ 30
printf("First defined value for age is: %d\n",age);
#undef age // undefining variable
#define age 30 // redefining age with new value
printf("Age after undef redefine is: %d",age);
return(0);
}

PART A:
1. What are variables? Give Examples (M/J’16)(N/D’14)
2. Define implicit type conversion (M/J’16)
3. What is an array? Give Example (M/J’16) (M/J’15)
4. Define strings. Give examples(M/J’16)
5. What is meant by linking process? (N/D’15)
6. What are the input functions and output functions in C? (N/D’15) (M/J’15)
7. Write a C program to store Fibonacci series in an array. (N/D’15)
8. List the string functions available in C. (N/D’15)
9. List some pre-processor directives. (N/D’15)
10. What are the importance of keyword in C? (M/J’15)
11. How is a character string declared? (M/J’15)
12. Give the use of pre-processor directives. (M/J’15) (N/D’14) (M/J’14)
13. Give an Example of ternary operator. (N/D’14)
14. Describe float array of size 5 and assign 5 values in it. (N/D’14)
15. Give an example for initialization of string array.
16. Define static storage class. (N/D’14)
17. List different data types available in C. (M/J’14)
18. Write a C program to find factorial of the number using iteration. (M/J’14)
19. Write an example code to declare two dimensional array. (M/J’14)
20. List any 4 string handling functions (M/J’14)

PART B:
1. Explain different types of operators in detail. (M/J’16) (M/J’15) (N/D’14)
2. Discuss basic data types in C (M/J’16)
3. Describe various input and output statements in detail. (M/J’16)
4. Write a C program for the following series 1+2+3+4+…N (M/J’16)
5. Write a C program to convert the number of vowels in your name (M/J’16)
6. Write a C program to multiply two matrices/ Write a C program for two 3*3 Matrix
(M/J’16)/(N/D’15) (N/D’14)
7. Write a C program to check whether the given string is palindrome or not (M/J’16)
8. Write a C program to arrange the given 10 numbers in descending order (M/J’16
9. Explain various storage classes in detail. (M/J’16) (N/D’15) (M/J’15) (M/J’14)
10. Describe about pre-processors with suitable examples. (M/J’16)

58
11. Describe the structure of C program using ‘calculator program’ example. (N/D’15)
12. Write short notes on branching statements in C. (N/D’15)
13. Write in detail about various looping statements with suitable example.(N/D’15) (M/J’15)
(N/D’14)
14. Write a C program to find determinant of the resultant matrix. (N/D’15)
15. Write the following programs (N/D’15)
(i) To sort the given set of strings alphabetically
(ii) To print whether each word is palindrome or not
(iii) To count the length of the string
16. What are constants? Explain various types of constants in C. (M/J’15)
17. Write a C program to solve(roots of) Quadratic Equation ((M/J’15) (M/J’14)
18. Write a C program to add two matrices. (M/J’15)
19. Write a C program to search a number in an array of elements. (M/J’15) (N/D’14)
20. Write a C program to arrange the given 10 numbers in ascending order/ Write a C program to
sort array of numbers. (N/D’14) (M/J’15) (M/J’14)
21. Explain various string handling functions in C. (M/J’15)
22. Explain various string operations. Write a C program to find the length of the string without using
build in function. (N/D’14)
23. Write a short notes on (i) #include<stdio.h> (ii) ifdef.. # endif (N/D’14)
24. Write a C program to check the given number is prime or not (M/J’14)
25. Write a C program to find sum of digits of a number (M/J’14)
26. Explain entry and exit checked conditional structure with example(M/J’14)
27. Write a C program to subtract two matrices and display the resultant matrix.(M/J’14)
28. (M/J’14)

***************

59

You might also like