You are on page 1of 45

DIPLOMA-CME PROGRAMMING IN C

UNIT-1

History of c language:

 C was developed by Dennis Ritchie at Bell Labs between 1969 and 1973.
 It evolved from an earlier language called B, which was developed by Ken Thompson in the late
1960s.
 C language was developed by Dennis Ritchie in 1970s at AT& T Bell laboratories, Murray Hill in

Languages Developed by Year

FORTRAN John Backus 1957

BCPL Martin Richard 1967

B Ken Thompson 1970

C Language Dennis Ritchie 1972

K and R C Dennis Ritchie & Kernighan 1978

ANSI C ANSI TEAM 1989

ANSI/ISO C ISO Committee 1990

Machine Language, The First Generation Language

 Scientists used to write small programs using machine language.

 Machine language is that low level language which the central processing unit executes.

 Machine language(or low level language) is known as the first generation language.

 Machine languages are hexadecimal numbers and these are very difficult to write and remember.

Assembly Language, The Second Generation Language

 Then after Machine language scientists came up with an idea of replacing machine code
instructions with the English words and thus assembly language came.
 Assembly language is called second generation language.
 Its own set of instructions for handling various operations such as displaying information on
screen, getting input from keyboard and performing various other jobs.
1|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

 Assembly language was a boon but writing a large program with lots of procedures was still
difficult.
 The assembly language is designed to represent various instructions only in symbolic code and is
more understandable than the low level language or machine language.

Higher Level Languages, The Third Generation Languages

 So Assembly language was a little bit difficult to understand, Because in the assembly language
there were a set of instructions for handling various operations.

 Scientists wanted to make a language independent of processor instructions.

 They wanted to create one of the language which uses mathematical expressions ,simple English
like English statements, and operators.

 This is the time of third generation programming language as we mentioned above C, BASIC,
Pascal, Fortran etc These are higher level languages and independent of processor architectures.

 All above mention C,BASIC, Pascal, Fortran come with compiler which convert the source code
into an intermediate code known as object code.

 Object codes are lower level code but not machine code.

 Then we also know computer understand machine code to convert the object code into machine
code assembler is used.

 Assembler convert object code to the machine code.


Features of c language

 C is middle level language.it has the simplicity of a high level language as well as the power of
low level language.
 The C makes it suitable for writing for both System programs and application programs.

 Thus c language features it is an Excellent, Efficient and general purpose language.

2|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

 Most of the application such as mathematical, scientific, business and system software
applications developed by C Language.

 The C language is extensible since it allows the users to add their own library functions to the
library
1. Portable
 The high Level languages are designing to keep in mind the features of portability.
 Portable languages are Machine independent.
 These languages are not tied with any hardware.
 So we can say it is hardware independent or platform independent

2. Extensible
 In c language features The C language is Extensible.
 Because it can adopt easily new features we can also add new libraries in c Language
3. Pointer

 C is the Very powerful language and Real Power of C lies in pointers using pointers
Accessing dynamically allocated memory and using pointer and we can directly interact with
memory using pointers implementing Data structure like linked lists,trees and graphs

4. Faster

 C is faster then other languages because of C has less in build functions its more closed with hardware.

5.Memory Management

 C support DMA(Dynamic memory allocation) we should able to allocate and de-


allocate memory at run time.

 The process of allocation memory at the time of execution is called Dynamic memory
allocation<

6.Rich Library

 C support number of libraries functions to build application fast.


3|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

7.Structure Language

 In c language features includes C is a structure language because it support modular approach .

 Its better to divide a large system into modules.

 In term of programming module is logically well-defined part of program .

 There are two types of structure follow in c.

1.Top-down Design
2.Button up design

structure of a C program

Importance of structure of a C program

 Sometimes, when we begin with a new programming language, we are not aware about the basic
structure of a program.

 The sections of a program usually get shuffled and the chance of omission of error rises.

 The structure of a language gives us a basic idea of the order of the sections in a program.

 We get to know when and where to use a particular statement, variable, function, curly braces,
parentheses, etc.

 It also increases our interest in that programming language.

Thus, the structure helps us analyze the format to write a program for the least errors. It gives better clarity
and the concept of a program.

Here, we will discuss the sections of a C program, some practical examples with explanations, steps
to compile and execute a C program.

Let's start.

The sections of a C program are listed below:

4|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

1. Documentation section.
2. Preprocessor section or Link Section.
3. Definition section.
4. Global declaration.
5. Main function.
6. User defined functions.

Documentation section

 It includes the statement specified at the beginning of a program, such as a program's name, date,
description, and title.

 It is represented as:

//name of a program or Programmer details ----------Single Comment Line.

Or

/*

Overview of the code ---------- Multi Comment Line.

*/

 Both methods work as the document section in a program.

 It provides an overview of the program.

 Anything written inside will be considered a part of the documentation section and
will not interfere with the specified code.

Preprocessor section Or Link Section.


 The preprocessor section contains all the header files used in a program.

5|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

 It informs the system to link the header files to the system libraries.

 It is given by:

#include<stdio.h>
#include<conio.h>

 The #include statement includes the specific file as a part of a function at the time of the
compilation.

 Thus, the contents of the included file are compiled along with the function being compiled.

 The #include<stdio.h> consists of the contents of the standard input output files, which contains
the definition of stdin, stdout, and stderr.

 Whenever the definitions stdin, stdout, and stderr are used in a function, the statement
#include<stdio.h> need to be used.

There are various header files available for different purposes. For example, # include <math.h>. It is
used for mathematic functions in a program.etc

Define section:

 The define section comprises of different constants declared using the define keyword.
 It is given by:

#define a = 2

Global declaration

 The global section comprises of all the global declarations in the program.

 It is given by:

float num = 2.54;


int a = 5;
char ch ='z';
6|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

The size of the above global variables is listed as follows:

char = 1 byte

float = 4 bytes

int = 2 bytes

We can also declare user defined functions in the global variable section.

Main function

 main() is the first function to be executed by the computer.

 It is necessary for a code to include the main().

 It is like any other function available in the C library.

 Parenthesis () are used for passing parameters (if any) to a function.

 The main function is declared as:

main()

 We can also use int or main with the main ().


 The void main() specifies that the program will not return any value.
 The int main() specifies that the program can return integer type data.

int main()

Or

void main()

 Main function is further categorized into local declarations,


statements, and expressions.

Local declarations

 The variable that is declared inside a given function or block refers to as local declarations.
7|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

main()
{
Int i = 2;
i++;
}

Statements

 The statements refers to if, else, while, do, for, etc. used in a program within the main function.

Expressions

An expression is a type of formula where operands are linked with each other by the use of operators.
It is given by:

a - b;
a +b;

User defined functions

 The user defined functions specified the functions specified as per the requirements of the user.
For example, color(), sum(), division(), etc.

 The program (basic or advance) follows the same sections as listed above.

 Return function is generally the last section of a code.

 But, it is not necessary to include.


 It is used when we want to return a value.
 The return function returns a value when the return type other than the void is specified with the
function.
 Return type ends the execution of the function.
 It further returns control to the specified calling function. It is given by:

return;

or

return expression ;

8|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

For example,

return 0;

Examples

Let's begin with a simple program in C language.

Example 1: To find the sum of two numbers given by the user

It is given by:

/* Sum of two numbers */


#include<stdio.h>
int main()
{
int a, b, sum;
printf("Enter two numbers to be added ");
scanf("%d %d", &a, &b);
// calculating sum
sum = a + b;
printf("%d + %d = %d", a, b, sum);
return 0; // return the integer value in the sum
}

Output

Enter two numbers to be added 3 5


8.

The detailed explanation of each part of a code is as follows:

/* Sum of the two It is the comment section. Any statement described in it is not considered
numbers */ as a code. It is a part of the description section in a code.
The comment line is optional. It can be in a separate line or part of an
executable line.

#include<stdio.h> It is the standard input-output header file. It is a command of the


preprocessor section.

9|Page LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

int main() main() is the first function to be executed in every program. We have used
int with the main() in order to return an integer value.

{………………..} The curly braces mark the beginning and end of a function. It is
mandatory in all the functions.

printf() The printf() prints text on the screen. It is a function for displaying
constant or variables data. Here, 'Enter two numbers to be added' is the
parameter passed to it.

scanf() It reads data from the standard input stream and writes the result into the
specified arguments.

sum = a + b The addition of the specified two numbers will be passed to the sum
parameter in the output.

return 0 A program can also run without a return 0 function. It simply states that a
program is free from error and can be successfully exited.

The C Character Set:


 To develop a program what fundament components are required those are called characteristics of C
 The classical method of learning English is to first learn the alphabets used in the language, then
learn to combine these alphabets to form words, which in turn are combined to form sentences and
sentences are combined to form paragraphs.
 Learning C is similar and easier.

Character set of C Language

 Letters : A to Z and a to z
 Digits : 0 to 9
 Special characters : *, @, # ......etc.
10 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

 White space characters: Enter key(\n), tab space key(\t), space key ( −), back
space key (‘\b’)....etc.

Keywords

 Keywords are the words whose meaning has already been explained to the C compiler.
 The keywords cannot be used as Identifiers because if we do so we are trying to assign a new
meaning to the keyword, which is not allowed by the computer.
There are only 32 keywords available in C.

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

Variables
 A variable is an identifier or a name which is used to refer a value.
 A variable is a name of the memory location where data is stored.
 Each variable in C has a specific type, which determines the size of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be applied
to the variable.

Rules for Constructing Variable Names

 A variable name is any combination of alphabets, digits or underscores


 The first character in the variable name must be an alphabet or underscore.
 Upper and lowercase letters are distinct because C is case-sensitive

11 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

 No whitespace is allowed within the variable name.

 In C Language, the variable can be Declare or declaration with initialization.


 If you declare a variable, that means you are asking the compiler to reserve a piece of memory
with that variable name.
 If you declare with initialize a variable, that means you are asking the compiler to reserve a piece
of memory with that variable name and store the data at reserved memory.

Variable Declaration in C

Syntax

datatype variable_name;

Example:

int id;
float bassal;

Variable Declaration with initialization

Syntax

datatype variable_name = constant_value;

Example:

int id = 5;
float bassal = 18000;

This type declaration is done at the beginning of the program.

Constant in c

12 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

Numeric Constant in C
 The Numeric constant consist of numerical digits.
 They may be without decimal point or may have decimal point(.).
 These are number of rules for defining numeric constants-
1. Numeric constant should have at least one digit.
2. There should be no comma or space is allow within the numeric constant for defining.
3. Numeric constant may be positive or negative but default sign of numeric constant is always be
positive.
Integers Constant in C

 There are three types of integer constant based on numbers systems such (decimal, octal,
hexadecimal) so here all are integer constants or integer types constants but based on number
system
 Decimal constants- 0,1,2,3,4,5,6,7,8,9 (base 10).
 Octal constants- 0,1,2,3,4,5,6,7 (base 8)
 Hexadecimal constants 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,a,b,c,d,e,f (base 16)

13 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

Invalid Remarks

8.5 Illegal Character(.)

67 9 No Black Space Allowed

86,55 Comma Not Allowed

05546 First Digit Can Not Be Zero

809#55 Illegal Character (#)

lets us see some valid decimal integers constants are-

0 156 8765 3459 66558

Here are some invalid decimal integers constants are in the below example-

let us see some valid octal integers constants and take example, first digit must be 0.

0 0156 0765 08 0558

let us see and take example of some valid Hexadecimal integers constant, first two characters should be
0X or 0x. some examples are

0X89 0x6653 0X98FBC 0xAAABM 0Xabm

14 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

Real(Floating point) Constant in C

The Invalid Remarks Floating


point constant
are ‘lion’ There should be only one character within quotes numeric
number constant
with decimal
“N” Double quotes are not allowed
point. Here take
example of some
floating X single quotes missing point
constants –

” There is no character between single quotes


0.9 3.459 6655.8 100.6 5.2 99.33

Character Constant in C

The character constant is the single character that is enclosed with in the single quotes. here are
some valid character constants are-

15 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

Note: Every character has unique integer value. so every associated value or integer value is
machine code such as ASCII(American standard code for information interchange). its depend on
machine if machine using ASCII then A character represent by 65

Here are Some ASCII values are-

A-Z ASCI value(65-90)

a-z ASCI value(97-122)

0-9 ASCI value(48-57)

; ASCI value(59)

String Constant in C

A string Constant is a group of characters enclosed within double quotes(“”). At the end of string
the complier automatically placed null character (‘\0’). Here are some examples of String constants-

“Saraswat”
“Nitish”
“897”
“5”
”“
“,”
16 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

Symbolic Constant in C

 If in program we want to use constant as several times, we can given it a name.

 Such as if we use 3.1414587 at many times in a program.

 We can give it a name PI, and uses it name PI .

 Where we need instead of writing the constant value anywhere.

 These types of constant are known as Symbolic constant.

#define PI 3.141567
#define name “Nitish”
#define CH ‘c’

Data types in c
 Data types in c programming, A data types defines a domain of allowed values and the what type
of values will be store and what types of operations performs.
 Storage represents every different data types with different memory blocks.
 In C languages there some data types predefined, Derived, Enumeration, void

17 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

The C language supports following types of Data types

Types Data Types

Basic Data types int, char, float, double

derived Data types Array, pointer, union, structure

Enumeration Data types Enum

Void Data types void

Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:

Floating point type

Floating types are used to store real numbers.


Size and range of float type on 16-bit machine:
18 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

Character type

Character types are used to store characters value.


Size and range of character type on 16-bit machine

 So int is use to stored integer type value, char is used to store any single character, float is use for
storing single precision floating point number and the last is double are use for
storing double precision floating point number. These basic data types also divides into two types–
1. Size qualifiers short, long
2. Sign qualifiers signed, unsigned
Talk about the qualifiers signed and unsigned are apply to char and integers types.

 Data types in c programming, when the qualifier signed is use store number may positive or
negative, and when the qualifier is unsigned is used the number will always positive.

 If there is explicitly sign qualifier is not mention in integers, then the default signed qualifier is
assume and for the char if sign qualifier is not mention explicitly.

 Then the char is signed and unsigned depend on machine.


19 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

 Talk about range the range of values of the signed data types are less than that of unsigned type.

 The qualifiers long and short we can be apply to int type to get types short int and long int.

 And the qualifier long we can applied to double to get type of long double.

 And the sizes and range of different different data types on a 16-bit machine is given in this table.
The size and range may be vary on machine by machine

Data types Memory Size(bytes) Range


Char
Signed Char 1 byte -128 to 127
Unsigned Char 1 byte 0 to 255
Int
Int or signed int 2 byte -32768 to 32767
Unsigned int 2 byte 0 to 65535
Short int or signed short int 1 byte -128 to 127
Unsigned short int 1 byte 0 to 255
Short int or signed short int 1 byte -128 to 127
Long int or signed long int 4 byte -2147483648 to 2147483647
Unsigned long int 4 byte 0 to 4294967295
Float 4 byte 3.4e-38 to 3.4e+38
Double 8 byte 1.7e-308 to 1.7e+308
Long double 10 byte 3.4e-4932 to 1.1e+4932

Scanf in C
 The Input Data can entered into the memory from a standard input device(Keyboard).
 There is scanf() library function are use for entering input data in c.
 This Scanf() can take All data types of values like(Numerical, character, string) as input. The
scanf() function read the data input data from console.
 The scanf() function can written as–

scanf("control string",address1,address2,......);

 Scanf function in c programming or reading input data in c, in This scanf() function should have at
least two parameters.
 The first parameter is a control string which is know conversion specification character.
 It should be in double quotes.
 The conversion specification characters may one or more than one.

20 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

 It depend on user want to numbers of variable inputs and the others parameters are addressed of
variables.
 In the scanf() function at least one address should inside.
 The address of the variable is represent by preceding the variable name and follow by an
ampersand (&) sign.
 This sign is know as address operator and its gives the starting address of the variable in memory.
Example–

int main()

int age=18;

scanf("%d",&age);

 In this example. in the first parameter control string contains only one conversion specification
character %d, which indicates that only one integer value should be enter as input

int main()

char grade='A';

scanf("%c",&grade);

 In this example in the first parameter contain conversion specification character %c.
 which means the single character should be enter as input.
 This value stored in the grade variable. for example-

21 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

In the
float salary=300.60; above
scanf("%f",&salary);

example first parameter control string contains the conversion specification character %f, which means that
floating point any number input as user input this entered value will be stored in salary variable

char str[30]

scanf("%s",&str);

In the above example first parameter conversion specifier %s indicates the String should be input. and its
stored in the str variable which is string type. we can use ampersand (&) or without ampersand (&) before
the variable More then one value we can stored using scanf() function there is some examples —

#include<stdio.h>

void main()

int salary,age;

scanf("%d%d",&salary,&age);

void main()

char grade='A',int salary=1000;

scanf("%c%d",&grade,&salary);

void main()

22 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

char grade='A',int salary=1000;

float average=89.67;

scanf("%c%d%f",&grade,&salary,&average);

//SCANF() function Example

#include<stdio.h>

int main()

int fnum;

printf("What is your Lucky number:");

scanf("%d ",&fnum);

printf(" %d is my Luck number,",fnum);

return (0);

What is your Lucky number: 6


6 is my Lucky number,

Printf in c
 Output data can be written from user input or from memory to the console and output
device(monitor) using printf() library function.

 With printf() function all types of values such as(numerical,character or string)can be written as
output the printf() function can be written as–

23 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

printf("control strings",variable1,variable2,variable3......);

 In C printf() function | writing output in c, in this printf() function, the first control string contains
conversion specification characters and text.
 The first control string should be enclosed with in double quotes.
 In the second part the variables not followed by an ampersand(&) sign.
 If the control string does not contain any conversion specification, the variables name not
specified. Here is some Examples–

int main()
{
printf(″C language has powerful tools″);
}

 In this example. In the printf() function the control string contains only text and no conversion
specification characters, so the output will be only text that written in the printf()

int main()

int marks;

printf("Enter the marks");

scanf("%d",&marks);

Enter the marks 100

 In this above example the printf() function does not contain any conversion specification character.
its contains only text to print so its used to display message. And tell to user to enter marks –

24 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

float salary=300.60;

printf("%f",salary);

 In the above example first parameter control string contains the conversion specification character
%f, which means that floating point value will be display. The variable salary has floating value
to display as output

char str='A';

printf("%c",str);

In the above example first parameter conversion specifier character %c. That means a single character will
be display and variable str has that character value

#include<stdio.h>

void main()

char name[10]="Nitish";

printf("%s",name);

Output

Nitish

In the above example first parameter conversion specifier character %s indicates that string will be display
and variable name is the type of character array that stored the string which will be display.

25 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

#include<stdio.h>

void main()

char name[10]="Nitish";

float average=90.7;

int roll;

printf("%s %f %d",name,average,roll);

Output

Nitish 90.699997 4195504

Identifiers in c
 C identifiers , All the words we will use in the C language will be either keywords or identifiers.
 The keywords are predefined words that cannot changed by the users and C Identifiers are user
defined words and are use to give names to entities like variables, functions, array, structures,
union etc. Rules for Naming identifiers giving—-
 C identifiers represent the name in the C language, for example, functions, arrays, structures
variables, labels unions, etc.

 It is a composed of letters such as lowercase, uppercase letters, digits and underscore, but the
starting letter should be either an alphabet or an underscore not the any digit.

 If identifiers not used in the external linkage, then it is known as an internal identifier.

 And whenever the identifier is used in the external linkage, then it is known as an external
identifier.

The Rules for Naming C Identifiers are giving below-

26 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

(1) The name should consist of only uppercase. lowercase, digits and underscore(_).
(2) The name should not be a keyword(reserve word)
(3) The first character should be an alphabet or underscore.
(4) Commas or blank spaces cannot be specified within an identifier.
(5) It should not start with any numerical digit.
(6) The length of the identifier should not be more than 31 characters.
(7) The C is a case sensitive. so the lowercase and uppercase considering different so for example program
and PROGRAM are different.

Some valid Identifiers examples are

number Amount_pay reg1 _data AVERAGE

Some Invalid Identifiers examples are-

6number int reg# 4data AVERAGE no

Difference between C Identifiers and keywords-

Identifiers Keywords

Identifiers are the user defined words Keywords are the pre-defined words. That
have a special meaning

It can be written in both case lowercase It must be written in a lowercase letter


and uppercase

It can contain underscore, number, It does not contain the underscore character
characters and numbers

Operators:

 For perform any task the variables, constants can joined by various operators to form
an expression.
 There are operands.
 Operands is a data item on which an operators acts.

27 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

 There are some operators required two operands and some operators required only
one operand.
 The c language support larger number of operators that are mentioned below with
several different categories operators in c programming

Operators are giving below-

(1) Arithmetic operators


(2) Assignment operators
(3) Increment and decrement operators
(4) Relational operators
(5) Logical operators
(6) Conditional operators
(7) comma operators
(8) sizeof operator
(9) Bitwise operators
Arithmetic operators in c:

The Arithmetic operators are used for numerical calculations such as addition, subtraction,
multiplication, division etc

1. Unary arithmetic operators


2. Binary arithmetic operators

Unary arithmetic operators

The unary operators are required only one operand. See in the below example

++x, –y, x++, y–

28 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

Binary Arithmetic operators in C

The binary operators require two operands So there are five binary operators in c. show in the below

Serial no. Operator Purpose

1. + Addition

2. – Subtraction

3. * Multiplication

4. / Division

5. % Modular

% Is modular operator which gives the remainder of the integer. Modular operator can not apply with floating
point operands. Here is one thing note that unary minus and plus operators are different from the addition and
subtraction operators. When both operands are integers, then the resulting value always will be integer let us
take example there are two operands x is 19 and y is 8, then the result of the following operations are-
Expression Result

x+y 27

x-y 11

x*y 152

x/y 2(decimal part remove)

x%y 3(remainder after integer division)

In the above example in the division operation the decimal part will be truncated then the result will be only
integer part of quotient.after modular operation in the result the remainder part of integer division. In the
modular operation the second operand must be non zero for modular and division operations.

/* Integer arithmetic operations*/


#include< stdio.h >

29 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

void main()
{
int x=19,y=8;
printf(“subtraction is=%d”,x-y);
printf(“\n addition is =%d”,x+y);
printf(“\n multiplication is =%d”,x*y);
printf(“\n division is =%d”,x/y);
printf(“\n remainder is =”,x%y);
}

output: subtraction is=11


addition is =28
multiplication is =152
remainder is =3

Assignment Operators In C:

 The values stored in any variable or in any operand using assignment operator.
 The operand on the left hand side should be variable where value will be assigned,
while on the right hand side the operand can any variable, constant or expression.
 So the value of right hand side will assign to the left hand side operand.
 Here in the below some examples of assignment expressions –

a=9 /*9 is assign to a*/


b=10 /* 10 is assign to b*/
c=a+b-1 /* value of a+b-1 is assigned to c*/
c=b /* value of b is assigned to c*/

30 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

We can have multiple assignment operators also for example–

a=b=c=50

Here in the above example all the three variables a,b,c will be assign 50. and the value of
the complete expression will be 50

There are some examples are given below of assignment operators-

a=a+9 can be written as a+=9 /*a+9 is assign to a*/


b=10*b can be written as b*=10 /* b*10 is assign to b*/
c=c/10 can be written as c/=10 /* value of c/10 is assigned to c*/
c=c-5 can be written as c-=5 /* value of c-5 is assigned to c*/

Increment and Decrement operators in C:

 The (++) increment and (–) decrement both operators are unary operators because of
both operators operate on a single operand.
 The increment operator increments the value of any variable by 1 and decrement
operator decrements the any variable value by 1.
 Here in the below there are some examples –
is Equivalent to a=a+1
++a

–a is Equivalent to a=a-1

 These opearators should be used used only with variables.

 These opearators can not be used with constant and expression here in the below are

example we can not use increment and decrement like this–

++9 or ++(a+b+c) are invalids

31 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

These opearators are two types


1. prefix increment/decrement
2. postfix increment/decrement

prefix increment/decrement

 In the prefix increment or decrement operator is written before the operand(e.g. ++x
or –x) here first the value of variable is increment/decrement then the new value is
used in any expression or operation.

 Let take example to understand the concept of prefix

example statement a=++b;


means first the value of variable is increment by one then assign the value of b to the variable a.
This statement is equivalent to these two statements

b=b+1;
a=b;

The statement a=- -b; means first decrement the value of b by one then assign the value to a This statement is
equivalent to these two statements

b=b-1;
a=b;

Now take the example of prefix increment and prefix decrement.

#include< stdio.h >


void main()

32 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

{
int a=7;
printf(“a=%d\t”,a);
printf(“a=%d\t”,++a); /*prefix increment*/
printf(“a=%d\t”,a);
printf(“a=%d\t”,–a); /*prefix decrement*/
printf(“a=%d\t”,a);
}

Output a=7 a=8 a=8 a=7 a=7

Postfix Increment/Decrement

 Here first the value of variable is used in the operation and then increment or
decrement will be perform.

 Let us take example here x is variable whose value is 5

 The statement y=x++; statement means the first the value of x is assign to y then
value of x is increase by one.

 This statement is equivalent to these two statements-

y=x;
x=x+1;

 Now in this above example value of x is 6 and value of y is 5.

 As the same the statement y=x–; means first the value of x is assigned to variable y
then value of x will decrease by one.
33 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

 This statement is equivalent to these two statements –

y=x;
x=x-1;

#include< stdio.h >


void main()
{
int x=7;
printf(“x=%d\t”,x);
printf(“x=%d\t”,x);
printf(“x=%d\t”,x–); /*postfix decrement*/
printf(“x=%d\t”,x); }

Now the value of x will be 4 and y will be 5

OUTPUT : x=7 x=7 x=8 x=8 x=7

Relational operator in c

 Relational operators are used to compare values of two expressions.


34 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

 An expression that contains relational operators is known relational expression or


called relational expression.
 If there is relation is true then the value of relational expression is 1 if relation is
false then the value of expression is 0. There are some relational operators are- –

Operators Meaning

< Less than

<= Less than or equal to

== equal to

!= Not equal to

> Grater than

>= Grater than or equal to

Lets us take example with applying relational operators let us take two variables x=10 and
y=8 and form simple relational expressions with them–
Expression Relation Value of Expression

x<=y false 0

x<=y False 0

x==y False 0

x!=y True 1

x>y True 1

x>=y True 1

x==0 False 0

y!=0 True 1

X>1 True 1

35 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

10<20 True 1

 Generally the relation operators are used with in the if else statement and loops so
now we will used relational operators with if else statement in the next program to
understand.
 If the control statement evaluates any expression and that expression is true or (non
zero) then the next statement is evaluated or executed .
 Otherwise the next statement is skipped or not show so in the below discussed
program with relation operator

/*Program to understand the use of relational operators*/

#include<stdio.h>

void main()

int x,y;

printf(“Enter the value of x and y”);

scanf(“%d%d”,&x,&y);

if(x>y)

printf(“%d is grater then %d\n”,x,y);

if(x>=y)

printf(“%d is grater then or equal to %d\n”,x,y);

if(x==y)

printf(“%d is equal to %d\n”,x,y);

if(x!=y)

36 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

printf(“%d is not equal to %d”,x,y); }

Logical operators in c
 When an Expression that combines two or more expressions is know as logical
expression.
 To combining these expressions we use logical operators.
 This logical operator return 0 for false and 1 for true.
 The operands may be constant, expressions or variables .
 In c language there are three logical operator –

Operator Name

&& AND

|| OR

! NOT

 Here in this example NOT is a unary operator while the others two OR, AND are
binary operators.
 Before using These operators let us understand the concept of these operators of true
and false.
 In c language any non zero value regarded as true and the zero is regarded as false.

AND (&&) operator:

 This operators gives the net result true if both condition will be true, Otherwise
result will be false.
 Let us see Example

Boolean Table

37 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

Condition1 Condition2 Result

True True True

True False False

False False False

False True False

Expression Result Value of Expression

(a==18)&&(c>b) false && false false 0

(a==15)&&(a>b) true && true true 1

(a>b)&&(b>c) true && true true 1

a&&c true && false false 0

 Let us understand the concept of AND operator.


 Let us take three variables a=15, b=6,c=0 let us take expression and results in the
last row example the expression a&&c we have take only variables a and c.
 Since non zero value is regarded as true and zero value is regarded as false, so in this
example variable a considered as true and variable c is considered as false.

OR (||) Operator

 This OR operator gives the result false. if both conditions have the value false.
 Otherwise the result is true
38 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

Boolean Table

Condition1 Condition2 Result

True True True

True False False

False False False

False True False

Let us understand the concept of OR operator. so take three variables a=20, b=15, c=0;

Expression Result Value of Expression

a || b true || true true 1

a || c true || false false 0

(a<5 || (c>b) false || false false 0

(a!=b) || c true || false false 0

NOT (!) Operator

 This is a Unary operator and its negates the values of any condition.
 So if the value of the condition is false then it gives the result true.
39 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

 And the value of condition is true then it gives the result false.
 So now understand the concept of NOT operator.

Boolean Table

Condition Result

True false

false true

Let us understand the concept of NOT operator

Expression Result Value of Expression

!a !true false 0

!c !false true 1

!(a>b) !true false 0

!(b&&c) !false true 1

Conditional Operator In C:
 Conditional operator is a ternary operator (? and ::) which is required three
expression as operand let us take example its written as –

Testexpression? expression1 : expression2

40 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

1. If Testexpression is true(non zero), then only expression1 is evaluted and it becomes


print all the values of this conditional expression
2. If Testexpression is false then expression2 is evaluted and it becomes all the values of
this conditional expression.

lets us take conditional expression

x>y is evaluated if the value of this condition expression is true then the value of variable x
will be value of conditional expression otherwise the value of y becomes the value of
conditional expression

Let us take example to understand the concept of conditional operator.

let us suppose x=6 and y=10 and now we are using above conditional operator.

Result=x>y ? x : y;

Here in the example the first expression x>y is evaluated so here in the x>y condition it is
false so the value of y variable becomes to the condition expression and finally its assign to
the result variable

So now let us take example of Conditional operator with program

\*program to print the larger number from two numbers*/


# include < stdio.h >
int main()
{
int x,y,larger;
printf(“Enter first number \n”);
scanf(“%d”,&x);
printf(“Enter second number \n”);

41 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

scanf(“%d”,&y);
larger=x>y ? x : y;
printf(“The larger number is %d”,larger);
return 0;
}

Output :

Enter first number 15.


Enter Second number 10.
The larger number is 15.

Comma operator in c:

 The comma operator ( , ) is used to permit different expression or separate difference


expression to appear in situation where only one expression will be used.
 The every expression are separated by the comma operator.
 And these separated expression are evaluated from left to right.

Let us understand the concept of comma operator with example-

a=8, b=5, c=9, d=10, e=a+b;

 In the above example we have combined 5


 Expressions. in the right or in the initially 8 assign to variable a, then 5 is assign to
b, 9 is assign to c, 10 is assign to d, and in the last e=a+b is expression evaluated
which assign value of whole expression to the variable c.
 result=(a=8, b=5, c=9, d=10, a+b+c+d);
The value of above expression will be 32. Now consider this statement
 In the above example whole expression assigned to the right variable result.
42 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT
DIPLOMA-CME PROGRAMMING IN C

 So the variable result assigned value 32.


 So we know precedence of comma operator is lower than the assignment operator.
 So here used of comma operator make the code more compact.
 So in this example show without the comma operator the above statement have been
in five statements

a=8;
b=5;
c=9;
d=10;
result=a+b+c+d;

/* program to understand the use of comma operator*/


#include< stdio.h >
int main()
{
int a,b,c,d,e,result;
result=(a=8, b=5, c=9, d=10, a+b+c+d);
printf(“result=%d\n”,result);
return 0;
}

Output:
result = 32

C control statements

Control Statements

43 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

 In c programming, statements are executed sequentially or step by step in the order in which they
are write in the program.
 Sometimes i want executes some parts of program on the basis of conditions.
 Also some times many situations arise where we want to use any statement or some statements
several times.in all these conditions the control statements are use.

Types of Control Statements in C


The primary types of control statements in C are:

 Decision-Making Control Statements


1. Simple if statement
2. If-else statements
3. Nested if-else statements
4. else-if ladder.
 Conditional statements

 Goto statements in C

 Loop control statements in C


1. While Loop
2. Do-while Loop
3. For Loop

Simple if Statement

 Simple if statements are carried out to perform some operation when the condition is
only true.
 If the condition of the if statement is true then the statements under the if block is
executed else the control is transferred to the statements outside the if block.

Syntax of the if statement is as given below:

If (Condition)
{

44 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT


DIPLOMA-CME PROGRAMMING IN C

Statement-1;
}

Flow Chart:

https://www.simplilearn.com/tutorials/c-tutorial/conditional-control-statements-in-c

45 | P a g e LOYOLA INSTITUTE OF TECHNOLOGY & MANAGEMENT

You might also like