0% found this document useful (0 votes)
26 views162 pages

Basics of Comp CHP 1

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

Basics of Comp CHP 1

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

CSIC101-PROBLEM

SOLVING AND
PROGRAMMING USING
C

By:-
Dr. Amandeep kaur
Assistant Professor
Department of Computer Engineering
Father of Computer
by Tim Cranmer
A lady who introduced
programming in computer.
• Computability and non-
computability
• In 1936 Alen Turing
figured which problems
can be solved using
computer.
• Also known as Father of
Computer Science and
Artificial Intelligence.
Computer Hardware:
• Hardware refers to the physical
components of a computer.
• Computer Hardware is any part
of the computer that we can
touch these parts.
• These are the primary electronic
devices used to build up the
computer.
• Examples of hardware are:
Processor, Memory Devices,
Monitor, Printer, Keyboard,
Mouse, and Central Processing
Unit.
Types of Computer Hardware
• Input Devices: Input devices are those devices through which a user enters data and
information into the Computer. Examples: Keyboard, Mouse, Scanner, etc.
• Output Devices: Output Devices are devices that are used to show the result of the task
performed by the user. Examples are Monitors, Printers, Speakers, etc.
• Storage Devices: Storage Devices are devices that are used for storing data and they are
also known as Secondary Storage Data. Examples are CDs, DVDs, Hard Disk, etc.
• Internal Component: Examples are the CPU, Motherboard, etc.
Types of Computer Software
• System Software: System Software is a component of Computer Software that
directly operates with Computer Hardware. The system software is a collection of
programs.
• designed to operate, control, and supports the process of computer
• System software –Inbuilt in System
• System software written in low-level languages
• Use to Interact with the hardware and software
• It serves as the interface between the hardware and end users
• Examples: Operating System, Language processors, Compilers, Interpreter,
Assemblers, and Device Drivers etc..
Contd…
• Application Software: It is a collection of programs, often called a
software package, which work together to accomplish user task.
• Application Software are the software that works the basic operations of
the computer.
• It performs a specific task for users.
• Application Software basically includes Word Processors, Spreadsheets,
Student Record Software , Income Tax Software and Railways
Reservation Software, Customized Software, Microsoft Office Suite
Software, Microsoft Word, Microsoft Excel. Microsoft PowerPoint etc.
Parameter System Software Application Software
System Software is the type of software which is Application Software is the type of software which
Definition the interface between application software and runs as per user request. It runs on the platform
system. which is provide by system software.
Development System software are developed using low-level Application software are developed using high level
Language language language.

System software are essential for operating the Application software are not essential for the
Necessity computer hardware. Without these software, a operation of the computer. These are installed as per
computer even may not start or function properly. the user’s requirements.

System software is used for operating computer Application software is used by user to perform
Usage
hardware. specific task.

System software are installed on the computer Application software are installed according to
Installation
when operating system is installed. user’s requirements.

System software can run independently. It An application software cannot run independently.
Dependency provides platform for running application It cannot run without the presence of system
software. software.

Examples of system software include operating


Examples of application software include word
Examples systems, compilers, assemblers, debuggers,
processors, web browsers, media players, etc.
drivers, etc.
Parameters Hardware Software
Hardware is a physical part of the
Software is a set of instructions that tells a
Basic Definition computer that causes the processing of
computer exactly what to do.
data.

Hardware cannot perform any task The software can not be executed without
Dependency
without software. hardware.

Electronic and other materials are used to Created by utilizing a computer language to
Process of creating
create hardware. write instructions.

Hardware is tangible as hardware is a


Software is intangible as we can see and also
Tangible physical electronic device, that can be
use the software but can’t touch them.
touched.

The software does not wear out with time.


Durability Hardware typically wears out over time.
However, it may contain flaws and glitches.

It has four main categories:


1. Input Devices It is mainly divided into
Types 2. Output Devices 1. System software
3. Storage Devices 2. Application software.
4. Internal Components.
Parameters Hardware Software

Virus effect Hardware is not affected by computer viruses. Software is affected by computer viruses.

It cannot be transferred from one place to another


Transfer It can be transferred via a network means.
electrically through the network.

The program accepts human-readable input,


Machine-Level Only machine-level language is known to be
interprets it in machine-level language, and
language understood by hardware.
sends it to hardware for additional processing.

If the hardware is damaged, it is replaced with a new If the software is damaged, its backup copy can
Replacement
one. be reinstalled.

Overloading, systematic error, major-minor


Dust, overheating, humidity, and other factors are
Failures version error, and other factors are commonly
commonly responsible for hardware failures.
responsible for software failures.

Ex: Keyboard, Mouse, Monitor, Printer, CPU, Hard Ex: MSWord, Excel, PowerPoint, Photoshop,
Examples
disk, RAM, ROM, etc. MySQL, etc.
Language:
• System of communication .
• Computer language are used to facilitate communication between computer and the
user.
Types of Translators
• There are three types of Translators:-
• Assembler .
• Compiler.
• Interpreter.
Assembler Compiler
• Assembler is a translator (program) used • Compiler is a translator used to
for converting the code of low-level convert the code of High Level
language (Assembly language) into Language into machine language .
machine level language
• The high level language program is
Interpreter known as source program and the
• Interpreter and compiler performs the same corresponding machine language
task ,there is a difference in the working. program is known as object program.
• An interpreter are also used to convert H.L.L. • A compiler searches all the errors of
into M.L Language. program and list them.
• An interpreter is a translator it checks the
errors of program statement by statement • If the program is error free then it
(Line by Line). converts the code of program into
• After checking one statement it converts that machine code and the program can
statement into machine code and then be executed separate commands
executes that statement. This process
continues until the last statement of program .
Operating System
• An Operating System is a program that acts as an
intermediary/interface between a user of a computer and the computer
hardware.
• It performs basic tasks, such as:
 Recognizing input from the keyboard or mouse,
 Sending output to the monitor,
 Keeping track of files and directories on the disk, and
 Controlling peripheral devices such as disk drives and printers
Types Of Operating System
There are four types of operating system based on the type of computer they
control and the sort of applications they support.
1.Single-user, single task: MS-DOS.
2.Multi-user, multi-task: Windows Server, macOS Server.
3.Single-user, Multi-tasking: Windows, Linux, Android, iOS, macOS.
4.Real Time Operating Systems:
• Medical Devices: MRI Machines, Pacemakers
• Automotive Systems: Airbag Control Systems
• Industrial Automation: Robotics
• Aerospace: Flight Control Systems
Network Operating System
A network operating system(NOS) is software that connects multiple
devices and computers on the network and allows them to share
resources on the network.
Functions of the NOS (Network Operating System):
• creating and managing user accounts on the network.
• Controlling access to resources on the network.
• Provide communication services between the devices on the network.
• Monitor and troubleshoot the network.
• Configuring and Managing the resources on the network.
Software Development Life Cycle (SDLC)
• It is a framework that describes the activities performed at each stage
of a software development project.
• It is a methodology that defines the entire procedure of software
development step-by-step.
• It is used by software industry to design, develop, and test good-
quality software.
SDLC PHASES
https://www.intelivita.com/blog/benefits-of-software-development-life-cycle/ (Benefits Explained)
Program
Design Tools
• Program Design tools are the tools used to develop a program. A program is
the expression of an algorithm in a programming language.

01 Algorithms

02 Flowcharts

03 Pseudo codes
Algorith
m
An algorithm in general is a sequence of steps to solve a particular problem.
Algorithms are universal.

The algorithm you use in C programming language is also the same algorithm you
use in every other language.
Qualities of a good
algorithm
1. Input and output should be defined precisely.

2.Each steps in algorithm should be clear and unambiguous.

3. Algorithm should be most effective among many different ways to solve a problem.

4.An algorithm shouldn't have computer code. Instead, the algorithm should be written in
such a way that, it can be used in similar programming languages
Examples Of Algorithms
In Programming
Examples Of Algorithms
In Programming
Flowcha
rt

• A flowchart is a type of diagram that represents a workflow or process.

• A flowchart can also be defined as a diagrammatic representation of an algorithm,


a step-by-step approach to solving a task.

• The flowchart shows the steps as boxes of various kinds, and their order by
connecting the boxes with arrows.
Symbols Used In
Flowchart
Symbols Used In
Flowchart
Guidelines for
Developing
Flowcharts
Guidelines for Developing Flowcharts

• These are some points to keep in mindwhile developing a flowchart −

• Flowchart can have only one start and one stop symbol

• On-page connectors are referenced using numbers

• Off-page connectors are referenced using alphabets

• General flow of processes is top to bottom or left to right

• Arrows should not cross each other


Guidelines for
Developing
Flowcharts
Guidelines for Developing Flowcharts

• These are some points to keep in mindwhile developing a flowchart −

• Flowchart can have only one start and one stop symbol

• On-page connectors are referenced using numbers

• Off-page connectors are referenced using alphabets

• General flow of processes is top to bottom or left to right

• Arrows should not cross each other


Pseudocod
e
• pseudocode is a method of writing an algorithm.

• It cannot be compiled or run like a regular


program.

• Pseudocode can be written how you want. But some companies use specific pseudocode syntax
to keep everyone in the company on the same page.

• Syntax is a set of rules on how to use and organize

statements in a programming language


Advantages of
Pseudocode
• Improves the readability of any approach.

• It’s one of the best approaches implementation to start of an algorithm.

• Acts as a bridge between the program and the algorithm or flowchart.

• The main goal of a pseudo code is to explain what exactly each line of a program
should do,

• Hence making the code construction phase easier for the programmer.
Advantages of
Pseudocode
Exam
ple
SumOfTwoNumbers(
) Begin
Set sum =0;
Read: a, b;
Set sum = a + b;
Print sum;
End
History of C
Language
• C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.

• Dennis Ritchie is known as the founder of the c language.

• It was developed to overcome the problems of


previous languages such as B, BCPL, etc.
Features of C Language
• C is thewidely used language. It provides
many that are given below.
features
C- compiler
• There are many compilers available for c and c++. You need to download any
one. Here, we are going to use Turbo C++.
Compilation process in c

• The compilation is a process of converting the source code into object code. It is done with the
help of the compiler.

• The compiler checks the source code for the syntactical or structural errors, and if the source
code is error-free, then it generates the object code.
Compilation process in c

• The compilation process can be divided into four steps, i.e., Pre-processing, Compiling, Assembling, and
Linking.

• The following are the phases through which our program passes before being transformed into an
executable form:

1. Preprocessor

2. Compiler

3. Assembler

4. Linker
Compilation process in c
Compilation process in c
Preprocessor
• The source code is the code which is written in a text editor and the source code file is
given an extension ".c".
• This source code is first passed to the preprocessor, and then the preprocessor expands
this code.
• After expanding the code, the expanded code is passed to the compiler.
Compilation process in c
Compiler
• The code which is expanded by the preprocessor is passed to the compiler.
• The compiler converts this code into assembly code.

• Or we can say that the C compiler converts the pre-processed


code into assembly code

.
Compilation process in c
Assembler
• The assembly code is converted into object code by using an assembler.
The name of the object file generated by the assembler is the same as the
source file.
• The extension of the object file in DOS is '.obj,' and in UNIX, the
extension is 'o'. If the name of the source file is 'hello.c', then the name of
the object file would be 'hello.obj'.
Compilation process in c
Linker
• Mainly, all the programs written in C use library functions.

• These library functions are pre-compiled, and the object code of these library files is stored with '.lib'
(or '.a') extension.

• Therefore, we conclude that the job of the linker is to link the object code of our program with the
object code of the library files and other files.
Compilation process in c
Linker
• The output of the linker is the executable file. The name of the executable file is the same as the source file
but differs only in their extensions.

• In DOS, the extension of the executable file is '.exe',

• For example, if we are using printf() function in a program, then the linker adds its associated code in an
output file.
Compilation process in c
Let's understand through an example.

hello.c

#include <stdio.h>

int main()

printf("Hello javaTpoint");

return 0;

}
Compilation process in c
Structure of c program
A C program involves the following sections:

• Documentations (Documentation Section)

• Preprocessor Statements (Link Section)

• Global Declarations (Definition Section)

• The main() function

• Local Declarations

• Program Statements & Expressions

• User Defined Functions


First C Program
/*My first c
program*/

#include<stdio.h>

Void main()

printf("Hello, World!\
n");

}
/* Comments */ - Comments are a way of explaining what makes a program. The compiler ignores
comments and used by others to understand the code.

#include<stdio.h> - This is a preprocessor command. That notifies the compiler to include the header
file stdio.h in the program before compiling the source-code.

Void – the function returns null


main() - The main() is the main function where program execution begins. Every C program must

contain only one main function.

Braces - Two curly brackets "{...}" are used to group all statements.

printf() - It is a function in C, which prints text on the screen.


Compile and Execute C Program

• Open a text editor and add the above-mentioned


code.

•Save the file as hello.c

•Alt + F9 – Compile

•Ctrl + F9 – Compile & Run


Input and output statements

• printf() is used to display the output and scanf() is used to read the
inputs.

• printf() and scanf()


declared functions are in
in C library.“stdio.h” header
• All file in C
syntax
including language and
printf()
functions are case sensitive.
Tokens – small individual unit
Keywords
in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only
32 reserved words (keywords) in the C language.
C Identifiers
• Identifier refers to name given to entities such as variables, functions, structures etc.

• Identifiers must be unique. They are created to give a unique name to an entity to identify it during the execution of
the program.

• For example:

• 1. int money;

• 2. double accountBalance;

• Here, money and accountBalance are identifiers.

• Also remember, identifier names must be different from keywords. You cannot use int as an identifier because int is a
keyword.
Rules for naming
identifiers
• 1. A valid identifier can have letters (both
uppercase letters), digits and underscores.
and lowercase

• 2. The first letter of an identifier should be either a letter or an underscore.

• 3. You cannot use keywords as identifiers.

• 4. There is no rule on how long an identifier can be. However, you may run into problems in
some compilers if the identifier is longer than 31 characters.
Variables
in C
• A variable is a name of the memory location. It is used to store data. Its value can be changed, and it
can be reused many times.

• It is a way to represent memory location through symbol so that it can be easily identified.

• Let's see the syntax to declare a variable:

type variable_list;

• The example of declaring the variable is given below:

• int a;

• float b;

• char c;
Variables in C

• Here, a, b, c are variables. The int, float, char are the data types.

• We can also provide values while declaring the variables as given below:

• int a=10,b=20;//declaring 2 variable of integer


type

• float f=20.8;

• char c='A';
Variables in C
Rules for defining variables
• A variable can have alphabets, digits, and underscore.

• A variable name can start with the alphabet, and underscore only. It can't start with a digit.

• No whitespace is allowed within the variable name.

• A variable name must not be any reserved word or keyword, e.g. int, float, etc.
Variables in C
Local Variable

• A variable that is declared inside the function or block is called a local variable.

• It must be declared at the start of the block.


void main(){
int x=10;//local variable
}
Variables in C
Global Variable

• A variable that is declared outside the function or


block is called a global variable.

• Any function can change the value of the global variable. It is available to all the functions.
int value=20;//global variable
void main(){
int x=10;//local variable
}
Constants in C
A constant is a value or variable that can't be changed in the

program, for example: 10, 20, 'a', 3.4, "c programming" etc. There are two simple ways in C to define constants
Using #define preprocessor.

Syntax:

#define identifier value Example

#define LENGTH 10

#define WIDTH 5
Using const keyword.

Syntax:
const type var
const int LENGTH = 10; const int WIDTH = 5;
Data Types in C
A data type specifies the type of data that
a variable can store such as integer,
floating, character
Data Types in C

• Basic Data Type- int, char, float, double

• Derived Data Type- array, pointer, function

• User Defined- Enumeration Data Type(enum), structure, union, typedef

• Void Data Type - void


Format specifier
• The Format specifier is a string used in the formatted input and output functions.
• The format string determines the format of the input and output.
• The format string always starts with a '%' character.
EXAMPLE:
%d - int
%f - float
%c - char
INPUT OUTPUT (I/O) STATEMENTS

 scanf() function to take input from the user,

 printf() function to display output to the user

EXAMPLE:
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Output
statement in C
printf() function to display output to the user

Syntax: printf(“%X”, variableOfXType);

where %X is the format specifier in c


In C programming, printf() is one of the main output function. The function sends
formatted output to the screen.
The printf() is a library function to send formatted output to the screen. The function
prints the string inside the quotations.

To use printf() in our program, we need to include stdio.h


header file using #include <stdio.h> statement.
EXAMP
LE
#include <stdio.h> void main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
}

• Output:Number = 5
• We use %d format specifier to print int
types.
• Here, the %d inside the quotations will
be
replaced by the value of testInteger
Example 3: float and double
Output
#include <stdio.h>
void main()
{
float number1 = 13.5;
double number2 = 12.4;
printf("number1 = %f\
n", number1);
printf("number2 = %lf",
number2);
}
Print
Characters
#include <stdio.h>
void main()
{
char chr = 'a';
printf("character = %c", chr);
}
Output
character = a
To print char, we use %c
format specifier
INPUT OUTPUT (I/O) STATEMENTS

 scanf() function - to take input from the user, Syntax: scanf(“%X”, &variableOfXType); where %X is the format specifier in
c
& is the address operator in C.

EXAMPLE:
#include <stdio.h>
void main()
{
int a;
// Displays the string inside quotations printf("C Programming");
//getting input from the user
scanf(“%d”,&a);
printf(“Given data is %d”,a);
}
C Input
• In C programming, scanf() is one of the commonly used function to take input from the user.

• The scanf() function reads formatted input from the standard input such as keyboard

Integer Input/Output #include <stdio.h> void main()


{
int testInteger; printf("Enter an integer: ");
scanf("%d", &testInteger); printf("Number = %d“,testInteger);
}
Output
Enter an integer: 4 Number = 4
C Input
• Here, we have used %d format specifier inside the scanf() function to take intinput from
the user. When the user enters an integer, it is stored in the testInteger variable.

• Notice, that we have used &testInteger inside scanf(). It is because &testIntegergets the
address of testInteger, and the value entered by the user is stored in that address.
C Input
Example 6: Float and Double Input/Output
#include <stdio.h>
int main()
{
float num1;
double num2;
printf("Enter a number: ");
scanf("%f", &num1);
printf("Enter another
number: ");
scanf("%lf", &num2);
printf("num1 = %f\n", numprintf("num2 = %lf",
num2);
return 0;}
C Input
C Character I/O
#include <stdio.h>
void main()
{
char chr;
printf("Enter a
character: ");
scanf("%c",&chr);
printf("You
entered %c", chr);
}
Output
Enter a character: g
C Input
• When a character is entered by the user in the above program, the character
itself is not stored. Instead, an integer value (ASCII value) is stored.

• And when we display that value using


%c text format, the entered character is displayed. If we use %d to display the
character, it's ASCII value is printed.
ASCII
Value
#include <stdio.h>
int main()
{
char chr;
printf("Enter a
character: ");
scanf("%c", &chr);
// When %c is used, a character is displayed
printf("You entered %c.\n",chr);
/*When %d is used, ASCII value is displayed */
printf("ASCII value is % d.", chr);
return 0;
}
Output
Enter a character: g
You entered g.
ASCII value is 103.
I/O Multiple
Values
Here's how you can take multiple inputs from the user and displaythem.
#include <stdio.h>
int main()
{
int a;
float b;
printf(
"Enter
integer
and
then a
float:
");
// Taking multiple inputs Page13
scanf("%d%f", &a, &b);
printf("You entered %d and %f",
a, b);
return 0;
}
Output
Enter integer and then a float: -
Format Specifiers
for I/O
Data Type Format Specifier
int %d
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned %lu
long int long long int
unsigned %llu
signed char %c
unsigned char %c
Formatted and Unformatted
Console I/O Functions
Input / Output (I/O) Functions :
• In “C‟ language, two types of Input/Output functions are available, and all input and output operations are carried out through
function calls.
• Several functions are available for input / output operations in “C‟.
• These functions are collectively known as the standard i/o library. Input: In any programming language input means to feed
some data into program. This can be given in the form of file or from command line.
• Output: In any programming language output means to display some data on screen, printer or in any file.
• The Standard Files: C programming treats all the devices as files. So devices such as the display are addressed in the same way
as files and the following three files are automatically opened when a program executes to provide access to the keyboard and
screen.
Formatted and
Unformatted
Console I/O
Functions
Input / Output functions are classified into two types
Formatted Console I/O Functions
Formated I/O Functions: formatted I/O functions operates on various types of data. 1 :
printf() : output data or result of an operation can be displayed from the computer to a
standard output device using the library function printf().
This function is used to print any combination of data.
Syntax : printf(“control string “, variable1, variable2, -----------, variablen);
 Ex : printf(“%d”,3977); // Output: 3977
printf() statement another syntax :
Syntax : printf(“fomating string”);
 Formating string : it prints all the character given in doublequotes (“ “) except
formatting specifier.
Formatted Console I/O Functions
• Ex : printf(“ hello “);-> hello
• printf(“a”); -> a
• printf(“%d”, a); -> a value
• printf(“%d”); -> no display
2. scanf() : input data can be entered into the computer using the standard input „C‟ library function called
scanf().
 This function is used to enter any combination of input.
 Syntax : scanf(“control string “,&var1, &var2,----, &varn);
 The scanf() function is used to read information from the standard input device (keyboard).
 Ex : scanf(“ %d “,&a);-> hello
 Each variable name (argument) must be preceeded by an ampersand (&). The (&) symbol gives the
meaning “address of “ the variable.
Formatted Console I/O Functions
sprintf():
sprintf stands for “string print”. This function is similar to printf() function but, this function prints the string into a
character array instead of printing it on the console screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);

#include <stdio.h>
int main()
{
char str[50];
int a = 2, b = 8;

// The string "2 and 8 are even number"


// is now stored into str
sprintf(str, "%d and %d are even number", a, b);

// Displays the string


printf("%s", str);
return 0;
}
Output:
2 and 8 are even number
Formatted Console I/O Functions
sscanf():
sscanf stands for “string scanf”. This function is similar to scanf() function but, this function reads data from the string
or character array instead of the console screen.
Syntax:
sscanf(array_name, “format specifier”, &variable_name);

#include <stdio.h>

int main()
{
char str[50];
int a = 2, b = 8, c, d;
// The string "a = 2 and b = 8" is now stored into str
character array
sprintf(str, "a = %d and b = %d", a, b);
// The value of a and b is now in c and d
sscanf(str, "a = %d and b = %d", &c, &d);
// Displays the value of c and d
printf("c = %d and d = %d", c, d); Output:
return 0; c = 2 and d = 8

}
Unformatted I/O functions:
Unformatted I/O functions:
a) Character I/O
b) String I/O
a) character I/O:
1. getchar(): Used to read a character from the standard input
2. putchar(): Used to display a character to standard output
3. getch() and getche(): these are used to take the any alpha numeric characters from the
standard input
•getche() read and display the character
• getch() only read the single character but not display
4. putch(): Used to display any alpha numeric characters to standard output
Unformatted I/O functions:

Unformatted I/O functions:


b) String I/O :
1. gets(): Used for accepting any string from the standard input(stdin)
ex:gets()
2. puts(): Used to display a string or character array Ex:puts()
3. Cgets(): read a string from the console
ex: cgets(char *st)
4. Cputs(): display the string to the console
ex: cputs(char *st)
Operato
rs
 An operator is simply a symbol that is used to perform operations.
There can be many types of operations like arithmetic, logical, bitwise, etc.
 There are following types of operators to perform different types of operations in C
language.

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operator
 Ternary or Conditional Operators
 Unary Operators
 Bitwise Operators
 Shift Operators
 Special Operators
Arithmetic
Operators
• The following table shows all the arithmetic operators supported by the C language.
• Assume variable A holds 10 and variable B holds 20 then
Arithmetic
Operators
EXAMPLE:
Relational
Operators
• The following table shows all the relational operators
supported by C. Assume variable A holds 10 and
variable B holds 20 then
Relational
Operators
A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if
the relation is false, it returns value 0.
Logical
Operators
An expression containing logical operator returns either 0 or1 depending upon whether expression results true or false.
Logical operators are commonly used in decision making in C programming.
• (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).

• (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).

• (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).

• (a != b) || (c < b) evaluates to 0 because both


operand (a != b) and (c < b) are 0 (false).

• !(a != b) evaluates to 1 because operand (a !=


b) is 0 (false). Hence, !(a != b) is 1 (true).

• !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).


Assignment
Operators
Assignment operators are used to assign a value (or) an expression (or) a value of a variable to another variable.
Syntax : variable name=expression (or) value (or) variable
Ex : x=10;
y=a+b;
z=p;

Compound assignment operator: „C‟ provides compound assignment operators to assign a value to variable in order to
assign a new value to a variable after performing a specified operation.
Assignment
Operators
// C Program to demonstrate the working of assignment operators

#include <stdio.h>
int main()
{
int a = 5, c;
c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
conditional
operator
(condition) ? expression1 : expression2

If the condition is true then expression1 is executed else expression2 is executed


Exam
ple
Unary
Operators
Examples: // C program to illustrate the decrement operator of
// C Program to illustrate the increment of both both types
type #include <stdio.h>
#include <stdio.h>
void decrement()
void increment()
{
{
int a = 5;
int a = 5;
int b = 5;
int b = 5;

// PREFIX // PREFIX
int prefix = ++a; int prefix = --a;
printf("Prefix Increment: %d\n", prefix); printf("Prefix = %d\n", prefix);
// POSTFIX
int postfix = b++; // POSTFIX
printf("Postfix Increment: %d", postfix); int postfix = b--;
} printf("Postfix = %d", postfix);
}
// Driver code
int main()
{ // Driver code
increment(); int main()
{
return 0; decrement();
}

return 0;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int p,q;
q=10;
P=++q;
printf(“p: %d”,p);
printf(“q: %d”,q);
getch();
}
1. Whenever more than one format
specifiers (i.e %d) are directly or
indirectly related with same variable
(i,i++,++i) then we need to evaluate each
individual expression from right to left.
2. As shown in the above image
evaluation sequence of expressions
written inside printf will be – i++, ++i, i
3. After execution we need to replace the
output of expression at appropriate
place.
Differences between Increment And Decrement Operators

Increment Operator Decrement Operator


Increment Operator adds 1 to the operand. Decrement Operator subtracts 1 from the operand.

The Postfix increment operator means the expression is evaluated first using The Postfix decrement operator means the expression is evaluated first using
the original value of the variable and then the variable is the original value of the variable and then the variable is
incremented(increased).The decremented(decreased).

Prefix increment operator means the variable is incremented first and then the Prefix decrement operator means the variable is decremented first and then
expression is evaluated using the new value of the variable. the expression is evaluated using the new value of the variable.

Generally, we use this in decision-making and looping. This is also used in decision-making and looping.
Find Output of following programs:
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int a, b; int x=4,y,z;
a = 5; y = –x;
b = x++ / 2; z = x–;
printf(“%d”, y); printf(“%d %d %d”,x,y,z);
return 0; return 0;
} }

Answer:– 2 Answer:– 2 3 3
Bitwise
• Operators
Bitwise operators are used to manipulate the data at bit level.
• It operates on integers only.
• It may not be applied to float.
• In arithmetic-logic unit (which is within the CPU), mathematical operations like: addition,
subtraction, multiplication and division are done in bit-level which makes processing faster and
saves power.
• To perform bit-level operations in C programming, bitwise operators are use
Bitwise AND Operator &
The output of bitwise AND is 1 if the corresponding bits of two operands is 1.
If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
In C Programming, the bitwise AND operator is denoted by &.
Let us suppose the bitwise AND operation of two integers 12 and 25.
Bitwise OR operator |
• The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1.
• In C Programming, bitwise OR operator is denoted by |.
Bitwise XOR (exclusive OR) operator ^
• The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite.
• It is denoted by ^
Bitwise complement operator ~
• Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0
and 0 to 1.
• It is denoted by ~.
Twist in bitwise complement operator in C Programming
35 = 00100011 (In Binary) The bitwise complement of 35 (~35) is -36 instead of 220, but why?
Bitwise complement Operation of 35 For any integer n, bitwise complement of n will be -(n+1).
To understand this, you should have the knowledge of 2's
complement.
Two's complement is an operation on binary numbers. The
2's complement of a number is equal to the complement of that
number plus 1. For example:
Contd..
• The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36. Hence, the output is -36 instead
of 220.

• Bitwise complement of any number N is -(N+1). Here's how:

• bitwise complement of N = ~N (represented in 2's complement form)

• 2'complement of ~N= -(~(~N)+1) = -(N+1)

Example #4: Bitwise complement


#include <stdio.h>
int main()
{
printf("complement = %d\n",~35);

return 0;
}
Bitwise Shift
Operators

Right Shift LEFT Shift


Special Operators
Special Operators
Expressions
Operator Precedence
Operator Precedence
Operator Precedence and Associativity
Operator Precedence and Associativity
Type Conversion
in C
• The type conversion process in C is basically converting one type of data type to other to perform some
operation.

• The conversion is done only between those datatypes wherein the conversion is possible

• EX – char to int and vice versa.

• There are two types of type conversion


1) Implicit Type Conversion
2) Explicit Type Conversion
1.Implicit Type Conversion
• This type of conversion is usually performed by the compiler when necessary without any commands by the
user. Thus it is also called "Automatic Type Conversion".

• The compiler usually performs this type of conversion when a particular expression contains more than one
data type.

• In such cases either type promotion or demotion takes place.


Whenever the compiler deals with different data types in an expression, the operand which is present at the lower
rank will be converted to the corresponding datatype of the operand with the higher rank.
Rules...
1.char or short type operands will be converted to int during an operation
and the outcome data type will also be int.
2.If an operand of type long double is present in the expression, then the corresponding
operand will also be converted to long double same for the double data type.
3.If an operand of float type is present then the corresponding operand in the expression
will also be converted to float type and the final result will also be float type.
4.If an operand of unsigned long int is present then the other operand will be converted to
unsigned long int and the final result will also be unsigned long int.
5.If an operand of long int is present then the other operand will be converted to long int and
the final result will also be long int.
6.If an operand of unsigned int is present then the other operand will be converted to
unsigned int and the final result will also be unsigned int.
Exam
ple
int a = 20; double b = 20.5; a + b;

 Here, first operand is int type and other is of type double.

 So, as per rule 2, the variable a will be converted to double.

 Therefore, the final answer is double a + b =

40.500000.
2) Explicit Type
Conversion
• Explicit type conversion rules out the use of compiler for converting one
data type to another instead the user explicitly defines within the program
the datatype of the operands in the expression.
2) Explicit Type
Conversion

Output:
1. Thus, in the above example we find that the output result is 12 because in the result expression the user has explicitly defined the
operands (variables) as integer data type.
2. Hence, there is no implicit conversion of data type by the compiler.If in case implicit conversion was used the result would be 13.
C - Type Casting

• Type casting is a way to convert a variable from one data type to another data type.

• For example, if you want to store a 'long' value into a simple integer then you can type cast
'long' to 'int'.

• You can convert the values from one type to another explicitly using the cast operator as
follows −

• (type_name) expression
Example:

#include <stdio.h> main() {


int sum = 17, count = 5; double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
• When the above code is compiled and executed, it produces the following result
• Value of mean : 3.400000
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either to int
or unsigned int.

#include <stdio.h> main() {


int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}

Value of sum : 116

You might also like