KEMBAR78
UNIT 1 Notes | PDF | Variable (Computer Science) | Integer (Computer Science)
0% found this document useful (0 votes)
16 views72 pages

UNIT 1 Notes

The document provides an introduction to C programming, covering problem-solving techniques, programming paradigms, and the structure of a C program. It details the features of C, its applications, and the fundamental concepts such as data types, variables, and identifiers. Additionally, it explains the syntax and components of a C program, including the main function, comments, and variable scope.

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)
16 views72 pages

UNIT 1 Notes

The document provides an introduction to C programming, covering problem-solving techniques, programming paradigms, and the structure of a C program. It details the features of C, its applications, and the fundamental concepts such as data types, variables, and identifiers. Additionally, it explains the syntax and components of a C program, including the main function, comments, and variable scope.

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/ 72

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.

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

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.

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>

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

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.

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
Of An Assignment Operator. following: 1.Variable
For Example: Mark=20; // 2.Function
The L- Value Should Be A Variable. 3. Constant
Eg,
num=20; //constant R value

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 Output:
gloab 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);}

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 to32767

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,648to2,147,483,647

unsigned longint 4 0 to4,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.
Float 4 3.4

Double 8 1.

longdouble 10 3.4
Character type
Type S
- 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’;
char or signed char 1 -128 to

unsigned char 1 0 to25


void type
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 It is used to
accepts both accepts only type occupies increase the size of
negative or positive positive values. different memory the current data
value. spaces for a different type to 2 more
.(It is the default operating system; bytes.
integer data type). To allocate fixed
memory space short
keyword can be used.

Example: Example: For example: For Example:


signed int unsigned int rate; short int a; long int a;
number; 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 Example 2:
enum datatype): #include<stdio.h>
#include<stdio.h> main()
main() {
{ enum
enum month{JAN, month{JAN,FEB=5,MARCH
FEB, MARCH, ,A PRIL=2, MAY,JUNE=3,
APRIL, MAY}; enum JULY};
month m1; enum month m1;
m1=APRIL;

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


#include<stdio.h> typecasting) #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 printf("%f\n", sum );
as 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
stored in float variable to float and float value(quotiemt) is
printf("%f",z); stored in 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 Output:


class. #include<stdio.h> 3
int main() 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.
- Theyhave tobe 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 Output:


class #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 =


printf("%d",a); 10; const int WIDTH =
a=20; 5; 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

Opera Description Eg Program Output:


to r

+ adds two operands a+b #include<stdio.h> 13


int main() -3
- subtract second operands a-b { 40
from first int a=5,b=8; 0
printf("%d\n",a+ 40
* multiply twooperand a*b
b);
/ divide numerator by a/b printf("%d\n",a-b
denominator, gives quotient as );
result printf("%d\n",a*
b);
% dividenumeratorbydenominat a%b printf("%d\n",a/b
or, givesremainder asresult );
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

= assignsvaluesfromrightsideoperandstoleftside operand a=b

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

-= subtracts right operand from the left operand and assign a-=bissameas a=a-b
the result to left operand

*= multiply left operand with the right operand and assign a*=b is same as
the result to left operand a=a*b

/= divides left operand with the right operand and assign the a/=bissameas a=a/b
result to left operand

%= calculate modulus using two operands and assign a%=b is same as


the 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;
c=5
printf("c=%d \n", c);
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. 0


h> int main() 0
!= Check if two operand are not equal. { 1
int a=5,b=8; 0
> Check if operand on the left is
printf("%d\n",a== 1
greater than operand on the right
b); 1
< Check operand on the left is printf("%d\n",a>b)
smaller than right operand ;
printf("%d\n",a<b)
>= check left operand is greater than or ;
equal to right operand printf("%d\n",a>=
b);
<= Check if operand on left is smaller
printf("%d\n",a<=
than or equal to right operand b);
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.
O Description Example a=5, b=2
p

era
tor

&& 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
for evaluation of the expression. it 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
for evaluation of the expression. it 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;
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);
printf("%d\n",--i); return(0); return(0);
} } }
Output: Output: Output:
10 x:11 x: 10
12 i:11 i: 11
12
10

Special Operator:
Operator Description Example

Sizeof Returns the size of an variable sizeof(x);

& Returnsthe 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
int a;float b;char c; is 1
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 Example 2: Use of ternary operator
ternary 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"))); return(0);
printf("%d\n",b);return(0); }
} Output:
Output: a is less
2

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: Thisrule decidesthe orderinwhich 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
sizeof Determine size in bytes on
this implementation

24

*
Multiplication
left-to-right
/
Division
%
Modulus

+ Addition left-to-right
- Subtraction

< Relational less than left-to-right


<= operator 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 int a=
a=? a=2*3.25+((3+6)/2) +6 a=? 5+7*4-9*(3,2) 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 a=2,b=12,c=1 find m=?


:3 b=? d=a<b>c m=-43||8&&0||-2
b=24+3*4<3?4: d=2<12>1 d=1>1 m=-43||0||-2
3 d=0 m=1||-2
b=24+12<3?4:3 m=1
b=36<3?4:3
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: Output:
#include<stdio.h Enter two numbers:
int main() 2
{ 2
int a,b,c; Sum of entered
printf("Entertwo numbers:\n"); numbersis 4
scanf("%d%d",&a,&b);
c = a + b;
printf("Sumof entered numbersis %d\n",c);
return(0);
}

Program to print student details: Output:


#include<stdio.h> enter the roll no,mark1,
int main() mark2,mark3,name
{ 1001 95 85 95 george
int rollno,m1,m2,m3; Roll no is 1001
char name[20]; Name is george
float total,percentage;

29

printf("enter the roll Marks Obtained is


no,mark1,mark2,mark3,name\n"); 958595 total marks is
scanf("%d%d%d%d%s",&rollno,&m1,&m2,&m3,na 275.000000 percentage
me ); 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
int main() and b 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 Output:


variable: #include <stdio.h> Enter the value of a
int main() and b 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
int main () x1,y1: 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 This function prints one character on the
till the user presses the enter key. screen at a time, which is read by standard

31

Syntax: input.
variable name=getchar(); Syntax:
Example putchar(variable_name);
char c; Example:
c=getchar(); char c;
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 from It displays any alphanumeric characters to
keyboard. the standard output device. It displays only
- getch() function will just wait for any one character at a time.
keyboard input (and press ENTER). It Syntax:
won’t display the given input character in putch(variable_name)
output 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
spaces from the standard Input device the standard output device.
(keyboard). Syntax:
-gets() stops reading character from puts(variable_name);
keyboard only when the enter key is Example:
pressed. char name[25];
Syntax: puts(name);
gets(variable_name);
Example:
char name[25];
gets(name);
Program to read and print the string using
gets and puts:
#include<stdio.h>
main() Output:
{ enter the string
char name[20]; hello my friend
printf("enter the string\n"); hello my friend
gets(name);
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 Unformatted input/output can deal with one
can 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 Output


200 will deducted from purchase.
#include<stdio.h> enter the purchase
int main() value50000 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


int main( ) numbers 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: Output:
#include <stdio.h>
int main() Enter a year
{ 2016
int year; leap year
printf("Enter a year\n");
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> enter 3 numbers


int main( ) 6
{ 8
int a,b,c; 1
printf("enter 3 numbers\n"); 8 is greatest
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
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 Output:


marks #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
float x1,x2; diff First Root x1=
printf("enter the value of a,b & c\n"); -1.236068 Second Root
scanf("%d%d%d",&a,&b,&c); x2= 3.236068
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 Output:
numeric or alphanumeric(using character Build-in Enter any key
functions) #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 Output:


or alphanumeric(using print, scanf statements) enter a single character
#include<stdio.h> or 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
codeswillget executedafterthematchingblock.
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
isnobreak statementaftertheblock,thenextblocksareexecuted,untilthe cursor encounters a break.
Rules for switch Statement:
o Default case is optional andcanbeplaced anywhere inthe switchcase. But Usually we place it at
the end.

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 March
month\n"); 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
printf("Enter the values of a & b: "); a & 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: Output:
#include<stdio.h> Enter three subject
int main() Marks95
{ 94
int m1,m2,m3,gpa; 96
float tot, avg; grade=A
printf("Enter three subject Marks");
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 ofloop body,conditionis verified, andifitisfoundtobe true the loop body is
executed again.When the condition check returnsfalse, the loop body is not executed. There are
3 type of Loops in C language
forloop
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
the loop is executed. condition 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 Output:


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


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

Conditionistestedfirstandthen statements Statements are executed at least


are 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 Output:


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


10: #include<stdio.h> numbers squares
#include<math.h> 11
int main() 24
{ 39
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:
forloopisusedtoexecuteasetofstatementsrepeatedlyuntilaparticularconditionis 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 3
printed:"); 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:


#include <stdio.h> 10 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 are: 2
factors\n"); 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 Output:


not: #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
if(n%i==0) that has only 2 states (0 and
{ 1)
flag=0; Eg, On/Off, True/False,
break; Yes/No
}
}
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 Output:


for: #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
statementimmediatelyfollowingthe 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 Output:
print numbers: to print numbers:
#include <stdio.h> enter the enter the
int main() number: #include <stdio.h> number: 10
{ int main()
10 1 1
int i,num; {
2 2
printf("enter the number: int i,num;
"); 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"); {
8
break; printf("skipped\n");
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
controloftheprogramtooutsideloopor of the loop and moves to the next
switch case statement. iteration in 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
transferringcontrolto some other part ofthe 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
∙ Conditionalcompilation 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 The macro defined within


constants more complex another macro is called nested
expressions 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
#define age 20 is: 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