0% found this document useful (0 votes)
58 views33 pages

Unit I Ip

The document provides an introduction to programming and problem solving, covering the history of computers, basic computer organization, programming languages, and problem-solving techniques. It outlines the evolution of computing devices from early tools like the abacus to modern computers, detailing the characteristics and classifications of programming languages, particularly C. Additionally, it discusses the compilation process and structure of a C program, emphasizing the importance of algorithms and problem-solving strategies in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views33 pages

Unit I Ip

The document provides an introduction to programming and problem solving, covering the history of computers, basic computer organization, programming languages, and problem-solving techniques. It outlines the evolution of computing devices from early tools like the abacus to modern computers, detailing the characteristics and classifications of programming languages, particularly C. Additionally, it discusses the compilation process and structure of a C program, emphasizing the importance of algorithms and problem-solving strategies in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

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, Operators, Type Conversion, and Casting.
Problem solving techniques: Algorithmic approach, characteristics of algorithm, Problem solving strategies:
Top-down approach, Bottom-up approach, Time and space complexities of algorithms.

History of Computers
What is a Computer?
Definition: Computer is an advanced electronic device that takes raw data as an input from the user and processes
it under the control of a set of instructions (called program), produces a result (output), and saves it for future
use
Earliest Computer
• Originally calculations were computed by humans, whose job title was computers.
• These human computers were typically engaged in the calculation of a mathematical expression.
• The calculations of this period were specialized and expensive, requiring years of training in
mathematics.
• The first use of the word "computer" was recorded in 1613, referring to a person who carried out
calculations, or computations, and the word continued to be used in that sense until the middle of the
20th century.
Tally Sticks
A tally stick was an ancient memory aid device to record and document numbers, quantities, or even messages.

Abacus
• An abacus is a mechanical device used to aid an individual in performing mathematical calculations.
• The abacus was invented in Babylonia in 2400 B.C.
• The abacus in the form we are most familiar with was first used in China in around 500 B.C.
• It used to perform basic arithmetic operations.

Napier’s Bones
• Invented by John Napier in 1614.
• Allowed the operator to multiply, divide and calculate square and cube roots by moving the rods around
and placing them in specially constructed boards.
Slide Rule
• Invented by William Oughtred in 1622.
• Is based on Napier's ideas about logarithms.
• Used primarily for
– multiplication
– division
– roots
– logarithms
– Trigonometry
• Not normally used for addition or subtraction.

Pascaline
• Invented by Blaise Pascal in 1642.
• It was its limitation to addition and subtraction.
• It is too expensive.

Stepped Reckoner
• Invented by Gottfried Wilhelm Leibniz in 1672.
• The machine that can add, subtract, multiply and divide automatically.

Jacquard Loom
• The Jacquard loom is a mechanical loom, invented by Joseph-Marie Jacquard in 1881.
• It an automatic loom controlled by punched cards.

Arithmometer
• A mechanical calculator invented by Thomas de Colmar in 1820.
• The first reliable, useful and commercially successful calculating machine.
• The machine could perform the four basic mathematic functions.
• The first mass-produced calculating machine.

Difference Engine and Analytical Engine


• It an automatic, mechanical calculator designed to tabulate polynomial functions.
• Invented by Charles Babbage in 1822 and 1834.
• It is the first mechanical computer.

First Computer Programmer


• In 1840, Augusta Ada Byron suggests to Babbage that he use the binary system.
• She writes programs for the Analytical Engine.
Scheutzian Calculation Engine
• Invented by Per Georg Scheutz in 1843.
• Based on Charles Babbage's difference engine and it is the first printing calculator.
Tabulating Machine
• Invented by Herman Hollerith in 1890.
• To assist in summarizing information and accounting.

Havard Mark 1
• Also known as IBM Automatic Sequence Controlled Calculator (ASCC).
• Invented by Howard H. Aiken in 1943 and it is the first electro-mechanical computer.

Z1
• The first programmable computer and Created by Konrad Zuse in Germany from 1936 to 1938.
• To program the Z1 required that the user insert punch tape into a punch tape reader and all output was
also generated through punch tape.

Atanasoff-Berry Computer (ABC)


• It was the first electronic digital computing device.
• Invented by Professor John Atanasoff and graduate student Clifford Berry at Iowa State University
between 1939 and 1942.
ENIAC
• ENIAC stands for Electronic Numerical Integrator and Computer.
• It was the first electronic general-purpose computer.
• Completed in 1946 and Developed by John Presper Eckert and John W. Mauchl.

UNIVAC 1
• The UNIVAC I (UNIVersal Automatic Computer 1) was the first commercial computer.
• Designed by J. Presper Eckert and John Mauchly.

EDVAC
• EDVAC stands for Electronic Discrete Variable Automatic Computer
• The First Stored Program Computer • Designed by Von Neumann in 1952.
• It has a memory to hold both a stored program as well as data.

The First Portable Computer


• Osborne 1 – the first portable computer.
• Released in 1981 by the Osborne Computer Corporation.

The First Computer Company


• The first computer company was the Electronic Controls Company.
• Founded in 1949 by J. Presper Eckert and John Mauchly.

Computer Generations
There are five generations of computer:
First generation – 1946 – 1958
Second generation – 1959 – 1964
Third generation – 1965 – 1970
Fourth generation – 1971 – today
Fifth generation – Today to future

The First Generation


• The first computers used vacuum tubes for circuitry and magnetic drums for memory, and were often
enormous, taking up entire rooms.
• They were very expensive to operate and in addition to using a great deal of electricity, generated a lot
of heat, which was often the cause of malfunctions.
• First generation computers relied on machine language, the lowest-level programming language
understood by computers, to perform operations, and they could only solve one problem at a time.
• Input was based on punched cards and paper tape, and output was displayed on printouts

The Second Generation


• Transistors replaced vacuum tubes and ushered in the second generation of computers.
• One transistor replaced the equivalent of 40 vacuum tubes.
• Allowing computers to become smaller, faster, cheaper, more energy-efficient and more reliable.
• Still generated a great deal of heat that can damage the computer.
• Second-generation computers moved from cryptic binary machine language to symbolic, or assembly,
languages, which allowed programmers to specify instructions in words.
• Second-generation computers still relied on punched cards for input and printouts for output.
• These were also the first computers that stored their instructions in their memory, which moved from a
magnetic drum to magnetic core technology.

The Third Generation


• The development of the integrated circuit was the hallmark of the third generation of computers.
• Transistors were miniaturized and placed on silicon chips, called semiconductors, which drastically
increased the speed and efficiency of computers.
• Much smaller and cheaper compare to the second-generation computers.
• It could carry out instructions in billionths of a second.
• Users interacted with third generation computers through keyboards and monitors and interfaced with an
operating system, which allowed the device to run many different applications at one time with a central
program that monitored the memory.
• Computers for the first time became accessible to a mass audience because they were smaller and cheaper
than their predecessors.

The Fourth Generation


• The microprocessor brought the fourth generation of computers, as thousands of integrated circuits were
built onto a single silicon chip.
• As these small computers became more powerful, they could be linked together to form networks, which
eventually led to the development of the Internet.
• Fourth generation computers also saw the development of GUIs, the mouse and handheld devices.
The Fifth Generation
• Based on Artificial Intelligence (AI).
• Still in development.
• The use of parallel processing and superconductors is helping to make artificial intelligence a reality.
• The goal is to develop devices that respond to natural language input and are capable of learning and
self-organization.
• There are some applications, such as voice recognition, that are being used today.
Functionalities of a Computer:
If we look at it in a very broad sense, any digital computer carries out the following five functions
Step 1 - Takes data as input.
Step 2 - Stores the data/instructions in its memory and uses them as required.
Step 3 - Processes the data and converts it into useful information.
Step 4 - Generates the output.
Step 5 - Controls all the above four steps.

Block Diagram of a computer:


Input Unit:
This unit contains devices with the help of which we enter data into the computer. This unit creates
a link between the user and the computer. The input devices translate the information into a form understandable
by the computer.
CPU (Central Processing Unit):
CPU is considered as the brain of the computer. CPU performs all types of data processing operations. It stores
data, intermediate results, and instructions (program). It controls the operation of all parts of the computer.
CPU itself has the following three components
• ALU (Arithmetic Logic Unit)
• Memory Unit
• Control Unit

Arithmetic Logic Unit (ALU):


Data entered into computer is sent to RAM, from where it is then sent to ALU, where rest of data processing
takes place. All types of processing, such as comparisons, decision-making and processing of non-numeric
information takes place here and once again data is moved to RAM.
Control Unit:
As name indicates, this part of CPU extracts instructions, performs execution, maintains and directs operations
of entire system.
Functions of Control Unit
Control unit performs following functions –
• It controls all activities of computer
• Supervises flow of data within CPU
• Directs flow of data within CPU
• Transfers data to Arithmetic and Logic Unit
• Transfers results to memory
• Fetches results from memory to output devices
Memory Unit:
This is unit in which data and instructions given to computer as well as results given by computer are stored.
Unit of memory is "Byte".
1 Byte = 8 Bits
Output Unit:
The output unit consists of devices with the help of which we get the information from the computer. This unit
is a link between the computer and the users. Output devices translate the computer's output into a form
understandable by the users.

Introduction to programming languages:


History of Programming Languages:
• At the beginning there was only machine language: a sequence of bits (binary with: electric switches on
and off, or punched cards) that directly controls a processor, causing it to add, compare, move data from
one place to another, etc.
Example: GCD program in x86 machine language:

• Assembly languages were invented to allow machine level/processor operations to be expressed with
mnemonic abbreviations
For example, to add two numbers, you might write an instruction in assembly code like this:
ADDF3 R1, R2, R3
• A program called assembler is used to convert assembly language programs into machine code

Example: GCD program in x86 assembly:

• Assemblers were eventually augmented with elaborate “macro expansion” facilities to permit
programmers to define parameterized abbreviations for common sequences of instructions.
• Problem: each different kind of computer had to be programmed in its own assembly language
• People began to wish for machine-independent languages. These wishes led in the mid-1950s to the
development of standard higher-level languages compiled for different architectures by compilers
Today there are thousands of high-level programming languages, and new ones continue to emerge
Most Popular Programming Languages –
• C
• Python
• C++
• Java
• SCALA
• C#
• R
• Ruby
• Go
• Swift
• JavaScript
Classifications of Programming Languages

Characteristics of a programming Language –


• A programming language must be simple, easy to learn and use, have good readability, and be
human recognizable.
• Abstraction is a must-have Characteristics for a programming language in which the ability to
define the complex structure and then its degree of usability comes.
• A portable programming language is always preferred.
• Programming language’s efficiency must be high so that it can be easily converted into a machine
code and its execution consumes little space in memory.
• A programming language should be well structured and documented so that it is suitable for
application development.
• Necessary tools for the development, debugging, testing, maintenance of a program must be
provided by a programming language.
• A programming language should provide a single environment known as Integrated Development
Environment (IDE).
• A programming language must be consistent in terms of syntax and semantics.
Basic Terminologies in Programming Languages:
• Algorithm: A step-by-step procedure for solving a problem or performing a task.
• Variable: A named storage location in memory that holds a value or data.
• Data Type: A classification that specifies what type of data a variable can hold, such as integer,
string, or Boolean.
• Function: A self-contained block of code that performs a specific task and can be called from
other parts of the program.
• Control Flow: The order in which statements are executed in a program, including loops and
conditional statements.
• Syntax: The set of rules that govern the structure and format of a programming language.
• Comment: A piece of text in a program that is ignored by the compiler or interpreter, used to add
notes or explanations to the code.
• Debugging: The process of finding and fixing errors or bugs in a program.
• IDE: Integrated Development Environment, a software application that provides a comprehensive
development environment for coding, debugging, and testing.
• Operator: A symbol or keyword that represents an action or operation to be performed on one or
more values or variables, such as + (addition), – (subtraction), * (multiplication), and / (division).
• Statement: A single line or instruction in a program that performs a specific action or operation.
Advantages of programming languages:
1. Increased Productivity: Programming languages provide a set of abstractions that allow
developers to write code more quickly and efficiently.
2. Portability: Programs written in a high-level programming language can run on many different
operating systems and platforms.
3. Readability: Well-designed programming languages can make code more readable and easier to
understand for both the original author and other developers.
4. Large Community: Many programming languages have large communities of users and
developers, which can provide support, libraries, and tools.
Disadvantages of programming languages:
1. Complexity: Some programming languages can be complex and difficult to learn, especially for
beginners.
2. Performance: Programs written in high-level programming languages can run slower than
programs written in lower-level languages.
3. Limited Functionality: Some programming languages may not have built-in support for certain
types of tasks or may require additional libraries to perform certain functions.
4. Fragmentation: There are many different programming languages, which can lead to
fragmentation and make it difficult to share code and collaborate with other developers.
INTRODUCTION TO C LANGUAGE
• C is a structured programming language.
• It was developed by M. Dennis Ritchie in 1972 at Bell Laboratories.
• It is considered a high-level language because it allows the programmer to concentrate on the problem at
hand and not worry about the machine that the program will be using.
• While many languages claim to be machine independent, C is one of the closest to
achieving that goal.
• That is another reason why it is used by software developers whose applications have
to run on many different hardware platforms.
Compilation Process
The compilation and execution process of C can be divided in to multiple steps:
• Preprocessing Using a Preprocessor program to convert C source code in expanded source code.
"#include" and "#define" statements will be processed and replaced actually source codes in this
step.
• Compilation Using a Compiler program to convert C expanded source to assembly source code.
• Assembly Using a Assembler program to convert assembly source code to object code.
• Linking Using a Linker program to convert object code to executable code. Multiple units of
object codes are linked to together in this step.
• Loading Using a Loader program to load the executable code into CPU for execution.

Structure of a C Program
The structure of a C program can be mainly divided into six parts, each having its purpose. It makes the program
easy to read, easy to modify, easy to document, and makes it consistent in format.

Section Description
Consists of the description of the program, programmer's name,
Documentation and creation date. These are generally written in the form of
comments.
All header files are included in this section which contains
Link different functions from the libraries. A copy of these header
files is inserted into your code before compilation.
Includes preprocessor directive, which contains symbolic
Definition constants. E.g.: #define allows us to use constants in our code.
It replaces all the constants with its value in the code.
Global Includes declaration of global variables, function declarations,
Declaration static global variables, and functions.
For every C program, the execution starts from
Main()
the main() function. It is mandatory to include
Function
a main() function in every C program.
Includes all user-defined functions (functions the user
provides). They can contain the inbuilt functions and the
Subprograms
function definitions declared in the Global Declaration section.
These are called in the main() function.
Let's look at an example to understand the structure of a C program:
Example: Write a program to calculate our age.
/** //Documentation
* file: age.c
* author: you
* description: program to find our age.
*/
#include <stdio.h> //Link
#define BORN 2000 //Definition
int age(int current); //Global Declaration
void main() //Main() Function
{
int current = 2021;
printf("Age: %d", age(current));
return 0;
}
int age(int current)
{ //Subprograms
return current - BORN;
}
Output
Age: 21
Let's explore the code: Different sections of the above code
Documentation
In a C program, single-line comments can be written using two forward slashes i.e., //, and we can
create multiline comments using /* */. Here, we've used multi-line comments.
/**
* file: age.c
* author: you
* description: program to find our age.
*/
Link
All header files are included in this section. A header file is a file that consists of C declarations that can be used
between different files. It helps us in using others' code in our files. A copy of these header files is inserted into
your code before compilation.
#include <stdio.h>
Definition
A preprocessor directive in C is any statement that begins with the "#" symbol. The #define is a preprocessor
compiler directive used to create constants. In simple terms, #define basically allows the macro definition, which
allows the use of constants in our code.
#define BORN 2000
We've created a constant BORN which is assigned a value of 2000. Generally, uppercase letters
are preferred for defining the constants. The above constant BORN will be replaced by 2000 throughout our
code wherever used. #define is typically used to make a source program easy to modify and compile in different
execution environments. The define statement does not end with a semicolon.
Global Declaration
This section includes all global variables, function declarations, and static variables. The variables declared in
this section can be used anywhere in the program. They're accessible to all the functions
of the program. Hence, they are called global variables.
int age(int current);
We've declared our age function, which takes one integer argument and returns an integer.
Main() Function
In the structure of a C program, this section contains the main function of the code. The compiler starts execution
from the main() function. It can use global variables, static variables, inbuilt functions, and user-defined
functions. The return type of the main() function can be void and also not necessarily int.
int main(void)
{
int current = 2022;
printf("Age: %d", age(current));
return 0;
}

Here, we've declared a variable named current and assigned the value as 2022. Then we've called the printf()
function, with calls the age() function, which takes only one parameter.
Subprograms
This includes the user-defined functions called in the main() function. User-defined functions are
Generally written after the main() function irrespective of their order. When the user-defined function is called
from the main() function, the control of the program shifts to the called function, and when it encounters a return
statement, it returns to the main() function. In this case, we've defined the age() function, which takes one
parameter, i.e., the current year.
int age(int current)
{
return current - BORN;
}
This function is called in the main function. It returns an integer to the main function
Conclusion
• To conclude, the structure of a C program can be divided into six sections, namely –
Documentation, Link, Definition, Global Declaration, Main() Function, and Subprograms.
• The main() function is compulsory to include in every C program, whereas the rest are optional.
• A well-structured C program makes debugging easier and increases the readability and modularity of the
code.
Elements of C Programming Language
As every language has some basic geometrical rules and elements, similarly C language has some elements and
rules for building a program which has some meaning.
Character Set:
In Real world to communicate with people we use language like Hindi English Urdu extra which is constructed
and Defined by some characters, words extra. Similarly in C programming language we have various characters
to communicate with the computer in order to produce a meaningful program and can produce an output.
Character Set in C Language:

Keywords:
• They are those elements of C language whose meaning has already being defined or explained.
• Keyword are called pre-defined words.
32 keywords in C language

What is algorithm?
An algorithm is a procedure or step-by-step instruction for solving a problem. They form the foundation of
writing a program.
For writing any programs, the following has to be known:
• Input
• Tasks to be performed
• Output expected
Flowchart:
Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts use
simple geometric shapes to depict processes and arrows to show relationships and process/data flow.
Flowchart Symbols:
Here is a chart for some of the common symbols used in drawing flowcharts.
Guidelines for Developing Flowcharts:
These are some points to keep in mind while 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
Here is a flowchart to calculate the average of two numbers:
Flow chart for prime numbers:

Pseudocode
Pseudocode is an artificial and informal language that helps programmers develop algorithms.
Definition: Pseudocode is an informal way of programming description that does not require any strict
programming language syntax or underlying technology considerations.

How it will be used to solve a problem?


• Describe the problem to be solved/function to be implemented. Break large problems into sub groups
of problems.
• Determine the root cause of the problem or the reason for the function. What is the expected outcome
for solving the problem? What is the impact of not solving this problem? Understanding “why” will
keep you rooted in the bigger picture.
• Indicate what you need to know to solve the problem.
• Describe the environment where the solution will exist. Describe the people, places and things that are
impacted? How does the environment interact with your solution? How is it impacted by your solution?
This will help you to evaluate the larger impact and to also uncover any assumptions or pre-conditions
that you’re assuming will be present or active.
• Document the high-level solution. Writing it out is the next best thing to talking (or walking) it out.
This is an excellent way to communicate your intent.
• Detail the steps for executing the solution. “When <the problem> occurs, First <an actor will> do this,
then <an actor will> do that, then <this solution will> do this other thing”
• For each step, evaluate & indicate the outcomes. What do you need to know to perform the step? What
are the results of performing the step? This is how you communicate the expected outputs & post-
conditions.
• Now how many steps did that take? How can you make it faster, better, smarter? (similar process to
editing a story). You may uncover some unnecessary steps, redundant procedures or methods for more
efficiently solving the problem.
• Rinse & repeat.
Data types
A data type is used to indicate the type of value stored in a variable
A data type indicates the following
• Type of value stored in a variable
• Memory allocated for data value
• Type of operations that can be performed on the variable.
Data types are classified in to the following categories.
1. Integer data types
2. Floating point data types
3. Characters
4. Double data type
5. Void data type
1. Integer data types:
It is used to store whole numbers
The size of the integer depends on the word length of a machine i.e. it can be either 16 or 32 bits
Signed Integers:
Signed integers are those integers which uses 15 bits for storing the magnitude of a number and I bit for
storing its sign
The left most bit i.e. 16th bit is used for storing the sign
1-> Negative number
0-> Positive number
Example:
signed int x=10;
0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
Magnitude
Sign

0-> Positive number


Unsigned Integers
Unsigned integers uses all 16 bits to store the magnitude.

Data type Size Format Range


(bytes) Specifier
int 2 or 4 %d -32768 to 32767 or
-21474836648 to 21474836648
unsigned int 2 %u 0 to 65535
signed int 2 %d -32768 to 32767
short int 2 %hd -32768 to 32767
unsigned short int 2 %hu 0 to 65535

signed short int 2 %hd -32768 to 32767


long int 4 %ld -21474836648 to 21474836648
unsigned longint 4 %lu 0 to 4294967295

signed long int 4 %ld -21474836648 to 21474836648


Example Program
Write a C program to display the value of an integer variable.
#include<stdio.h>
#include<conio.h>

void main()
{
int a=10;
clrscr();
printf("Value of a=%d",a);
getch();
}

Expected Output
Value of a=10

2. Floating point data types:


These are used to store real numbers i.e. decimal point numbers or numbers with fractional
values.
Data type Size (bytes) Format Range
Specifier
float 4 %f -3.4e-38 to 3.4e+38
double 8 %lf 1.7e-308 to 1.7e+308
long double 10 %Lf 3.4e-4932 to 1.1e+4932
Example Program
Write a C program to display the value of a floating variable.
#include<stdio.h>
#include<conio.h>
void main()
{
float a=2.5;
clrscr();
printf("Value of a=%f",a);
getch();
}
Expected Output
Value of a=2.500000

3. Character data type:


This data type is used to store characters.
Each character has an equivalent ASCII value.
The format specifier used with character data type is %c.
Data type Size (bytes) Format Range
Specifier
char or signed 1 %c -128 to 127
char
unsigned char 1 %c 0 to 255
Example Program
Write a C program to display a single character.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch=’A’;
clrscr();
printf("Character=%c",ch);
getch();
}
Expected Output
Character=A
4. Double Types:
• A Double data type in C is used to store decimal numbers (numbers with floating point values)
with double precision.
• It is used to define numeric values which hold numbers with decimal values in C.
• Double data type is basically a precision sort of data type that is capable of holding 64 bits of
decimal numbers or floating points.
• Since double has more precision as compared to that float then it is much more obvious that it
occupies twice the memory as occupied by the floating-point type.
• It can easily accommodate about 16 to 17 digits after or before a decimal point.
Range : 1.7E-308 to 1.7E+308
Size : 8 bytes
Format Specifier: %lf
5. Void Data types:
• The void data type in C is used to specify that no value is present.
• It does not provide a result value to its caller. It has no values and no operations. It is used to
represent nothing.
• Void is used in multiple ways as function return type, function arguments as void, and pointers
to void.

Constants: Symbolic name or an entity that does not change its value during the execution of a program.
There are two major categories of a constant:
Constants are classified into two types they are:
1. Primary Constant
2. Secondary Constant
Primary Constant: This category consist basic constants of C language like integer constant, float or real integer
constant, character constant.
Secondary Constant: This category consist arrays, pointers, structure, union, enum etc.
a) Integer Constant:
const int rate= 50;
In this const is a keyword, int is a data type, rate is a value , = is a assignment operator, 50 is a value, ; is a
terminate operator to terminate the statement. In this value of variable rate will not be changed throughout the
program.
b) const float or real integer:
const float pi= 3.1415;---> this is called the declaration with complete statement
c) Character Constant:
const char ch= 'A'; a character data type value is always assigned with “quotes.
Variables
“A variable is the name given to memory location to store data value in it.”
Unlike constant, the value of a variable can be changed.
A variable name must be chosen in such a way that it improves the readability of a program.
Syntax Data_type var_name=var_value;

Example
int x=10;
The above variable ‘x’ contains value 10 and it is of integer data type
C Programming Operators
An operator is a symbol that operates on a value or a variable
For example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.
Arithmetic Operators:
An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division
etc on numerical values (constants and variables).
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* Multiplication
/ division
% remainder after division (modulo division)
Example 1: Arithmetic Operators
// Working of arithmetic
operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+
b = %d
\n",c); c =
a-b;
printf("a-
b = %d
\n",c); c
= a*b;
Outputprintf("a*
b = %d
a+b = 13
\n",c);
a-b = 5c =
a/b;
a*b = 36
printf("a/
a/b = 2
b = %d
Remainder when a divided by b=1
\n",c); c
= a%b;and Decrement Operators:
Increment
printf("Remainder when a divided by b = %d \n",c);
C programming
return 0; has two operators increment ++ and decrement -- to change the value of an operand
}
(constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement-- decreases the value by 1. These two operators
are
unary operators, meaning they only operate on a single operand.
Example 2: Increment and Decrement Operators

// Working of increment and decrement


operators #include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Output

++a = 11
--b = 99
++c = 11.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also be used as
postfixes like a++ and a--

Assignment Operators:
An assignment operator is used for assigning a value to a variable. The most common assignment operator
is =

Operator Example
= a=b
+= a+=b or a=a + b
-= a -=b or a=a - b
*= a*=b or a=a * b
/= a/=b or a=a / b
%= a%=b or a=a % b
Example 3: Assignment Operators:
// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
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.
Normally Relational operators are used in decision making and loops.

Operator Meaning of Operator Example


== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0


Example 4: Relational Operators
// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;
}
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true
or false. Logical operators are commonly used in decision making in C programming.
Operator Meaning Example

Logical AND. True only if If c = 5 and d = 2 then, expression


&&
all operands are true ((c==5) && (d>5)) equals to 0.

Logical OR. True only if If c = 5 and d = 2 then, expression


||
either one operand is true ((c==5) || (d>5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression !(c==5)


!
operand is 0 equals to 0.

Example 5: Logical Operators

// Working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
Output

(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Bitwise Operators:
• During computation, mathematical operations like: addition, subtraction, multiplication, division, etc
are converted to bit-level which makes processing faster and saves power.
• Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND


| Bitwise OR

^ Bitwise exclusive OR
~ Bitwise complement

<< Shift left

>> Shift right

Special Operators:
Comma Operator:
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof operator:
The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).
Example 6: sizeof Operator
#include <stdio.h>
int main()
{
int a; float b;
double c; char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Ternary operator
It is also known as condition operator.
Syntax exp1?exp2:exp3;
The value of exp1 is evaluated first, If it is true, value of exp2 is evaluated otherwise exp3 is evaluated
Example Program
Write a C program to find the biggest of two numbers using Conditional operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,big;
clrscr();
a=20;
b=10;
big=(a>b)?a:b;
printf("Big number is %d",big);
getch();
}
Expected Output
Big number is 20

Other operators such as:


Reference operator: &
Dereference operator: *

Type Casting: In typing casting, a data type is converted into another data type by the programmer using
the casting operator during the program design. In typing casting, the destination data type may be smaller
than the source data type when converting the data type to another data type, that’s why it is also called
narrowing conversion.
Syntax/Declaration:-
destination_datatype = (target_datatype)variable;
(): is a casting operator.
target_datatype: is a data type in which we want to convert the source data type.
Type Casting example –
float x;
byte y;
...
...
y=(byte)x; //Line 5
In Line 5: you can see that, we are converting float(source) data type into byte(target) data type.
Type conversion: In type conversion, a data type is automatically converted into another data type by a
compiler at the compiler time. In type conversion, the destination data type cannot be smaller than the source
data type, that’s why it is also called widening conversion. One more important thing is that it can only be
applied to compatible data types.
Type Conversion example –
int x=30;
float y;
y=x; // y==30.000000.

S.NO TYPE CASTING TYPE CONVERSION

In type casting, a data type is converted Whereas in type conversion, a data type is
1. into another data type by a programmer converted into another data type by a
using casting operator. compiler.

Type casting can be applied to compatible


Whereas type conversion can only be applied
2. data types as well as incompatible data
to compatible datatypes.
types.

In type casting, casting operator is needed


Whereas in type conversion, there is no need
3. in order to cast a data type to another data
for a casting operator.
type.

In typing casting, the destination data type


Whereas in type conversion, the destination
may be smaller than the source data type,
4. data type can’t be smaller than source data
when converting the data type to another
type.
data type.

Type casting takes place during the Whereas type conversion is done at the
5.
program design by programmer. compile time.

Type casting is also called narrowing Whereas type conversion is also called
conversion because in this, the destination widening conversion because in this, the
6.
data type may be smaller than the source destination data type can not be smaller than
data type. the source data type.

Whereas type conversion is less used in


Type casting is often used in coding and
7. coding and competitive programming as it
competitive programming works.
might cause incorrect answer.

Whereas type conversion is less efficient and


8. Type casting is more efficient and reliable.
less reliable.

What is Top-Down Approach?


Top-Down Approach is an approach to design algorithms in which a bigger problem is broken down into
smaller parts. Thus, it uses the decomposition approach. This approach is generally used by structured
programming languages such as C, COBOL, FORTRAN.
The drawback of using the top-down approach is that it may have redundancy since every part of the code is
developed separately. Also, there is less interaction and communication between the modules in this approach.
The implementation of algorithm using top-down approach depends on the programming language and platform.
Top-down approach is generally used with documentation of module and debugging code.
What is Bottom-Up Approach?
Bottom-Up Approach is one in which the smaller problems are solved, and then these solved problems are
integrated to find the solution to a bigger problem. Therefore, it uses composition approach.
It requires a significant amount of communication among different modules. It is generally used with object
oriented programming paradigm such as C++, Java, and Python. Data encapsulation and data hiding is also
implemented in this approach. The bottom-up approach is generally used in testing modules.
Difference between Top-Down Approach and Bottom-Up Approach

S.No. Top-Down Approach Bottom-Up Approach

In this approach, the problem is broken In this approach, the smaller problems are
1.
down into smaller parts. solved.

It is generally used by structured It is generally used with object oriented


2. programming languages such as C, programming paradigm such as C++, Java,
COBOL, FORTRAN, etc. Python, etc.

It is generally used with documentation of It is generally used in testing modules.


3.
module and debugging code.

It does not require communication between It requires relatively more communication


4.
modules. between modules.

5. It contains redundant information. It does not contain redundant information.

6. Decomposition approach is used here. Composition approach is used here.

The implementation depends on the Data encapsulation and data hiding is


7.
programming language and platform. implemented in this approach.
Conclusion
The most significant difference between the two is that the top-down approach is mainly used in structure
programing languages like C, COBOL, etc., while the bottom-up approach is used in object-oriented
programming languages like C++, Java, Python, etc.
Time and space complexities of algorithms.
Generally, there is always more than one way to solve a problem in computer science with different algorithms.
Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more
optimal. The method must be:
• Independent of the machine and its configuration, on which the algorithm is running on.
• Shows a direct correlation with the number of inputs.
• Can distinguish two algorithms clearly without ambiguity.
There are two such methods used, time complexity and space complexity which are discussed below:
Time Complexity:
The time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of
the length of the input. Note that the time to run is a function of the length of the input and not the actual execution
time of the machine on which the algorithm is running on.
The valid algorithm takes a finite amount of time for execution. The time required by the algorithm to solve
given problem is called time complexity of the algorithm. Time complexity is very useful measure in algorithm
analysis.
It is the time needed for the completion of an algorithm. To estimate the time complexity, we need to consider
the cost of each fundamental instruction and the number of times the instruction is executed.
Space Complexity:
Definition –
Problem-solving using computer requires memory to hold temporary data or final result while the program is in
execution. The amount of memory required by the algorithm to solve given problem is called space
complexity of the algorithm.
The space complexity of an algorithm quantifies the amount of space taken by an algorithm to run as a function
of the length of the input.

Short Answer Questions


1. Write difference between algorithm and flowchart.
2. Explain the importance of C language.
3. What is format specifier?
4. Define keyword, constant and variable.
5. Write a short note on type casting.
6. Explain sizeof() with example?
7. Why do we use header files?
8. Define relational operator?
9. What is the purpose of adding comments in a program?
10. Differentiate between computer software and hardware?
Essay Answer Questions
1. Describe in detail about computer hardware and software.
2. Write detailed notes on C data types.
3. Write an algorithm, flowchart and C program to find the sum of numbers from 1 to n
4. Discuss about the following operators in C language with example.
a. Bitwise operators
b. Increment and decrement operators
c. Logical operators
5. Perform the following operations
a) 23>>3 b) 27<<2 c) 15&9 d) 15^9 e) 15|9
6. Write the structure of C program and explain.
7. Write a program to perform swapping of two numbers with and without using temporary variable.
8. Define algorithm. Write algorithm for finding factorial of a number.
9. What is flowchart? Explain different symbols used for flowchart.
10. What is constant? Explain different constants in C.
11. What is variable? Give the rules for variable declaration.
12. Write an algorithm and flowchart to generate Fibonacci series of numbers up to 'n'.
13. Draw the flowchart to find the greatest of three numbers.
14. Write an algorithm and flowchart to find whether the given number is prime or not.
15. Explain about type conversion and type casting in C.

You might also like