Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ip Unit-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

UNIT-I: Introduction to Programming and Problem Solving

History of Computers, Basic organization of a computer: ALU, input-output units, memory,


program counter, Introduction to Programming Languages, Basics of a Computer Program-
Algorithms, flowcharts (Using Dia Tool), pseudo code. Introduction to Compilation and
Execution, Primitive Data Types, Variables, and Constants, Basic Input and Output,
Operations, Type Conversion, and Casting.
Computer
 Computer is a fast electronic device that takes raw data as input from the user, processes it
according to the set of stored instructions (called program), gives the result (output) in desired
format.
 It is designed to execute applications and provides a variety of solutions by combining
integrated hardware and software components.
 A computer is made up of multiple parts and components that facilitate user functionality.
 Computers can perform easy and complex tasks repeatedly without committing errors.

Functionalities of a computer:
 Takes data as input.
 Stores the data/instructions in its memory and use them when required.
 Processes the data and converts it into useful information.
 Generates the output.

Characteristics of Computer
 Speed: Computers can perform operations at a great speed.
 Accuracy: Computers exhibit a very high degree of accuracy. There is a very less chance of
computing error. Errors that may occur are usually due to human errors.
 Reliability: Computers can carry out same type of work repeatedly without throwing up
errors.
 Versatility: Computers can carry out a wide range of work ranging from simple data storage to
complex continuous calculations.
A Brief History of Computer:
One of the earliest and most well-known devices was an abacus. Then in 1822, the father of
computers, Charles Babbage began developing what would be the first mechanical computer. And
then in 1833 he actually designed an Analytical Engine which was a general-purpose computer.
Classification of generations of computers
 The evolution of computer technology is often divided into five generations.
Five Generations of Computers

Generations of computers Generations timeline Evolving hardware

First generation 1940s-1950s Vacuum tube based

Second generation 1950s-1960s Transistor based

Third generation 1960s-1970s Integrated circuit based

Fourth generation 1970s-1980s Microprocessor based

Fifth generation 1980s - present and the future Artificial intelligence based
The first generation of computers (1940s-1950s)
 Main electronic component – vacuum tube
 Main memory – magnetic drums and magnetic tapes
 Programming language – machine language
 Power – consume a lot of electricity and generate a lot of heat.
 Speed and size – very slow and very large in size (often taking up entire room).
 Input/output devices – punched cards and paper tape.
 Examples – ENIAC, UNIVAC1, IBM 650, IBM 701, etc.
The second generation of computers (1950s-1960s)
 Main electronic component – transistor
 Memory – magnetic core and magnetic tape / disk
 Programming language – assembly language
 Power and size – low power consumption, generated less heat, and smaller in size (in
comparison with the first generation computers).
 Speed – improvement of speed and reliability (in comparison with the first generation
computers).
 Input/output devices – punched cards and magnetic tape.
 Examples – IBM 1401, IBM 7090 and 7094, UNIVAC 1107, etc.

The third generation of computers (1960s-1970s)


 Main electronic component – integrated circuits (ICs)
 Memory – large magnetic core, magnetic tape / disk
 Programming language – high level language (FORTRAN, BASIC, Pascal, COBOL, C, etc.)
 Size – smaller, cheaper, and more efficient than second generation computers (they were called
minicomputers).
 Speed – improvement of speed and reliability (in comparison with the second generation
computers).
 Input / output devices – magnetic tape, keyboard, monitor, printer, etc.
 Examples – IBM 360, IBM 370, PDP-11, UNIVAC 1108, etc.
The fourth generation of computers (1970s-1980s)
 Main electronic component – very large-scale integration (VLSI) and microprocessor.
 VLSI– thousands of transistors on a single microchip.
 Memory – semiconductor memory such as RAM, ROM, etc.
 Programming language – high level language (Python, C#, Java, JavaScript, etc.).
 A mix of both third- and fourth-generation languages
 Size – smaller, cheaper and more efficient than third generation computers.
 Speed – improvement of speed, accuracy, and reliability (in comparison with the third generation
computers).
 Input / output devices – keyboard, pointing devices, optical scanning, monitor, printer, etc.
 Network – a group of two or more computer systems linked together.
 Examples – IBM PC, STAR 1000, APPLE II, Apple Macintosh, etc.

The fifth generation of computers (1980s-the present and the future)


 Main electronic component: based on artificial intelligence, uses the Ultra Large-Scale
Integration (ULSI) technology and parallel processing method.
 ULSI – millions of transistors on a single microchip
 Parallel processing method – use two or more microprocessors to run tasks simultaneously.
 Language – understand natural language (human language).
 Power – consume less power and generate less heat.
 Speed – remarkable improvement of speed, accuracy and reliability (in comparison with the
fourth generation computers).
 Size – portable and small in size, and have a huge storage capacity.
 Input / output device – keyboard, monitor, mouse, trackpad (or touchpad), touchscreen, pen,
speech input (recognise voice / speech), light scanner, printer, etc.
 Example – desktops, laptops, tablets, smartphones, etc.
Basic organization of a computer:
Over the several years the size, processing speed, cost and reliability of computers has changed. But,
the basic structure of computer is still the same as was given by Von Neumann in the year 1945 has
not changed. According to Von Neumann architecture the computer consists of these components:
1. Input Unit
2. Output Unit
3. Central Processing Unit (CPU)
a. Arithmetic Logic Unit
b. Control Unit
4. Storage Unit or Memory Unit

1.Input unit:
 The set of devices used to give input to the computer is called an input unit. This unit makes a
link between user and computer.
 The computer accepts input data from the user via an input device like keyboard.
 The input data can be characters, word, text, sound, images, document, etc. This is either stored
in the memory or immediately used by the processor to perform the desired operations.
 Commonly used input devices are Keyboard, Mouse, Joystick, Track Ball, Scanner, Microphone,
web cam etc.
2. Output unit:
 The set of devices that are used to take the output from the computer are called an output unit.
 The output is the result generated after the processing of data.
 If the output is shown on the monitor, it is a soft copy and if the output is printed on the paper, it
is a hard copy.
 Commonly used output devices are monitors, printers, speakers, headphones, projectors, GPS
devices, optical mark readers, etc.

3. Central Processing Unit:


 CPU controls, coordinates and supervises the operations of the computer. It is responsible for
processing of the input data.
 CPU consists of Arithmetic Logic Unit (ALU) and Control Unit (CU).

Control Unit (CU):


 Control Unit controls the overall operations of the computer i.e. it checks the sequence of
execution of instructions controls and coordinates the overall functioning of the units of
computer.
 Functions of this unit are:
 It is responsible for controlling the transfer of data and instructions among other units
of a computer.
 It manages and coordinates all the units of the computer.
 It communicates with Input / Output devices for transfer of data or results from storage.
 In simple it controls the flow of data and instructions to and from the storage unit to ALU.

Arithmetic Logic Unit (ALU):


 ALU performs all arithmetic and logical operations on the input data.
 Whenever calculations are required, the control unit transfers the data from storage unit to
ALU. When the operations are done, the result is transferred back to the storage unit.
 ALU unit consists of two sub sections
 Arithmetic Section: Function of the arithmetic section is to perform arithmetic
operations like addition, subtraction, multiplication, and division. All complex
operations are done by making repetitive use of mentioned operations.
 Logic Section: Function of the logic section is to perform logic operations such as
comparing, selecting, matching and merging of data.
4. Storage Unit (or) Memory Unit:
 This unit can store instructions, data and intermediate results. This unit supplies information to
the other units of the computer when needed.
 The storage unit of a computer system can be divided into two categories:
 Primary storage
 Secondary storage
Primary Storage:
 Primary memory refers to a set of memory units within the computer CPU that has direct access
to, and it stores instruction and data needed for processing by the CPU.
 Primary memory stores the intermediate results and final results of the processing before it is
stored in permanent storage.
 It enhances overall system performance by providing fast, immediate access to data and
programs, reducing processing time.
 Some of this memory is volatile i.e. contents stored will get erased if power is switched off, and
some of them are non-volatile i.e. contents cannot be erased.
 The primary memory of a computer can be categorized into three major types.
a) Main memory
 RAM (Random Access Memory)
 ROM (Read Only Memory)
b) Cache memory
c) Register memory
a) Main Memory:
The Main memory size is the largest compared to Cache Memory and Register memory, but
the cost is the lowest among them. Main memory can be divided into two main types, viz.,
Random Access Memory (RAM), and Read-only Memory (ROM), and each of these is
divided into further sub-types.
RAM (Random Access Memory):
 RAM is used to hold data and instructions that are currently in use.
 RAM is volatile or temporary in nature i.e. once the system is switched off, the
information stored on RAM gets erased.
 RAM is read and writes memory; it can be read as well as write as per the processing
requirements.
 The contents of RAM can be changed at any time by overwriting it with other data and
instructions. For example, a user might close one document and open another or run a
different program.
 The more RAM a computer has, the more data and program instructions it can hold
simultaneously. RAM can also be upgraded easily, unlike other types of primary storage.

ROM (Read Only Memory):


 A non-volatile type of memory that continues to hold the contents even when the power
is switched off. As per the name, contents can only be read from these memory locations
and cannot be erased or rewritten.
 Contents like boot programs, firmware (is a computer program that is "embedded" in a
hardware device and is an essential part of the hardware), and mathematical tables in
scientific applications are stored during manufacturing and sold with pre-stored contents.
 These contents are used during the operation of the device, and they cannot be altered.

b) Cache Memory:
 Frequently addressed Instructions and data are stored in an exclusive faster memory in
the CPU to avoid wasting effort and time to bring it from slow main memory. Such
storage is called Cache memory, and its size is in the range of 2KB to 64KB.
 The size of this memory is much smaller than the main memory, and the cost is higher
than the main memory but lesser than the Resisters.

c) Register Memory:
 As part of the CPU, Registers are used to hold the memory addresses of the data, next
instruction, and intermediate results during the program execution.
 It also acts as transit storage between the main memory and the Processor. It is the
costliest of all the memory; size-wise, it is the smallest.

Secondary storage
 Secondary memory is where programs and data are kept on a long-term basis.
 If we need to store large amounts of data or programs permanently, we need a cheaper and
permanent memory.
 A secondary storage device refers to any non-volatile storage device that is internal or external to
the computer.
 There are some characteristics of secondary memory, which distinguish it from primary memory,
such as:
 It is non-volatile, which means it retains data when power is switched off.
 It allows for the storage of data ranging from a few megabytes to petabytes.
 It is cheaper as compared to primary memory.
 Secondary storage devices like CDs and flash drives can transfer the data from one device to
another.
 Secondary storage devices can be classified into three broad categories.
1) Magnetic storage devices
2) Optical storage devices
3) Solid-state storage devices

1) Magnetic storage devices


Magnetic storage devices use magnetization process to write, rewrite and access data. Data gets
saved here in binary form. These devices store data in the form of tiny, magnetized dots. The dots are
created, read and erased using magnetic fields created by tiny electromagnets.
 Hard disk drives (HDDs)
 Tape drives
 Floppy disk drives

2) Optical storage devices


These devices use optical storage technology to read and write data. Data gets stored digitally, and
lasers are used in these devices to read and write data.
 CD drives:
CD drives generally use laser rays to read and write data. With 700 MB of storage space,
these devices are cheap, portable and one of the most popular storage devices used.
 DVD drives:
They can store 15 times the data CDs hold and rich multimedia files that require high storage
capacity.
 Blue-ray drives:
A blue-ray disk can store high-definition (HD) video and other multimedia files. It uses a
shorter wavelength laser than CD/DVD and therefore can store more data.
3) Solid-state storage devices
Solid-state storage devices do not involve magnetic disks or any moving parts. They store data on
non-moving components.
 Solid-state drives (SSDs):
These devices store data using flash-based memory much faster than traditional hard disks.
SSDs have no moving parts and upgrading to one is a great way to speed up your computer
and make it more resilient.
 USB drives:
USB flash drives are essential for quickly moving files from one system to another. They can
now hold up to 2TB of storage and are a convenient medium to store and transfer smaller
files.

Program Counter:
 A program counter (PC) is a CPU register in the computer processor which has the address of the
next instruction to be executed from memory. It is a digital counter needed for faster execution
of tasks as well as for tracking the current execution point. A program counter is also known as
an instruction counter

Introduction to Programming Languages:


To communicate with computers, programmers also need a language is called Programming
language. The primary classifications of programming languages are:
 High level Languages
 Low level languages
High Level Language
 High-level programming languages are easy for humans to read and understand, the computer
understands the machine language that consists of numbers only. Each type of CPU has its own
unique machine language.
 High level languages is that they allow the programmer to write programs for all types of
computers and systems. Every instruction in high level language is converted to machine
language for the computer to comprehend.
Types of High-Level Language
Scripting languages:
 Scripting languages are essentially programming languages. These languages employ a high
level construct which allows it to interpret and execute one command at a time.
 Scripting languages are easier to learn and execute than compiled languages. Some examples
are AppleScript, JavaScript, Pearl etc.
Object-Oriented Languages:
 These are high level languages that focus on the ‘objects’ rather than the ‘actions’. To
accomplish this, the focus will be on data than logic.
 Some examples include Java, C+, C++, Python, Swift etc.
Procedural Programming Language:
 This is a type of programming language that has well structured steps and complex
procedures within its programming to compose a complete program.
 It has a systematic order functions and commands to complete a task or a program. C,
FORTRAN, ALGOL, BASIC, COBOL are some examples.
Low Level Languages
 Low-level languages are the basic computer instructions or better known as machine codes.
 A computer cannot understand any instruction given to it by the user in English or any other
high-level language. These low-level languages are very easily understandable by the machine.
 The main function of low-level languages is to interact with the hardware of the computer. They
help in operating, syncing and managing all the hardware and system components of the
computer. They handle all the instructions which form the architecture of the hardware systems.
Types of Low-Level Language
Machine Language:
 Machine language is also called as binary language. Binary means the language consists of
0‘s and 1‘s. This is the only language understand by computer.
 So the computer directly executes the program without any translation. In the earliest days of
computers, the only programming languages available were machine languages.
 Example Addition of two numbers
2→0010
+
3→0011
__________
5→0101
Assembly Language:
 Here binary language of 0’s, 1’s are replaced by mnemonics. These languages were known as
symbolic languages.
 Assembly language is the combination of operation codes and operands.
 ADD, SUB, MOV are some of examples of mnemonics. By remembering these mnemonics it
is easy to perform the operation and does not depend on machine.
 Computer does not understand Assembly language; it must be translated into the machine
language. A special program called an Assembler translates symbolic code into the machine
language. Hence they are called as Assembly language.
 Example: 2+3 =5 or c=2+3
MOV #2, R0
MOV #3, R1
ADD R0, R1
MOV R1, c
Algorithm:
Algorithm: An algorithm is a step-by-step procedure to solve a specific problem.

Characteristics or properties of an algorithm:


 Input: An algorithm has zero or more inputs. Each that contains a fundamental operator
must accept zero or more inputs.
 Output: An algorithm produces at least one output. Every instruction that contains a
fundamental operator must accept zero or more inputs.
 Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to
interpret.
 Finiteness: An algorithm must terminate after a finite number of steps in all test cases.
 Effectiveness: An algorithm must be developed by using very basic, simple, and feasible
operations so that one can trace it out by using just paper and pencil.
Advantages of Algorithms:
1. It is a step-wise representation of a solution to a given problem, which makes it easy to
understand. 2. An algorithm uses a definite procedure.
2. It is not dependent on any programming language, so it is easy to understand for anyone even
without programming knowledge.
3. Every step in an algorithm has its own logical sequence so it is easy to debug.
4. By using algorithm, the problem is broken down into smaller pieces or steps hence, it is easier
for programmer to convert it into an actual program.
Disadvantages of Algorithms:
1. Algorithms is Time consuming.
2. Difficult to show Branching and Looping in Algorithms.
3. Big tasks are difficult to put in Algorithms.
Algorithm writing by using an example.
a) Write an algorithm to add two numbers entered by the user.
Step 1: Start
Step 2: Declare the variables a,b,c as integer data type.
Step 3: Read the values of a & b.
Step 4: Calculate the sum of the two integers c=a+b
Step 5: Display sum as the result
Step 6: End
b) Write an algorithm to test the equality of two numbers.
Step 1: Start
Step 2: Input first number as A
Step 3: Input second number as B
Step 4: if A = B print “ Equal” else print ”Not Equal”
Step 5: End

Flowchart:

A flowchart is a graphical representation of an algorithm or process, using different symbols like


arrows, rectangles, and ovals.

Flowchart Symbols
Pseudo code:
Pseudo code is a term which is often used in programming and algorithm based fields. It is a
methodology that allows the programmer to represent the implementation of an algorithm.
Algorithms are represented with the help of pseudo codes as they can be interpreted by programmers
no matter what their programming background or knowledge is.

Introduction to Compilation and Execution:


 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.

 The c compilation process converts the source code taken as input into the object code or
machine code.
 The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.
Preprocessor
 The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it.
 For example, if <stdio.h>, the directive is available in the program, then the preprocessor
interprets the directive and replace this directive with the content of the 'stdio.h' file.
 The input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor converts the
source code into expanded source code. The extension of the expanded source code would
be hello.i.

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.
 The expanded source code is passed to the compiler, and the compiler converts this expanded
source code into assembly code. For example, The extension of the assembly code would be
hello.s.

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,' If the name of the source file is 'hello.c', then
the name of the object file would be 'hello.obj'.

Linker
 A linker is a special program that combines the object files, generated by the compiler/assembler
and other pieces of code to an executable file that has a .exe extension.
 In the object file, the linker searches and appends all libraries needed for the execution of the
file.
 The extension of the executable file is '.exe,' i.e., ‘hello.exe’.

Loader
Loader takes input of executable files from linker, loads it to main memory, and prepares this code
for execution by computer. Loader allocates memory space to program.
Data Types in C
 Data types are fundamental in computer programming because they enable a programmer to
determine the type of data that is being utilized and saved precisely.
 Data type specifies what type of data , how much space should be allocated to that data

Data types in C can be divided into 3 main categories-


 primitive data types,
 Derived data types,
 User-defined data types.

Primitive Data Types:

 Primitive data types are built in data types. They are directly supported by machine. They are
also known as fundamental data types.
 This data type includes-
 integer data type (int),
 character data type, i.e., character (char),
 floating-point data type, i.e., containing fractional part (float),
 double data type (double), which is the same as float data type, but it occupies twice
the storage space.
 Void data type(void)
 Variables declared with primitive data type can store only one value at a time and cannot be
divided into smaller parts.
In the table below, we have specified the various primitive data types along with specifier, range,
and memory occupied.

Integer Data Type in C


The integer data type in C is one of the most common data types and is represented by int. It refers
to a whole number that can be either positive or negative.

Size
Data type Format Specifier Range
bytes bits
int %d, %i 2 16 -32,768 to 32,767
unsigned int %u 2 16 0 to 65,535
Same as
signed int %d, %i Same as int Same as int
int
short int %hd 2 16 -32,768 to 32,767
unsigned short int %hu 2 16 0 to 65,535
signed short int %hd 2 16 Same as short int
-2,147,483,648 to
long int %ld, %li 4 32
2,147,483,647

signed long int %ld, %li 4 32 Same as long int


unsigned long int %lu 4 32 0 to 4,294,967,295
long long int %lld, %lli 8 64 -263 to 263 – 1
unsigned long
%llu 8 64 264 – 1
long int
Character Data Type in C
The character data type is represented by the char keyword and is used to store a variable with only
a single character. The size of the char data type is 1 byte (i.e., 8 bits). It has two subtypes- signed
char and unsigned char. The range for these is -127 to 128 and 0 to 255, respectively.
Size
Data type Format Specifier Range
bytes bits
char %c 1 8 -128 to 127
signed char %c 1 8 -128 to 127
unsigned char %c 1 8 0 to 255

Float Data Type in C


The float data type allows programs to represent real numbers with decimals like 3.14 in the
program’s code base instead of integers like 3 only. The float data type size is 4 bytes, i.e., it
occupies 4 bytes of memory. It ranges between -3.4E-38 to +3.4E+38.
Size
Data type Format Specifier Range
bytes bits
float %f 4 32 -3.4E-38 to +3.4E+38
double %lf 8 64 1.7E-308 to 1.7E+308
long double %Lf 10 80 3.4E-4932 to 1.1E+4932

Variables in C:
 It is a name given to a memory location where we can store a value (or) Data name that is
used to store value of data
 We can change the value of a variable in C or any other language, and we can also reuse it
multiple times.
How to declare a variable:
A variable can be declared by specifying its data type followed by the variable name. First choose a
data type like int, float, char, double.
Declare the variable
Syntax: data type variable1, variable2, variable3…….. ;
Example Declaration:
 int age; - declares an integer variable named age
 float salary; - declares a float variable named salary
 char initial; - declares a char variable named initial
Declaring and initializing:
 int age=25; - declares and initializes age to 25
 float salary=500.25; - declares and initializes salary to 500.23
 char initial=’A’; - declares and initializes initial to ‘A’
Multiple Declarations :
 int a ,b ,c ; // declares three integer variables a,b,c
 float x=12.05, y=3.8; // declares and initializes float variables x, y
Rules for constructing name of a Variable in C:
 A variable name can consist of digits, alphabets, and special symbol underscore _
 The name of the variable must not begin with a digit but begin with alphabet or underscore.
 Keywords cannot be used as variable ( there are 32 keywords in c which have predefined
meaning. Keywords like include, if, while, for, switch, break etc.)
 There must be no spaces or blanks in the variable name.
 The maximum length of a variable must be less than or equal to 31
Examples:

Correct Wrong
int var1; int 1var;
int my_var; iny my$var;
int abc; char else;
int average; int my var:
int sum12; int sum,12;
int _sum; int roll number;
int roll_number;

Constants:
 If you don't want others (or yourself) to change existing variable values, you can use
the constants
 This will declare the variable as "constant", which means unchangeable and read-only:
 Constants are fixed values not going to be changed throughout the program

Constants in C are declared in mainly two ways. The two ways are:
 Using const Keyword
 Using #define Preprocessor Directive
Declaring Constants in C using const Keyword
 Constants in C can be defined by using the const Keyword.
 The values of the variables which are defined using the const keyword cannot be changed
during the execution of the program.
Here is how we create constants in C using the const keyword.
Syntax: const data_type var_name = value;
const int MAX_VALUE = 100;
Declaring Constants in C using #define
We can also use #define to create constants in C. #define is a Preprocessor Directive. Here’s an
Example:
#define MAX_VALUE 100
 we have to initialize the constant variables at declaration.
 Otherwise, the variable will store some garbage value and we won’t be able to change it
Example program-1:
include <stdio.h>
int main( )
{
const float PI = 3.14;
float radius = 5.0;
// Using the constant PI
float area = PI * radius * radius;
printf("The area of circle is %f", area);
return 0;
}
Output: The area of circle is 78.500000
Example program-2:
#include <stdio.h>
#define PI 3.14
int main( )
{
float radius = 5.0;
// Using the constant PI
float area = PI * radius * radius;
printf("The area of circle is %f", area);
return 0;
}
Output: The area of circle is 78.500000

Tokens in C:
A token in C can be defined as the smallest individual element of the C programming language that is
meaningful to the compiler. It is the basic component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords
 The keywords are pre-defined or reserved words in a programming language.
 Each keyword is meant to perform a specific function in a program. Since keywords are
referred names for a compiler, they can’t be used as variable names.
 C language supports 32 keywords which are given below:

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
2. Identifiers
Identifiers in C are used for naming variables, functions, arrays, structures, etc. these are the user-
defined words.
It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the starting
letter should be either an underscore or an alphabet.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.
3. Constants
The constants refer to the variables with fixed values. They are like normal variables but with the
difference that their values cannot be modified in the program once they are defined. Constants
may belong to any of the data types.
Examples of Constants in C
const int a = 20;
4. Strings
Strings are nothing but an array of characters ended with a null character (‘\0’). This null character
indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a character
is enclosed in single quotes in C.
Examples of String
Now, we describe the strings in different ways:
 char a[12] = "cprogramming"; // The compiler allocates the 12 bytes to the 'a' array.
 char a[] = " cprogramming "; // The compiler allocates the memory at the run time.
 char a[12] = { ‘c’,’p’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’i’,’n’,’g’,'\0'}; // String is represented in the
form of characters.

5. Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be used
for some other purpose. Some of these are listed below:
 Brackets[]: Opening and closing brackets are used as array element references. These indicate
single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function
parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
 Comma (, ): It is used to separate more than one statement like for separating parameters in
function calls.
 Colon(:): It is an operator that essentially invokes something called an initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity.
That’s why each individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
 Assignment operator(=): It is used to assign values and for logical operation validation.
 Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
 Period (.): Used to access members of a structure or union.
 Tilde(~): Bitwise One’s Complement Operator.

6. Operators
 In C language, operators are symbols that represent operations to be performed on one or
more operands. They are the basic components of the C programming.
 An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables.
 The values and variables used with operators are called operands. So we can say that the
operators are the symbols that perform operations on operands.
For example: c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands. The addition
operator tells the compiler to add both of the operands ‘a’ and ‘b’.
Types of Operators in C
C language provides a wide range of operators that can be classified into 6 types based on their
functionality:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and Decrement operators
7. Comma operator
8. Ternary or Conditional operator
9. Sizeof operator

1. Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.

S. No. Symbol Operator Description Syntax

Adds two numeric


1 + Plus a+b
values.

Subtracts right
2 – Minus operand from left a–b
operand.

Multiply two
3 * Multiply a*b
numeric values.

Divide two
4 / Divide a/b
numeric values.

Returns the
5 % Modulus a%b
remainder
Example of C Arithmetic Operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf("a + b = %d\n", a + b); 30
printf("a - b = %d\n", a - b); 20
printf("a * b = %d\n", a * b); 125
printf("a / b = %d\n", a / b); 5(QUOTIENT)
printf("a % b = %d\n", a % b); 0(REM)
return 0;
}
2. Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All these operators
are binary operators that return true or false values as the result of comparison.
These are a total of 6 relational operators in C:

S.
Symbol Operator Description Syntax
No.

Returns true if the left operand is less than the right


1 < Less than a<b
operand. Else false

Returns true if the left operand is greater than the


2 > Greater than a>b
right operand. Else false

Less than or Returns true if the left operand is less than or equal
3 <= a <= b
equal to to the right operand. Else false

Greater than or Returns true if the left operand is greater than or


4 >= a >= b
equal to equal to right operand. Else false

5 == Equal to Returns true if both the operands are equal. a == b

6 != Not equal to Returns true if both the operands are NOT equal. a != b
C program to illustrate the relational operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);
return 0;
}
Here, 0 means false and 1 means true.

3. Logical Operator in C
 Logical Operators are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition in consideration. The result of the operation of a
logical operator is a Boolean value either true or false.

S. No. Symbol Operator Description Syntax

1 && Logical AND Returns true if both the operands are true. a && b

2 || Logical OR Returns true if both or any of the operand is true. a || b

3 ! Logical NOT Returns true if the operand is false. !a

Example of Logical Operators in C


#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results. Here logical operator used between conditions
printf("a && b : %d\n", a<b && b<a); 0&&1=0
printf("a && b : %d\n", a>b && b<a); 1&&1=1
printf("a || b : %d\n", a<b || b<a); 0||1=1
printf("!a: %d\n", !a); 0
return 0;
}

4. Bitwise Operators in C
 The Bitwise operators are used to perform bit-level operations on the operands.
 The operators are first converted to bit-level and then the calculation is performed on the
operands.
 Mathematical operations such as addition, subtraction, multiplication, etc. can be performed
at the bit level for faster processing.

S.
Symbol Operator Description Syntax
No.

Performs bit-by-bit AND operation and returns


1 & Bitwise AND a&b
the result.

Performs bit-by-bit OR operation and returns the


2 | Bitwise OR a|b
result.

Performs bit-by-bit XOR operation and returns


3 ^ Bitwise XOR a^b
the result.

Bitwise First
4 ~ Flips all the set and unset bits on the number. ~a
Complement

Shifts the number in binary form by one place in


5 << Bitwise Leftshift a << b
the operation and returns the result.

Shifts the number in binary form by one place in


6 >> Bitwise Rightshilft a >> b
the operation and returns the result.

C program to illustrate the bitwise operators


#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf("a & b: %d\n", a & b); a & b: 1
printf("a | b: %d\n", a | b); a | b: 29
printf("a ^ b: %d\n", a ^ b); a ^ b: 28
printf("~a: %d\n", ~a); ~a: -26
printf("a >> b: %d\n", a >> b); a >> b: 0
printf("a << b: %d\n", a << b); a << b: 800
return 0;
}

5. Assignment Operators in C
 Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value.
 The value on the right side must be of the same data type as the variable on the left side
otherwise the compiler will raise an error.
 The assignment operators can be combined with some other operators in C to provide
multiple operations using single operator. These operators are called compound operators.

S. No. Symbol Operator Description Syntax

Simple Assign the value of the right operand to the left


1 = a=b
Assignment operand.

Add the right operand and left operand and assign


2 += Plus and assign a += b
this value to the left operand.

Minus and Subtract the right operand and left operand and
3 -= a -= b
assign assign this value to the left operand.

Multiply and Multiply the right operand and left operand and
4 *= a *= b
assign assign this value to the left operand.

Divide and Divide the left operand with the right operand and
5 /= a /= b
assign assign this value to the left operand.

6 %= Modulus and Assign the remainder in the division of left a %= b


S. No. Symbol Operator Description Syntax

assign operand with the right operand to the left operand.

Performs bitwise AND and assigns this value to


7 &= AND and assign a &= b
the left operand.

Performs bitwise OR and assigns this value to the


8 |= OR and assign a |= b
left operand.

Performs bitwise XOR and assigns this value to


9 ^= XOR and assign a ^= b
the left operand.

Right shift and Performs bitwise Right shift and assign this value a >>=
10 >>=
assign to the left operand. b

Left shift and Performs bitwise Left shift and assign this value to a <<=
11 <<=
assign the left operand. b

Example of C Assignment Operators


#include <stdio.h>
int main()
{
int a = 25, b = 5;
// using operators and printing results
printf("a = b: %d\n", a = b); a = b: 5
printf("a += b: %d\n", a += b); a += b: 10
printf("a -= b: %d\n", a -= b); a -= b: 5
printf("a *= b: %d\n", a *= b); a *= b: 25
printf("a /= b: %d\n", a /= b); a /= b: 5
printf("a %%= b: %d\n", a %= b); a %= b: 0
printf("a &= b: %d\n", a &= b); a &= b: 0
printf("a |= b: %d\n", a |= b); a |= b: 5
printf("a >>= b: %d\n", a >>= b); a >>= b: 0
printf("a <<= b: %d\n", a <<= b); a <<= b: 0
return 0;
}
6. Increment and Decrement operator:
 The increment (++) and decrement (--) operators in C are unary operators for incrementing
and decrementing the numeric values by 1 respectively.
 The incrementation and decrementation are one of the most frequently used operations in
programming for looping, array traversal, pointer arithmetic, and many more.
Increment Operator in C
The increment operator ( ++ ) is used to increment the value of a variable in an expression by 1. It
can be used on variables of the numeric type such as integer, float, character, pointers, etc.
Syntax of Increment Operator
Increment Operator can be used in two ways which are as follows:
++a // AS Preincrement
a++ // AS Postincrement
where a is variable.
1. Pre-Increment
In pre-increment, the value is incremented first and then use the updated value in the expression.
Example
result = ++var1;
The above expression can be expanded as
var = var + 1;
result = var;

2. Post-Increment
In post-increment, first use value of a variable and then increment operation is performed It is
also known as postfix increment.
Example
result = var1++;
The above expression is equivalent
result = var;
var = var + 1;
Example of Increment Operator
#include <stdio.h>
int main()
{
int a = 5,b=5,x,y;
x= ++a; // PREFIX
printf("Prefix Increment: %d\n", x);
x = b++; // POSTFIX
printf("Postfix Increment: %d", x);
return 0;
}
Output
Prefix Increment: 6
Postfix Increment: 5
As we can see in postfix, the value is incremented after the assignment operator is done.
Decrement Operator in C
The decrement operator is used to decrement the value of a variable in an expression. The
decrement operator can also be used in two ways:
--a // AS PREFIX
a-- // AS POSTFIX
where a is variable.
1. Pre-Decrement Operator
In the Pre-Decrement, the value is first decremented and then used inside the expression.
Example
result = --var;
which can be expanded to
var = var - 1;
result = var;
2. Post-Decrement Operator
In the Post-Decrement, the value is first used inside the expression and then decremented.
Example
result = var--;
The above expression can be expanded as
result = var;
var = var-1;
Example of Decrement Operator
#include <stdio.h>
int main( )
{
int a = 5,b=5,x,y;
x = --a; // PREFIX
printf("Prefix = %d\n", x);
x = b--; // POSTFIX
printf("Postfix = %d", x);
return 0;
}
Output:
Prefix = 4
Postfix = 5
7. Comma Operator ( , )
 The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator.
Syntax: operand1, operand2
8. Conditional Operator ( ? : )
The conditional operator is the only ternary operator in C.
Syntax: variable = Expression1 ? Expression2 : Expression3;
Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we
will execute and return the result of Expression2 otherwise if the condition(Expression1)
is false then we will execute and return the result of Expression3.
Example program for conditional or ternary operator
#include <stdio.h>
int main()
{
int a = 5, b = 4;
(a > b) ? printf("a is greater than b that is %d > %d",a, b): printf("b is greater than a that is
%d > %d",b, a);
return 0;
}
Output
a is greater than b that is 5 > 4
9. Sizeof operator:
 sizeof is much used in the C programming language.
 It is a compile-time unary operator which can be used to compute the size of its operand.
 The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
 Basically, the sizeof the operator is used to compute the size of the variable or datatype.
Syntax
sizeof (operand)

Operator Precedence and Associativity in C


 In C, it is very common for an expression or statement to have multiple operators and in
these expressions; there should be a fixed order or priority of operator evaluation to avoid
ambiguity.
 Operator Precedence and Associativity is the concept that decides which operator will be
evaluated first in the case when there are multiple operators present in an expression.
 The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.

Precedence Operator Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right

1 . Member selection via object name left-to-right

-> Member selection via a pointer left-to-right

a++ , a– Postfix increment/decrement (a is a variable) left-to-right

++a , –a Prefix increment/decrement (a is a variable) right-to-left

+,– Unary plus/minus right-to-left


2
!,~ Logical negation/bitwise complement right-to-left

(type) Cast (convert value to temporary value of type) right-to-left


Precedence Operator Description Associativity

* Dereference right-to-left

& Address (of operand) right-to-left

sizeof Determine size in bytes on this implementation right-to-left

3 *,/,% Multiplication/division/modulus left-to-right

4 +,– Addition/subtraction left-to-right

5 << , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right


6
> , >= Relational greater than/greater than or equal to left-to-right

7 == , != Relational is equal to/is not equal to left-to-right

8 & Bitwise AND left-to-right

9 ^ Bitwise XOR left-to-right

10 | Bitwise OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

= Assignment right-to-left

+= , -= Addition/subtraction assignment right-to-left


14
*= , /= Multiplication/division assignment right-to-left

%= , &= Modulus/bitwise AND assignment right-to-left


Precedence Operator Description Associativity

^= , |= Bitwise exclusive/inclusive OR assignment right-to-left

<<=, >>= Bitwise shift left/right assignment right-to-left

15 , expression separator left-to-right

Example problem-1:

Example problem-2:
Example problem-3:

Example problem-4:

Input and Output functions:


 Input and output (I/O) in C programming handle data entering and leaving a program. The input
refers to feeding the information to the compiler and the output refers to displaying the
information on the screen.
 Input /Output functions are included in the user program by using the header file <stdio.h>
which stands for standard input-output header.
 The stdio.h header file provides essential functions like scanf() for input and printf() for output.
Format Specifier for different data types
Data type Format Specifier
int %d
float %f
char %c
long %l or %ld
double %lf
printf( ):
The printf( ) function is used to print the output of the given statements. To show any value,
including float, integer, character, string, etc. on the console screen, a C program uses the printf( )
function. This function is a pre-defined function because it is declared in the header file stdio.h.
To print the statement on the screen
Printf(“ write here the statement we want print”);
To print the single value:
Syntax:
printf("Format Specifier", var1);
Example:
For integer:- printf(“%d”,var);
For float:- printf(“%f”,var);
For char:- printf(“%c”,var);
To print the multiple values:
Syntax:
printf("Format Specifiers", var1, var2,…..,varn);
By using the above printf statement, we can print same datatype values or different datatype values
are at a time.
Example:
For printing 3 integer values:- printf(“%d%d%d”,var1,var2,var3);
For printing int, float, char values:- printf(“%d%f%c”,var1,var2,var3); /* var1 is integer, var2
float,var3 is char*/
scanf( ):
The scanf function is used to read or extract any value from the user’s keyboard. These values can be
of any data type, including integer, float, character, string, and many more. This function is also a
pre-defined function because it is declared in the header file stdio.h.
To read the single value:
Syntax:
scanf("Format Specifier", &var1);
Example:
For integer:- scanf(“%d”,&var);
For float:- scanf(“%f”,&var);
For char:- scanf(“%c”,&var);
To read the multiple values:
Syntax:
scanf("Format Specifiers", &var1, &var2,…..,&varn);
By using the above scanf statement, we can read same datatype values or different datatype values
are at a time.
Example:
For reading 3 integer values:- scanf(“%d%d%d”,&var1,&var2,&var3);
For reading int, float, char values:- scanf(“%d%f%c”,&var1,&var2,&var3); /* var1 is integer, var2
float,var3 is char*/

Type Casting and Conversion in C


 In a programming language, the expression contains data values of the same datatype or different
data types.
 When the expression contains similar datatype values then it is evaluated without any problem.
 But if the expression contains two or more different datatype values then they must be converted
to the single datatype of destination datatype. Here, the destination is the location where the final
result of that expression is stored.
if x is float, x=2*4.2 x=8.400000
if x is int, x=2*4.2 x=8
 For example, the multiplication of an integer data value with the float data value and storing the
result into a float variable. In this case, the integer value must be converted to float value so that
the final result is a float datatype value.
 In a c programming language, the data conversion is performed in two different methods as
follows...
 Type Conversion
 Type Casting
Type Conversion
 The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler.
 Sometimes type conversion is also called implicit type conversion. The implicit type
conversion is automatically performed by the compiler.
 When compiler converts implicitly, there may be a data loss.
 For example, in c programming language, when we assign an integer value to a float variable the
integer value automatically gets converted to float value by adding decimal value 0.
 And when a float value is assigned to an integer variable the float value automatically gets
converted to an integer value by removing the decimal value.
 To understand more about type conversion observe the following...
 int i = 10 ;
 float x = 15.5 ;
 char ch = 'A' ;
i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i
x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; =======> Here the ASCII value of A (65) is assigned to i
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 95;
float x = 90.99;
char ch = 'A';
i = x;
printf("i value is %d\n",i);
x = i;
printf("x value is %f\n",x);
i = ch;
printf("i value is %d\n",i);
}
Output:
i value is 90
x value is 95.000000
i value is 65
 In the above program, we assign i = x, i.e., float variable value is assigned to the integer
variable. Here, the compiler automatically converts the float value (90.99) into integer value
(90) by removing the decimal part of the float value (90.99) and then it is assigned to variable
i.
 Similarly, when we assign x = i, the integer value (90) gets converted to float value
(90.000000) by adding zero as the decimal part.

Typecasting
 Typecasting is also called an explicit type conversion.
 Compiler converts data from one data type to another data type implicitly. When compiler
converts implicitly, there may be a data loss.
 In such a case, we convert the data from one data type to another data type using explicit type
conversion. To perform this we use the unary cast operator.
 To convert data from one type to another type we specify the target data type in parenthesis as a
prefix to the data value that has to be converted.
 The general syntax of typecasting is as follows.
(TargetDatatype) DataValue
Example
int total = 450, marks = 600 ;
float avg ;
avg = (float) total / marks * 100 ;
 In the above example code, both total and marks are integer data values. When we perform
total/ marks the result is a float value, but the destination (avg) datatype is a float. So we use
type casting to convert total and marks into float data type.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
float avg ;
printf("Enter any three integer values : ");
scanf(“%d%d%d”,&a,&b,&c);
avg = (a + b + c) / 3 ;
printf(“Avg before casting: %f”, avg);
avg=(float)(a+b+c)/3;
printf(“Avg after casting: %f”, avg);
return 0;
}
Output:
Enter any three integer values : 2 4 5
Avg before casting: 3.000000
Avg after casting: 3.666666.

Hierarchy of datatypes
The conversion will occur in the hierarchy as follows.

Problem solving strategies:


 There are two approaches for designing an algorithm. these approaches include
 Top-Down Approach
 Bottom-up approach
Top-Down Approach:
 Breaking down a complex problem into smaller, more manageable sub-problems and solving
each sub-problem individually.
 Designing a system starting from the highest level of abstraction and moving towards the lower
levels.
Bottom-Up Approach:
 Building a system by starting with the individual components and gradually integrating them to
form a larger system.
 Solving sub-problems first and then using the solutions to build up to a solution of a larger
problem.
 Note: Both approaches have their own advantages and disadvantages and the choice between
them often depends on the specific problem being solved.

Performance Analysis of an algorithm:


 Performance of an algorithm is calculated based on the time complexity and space complexity.
Time Complexity
 Time complexity is the amount of time required to execute an algorithm.
 It's a crucial aspect of algorithm analysis as it helps understand how efficiently an algorithm
performs, particularly as the size of the input data increases.
 Time complexity can refer to the worst-case (usually represented), average-case, or best-case
scenario for an algorithm's running time. The worst-case time complexity is the most
commonly used because it guarantees the maximum time taken for any input.
Space Complexity
 Space complexity measures the total amount of memory or storage space an algorithm needs
to complete.
 It is an important metric for understanding how efficient an algorithm is in terms of memory
usage, especially in environments where memory resources are limited.
 This includes both the space taken up by the input data and any additional space used by the
algorithm for variables, data structures, and function calls.

You might also like