Introduction To Computers: Erased
Introduction To Computers: Erased
INTRODUCTION TO PROGRAMMING-R23
UNIT I
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.
Problem solving techniques: Algorithmic approach, characteristics of algorithm, Problem solving strategies:
Top-down approach, Bottom-up approach, Time and space complexities of algorithms.
Introduction to Computers
Computer:
• Computer is an electronic device which takes input data, process that data and gives desired output to the user.
• Charles Babbage is called as father of computer.
• We use computers to get accurate results and fast results.
Computer Systems:
• A computer system is made up of two components. They are software and hardware.
• The computer hardware is physical components.
• The computer software is collection of programs(instructions) that allow the hardware to do its job.
Computer hardware:
• The hardware components of the computer system consist of 5 parts.
• They are input devices, Central Processing Unit (CPU), primary storage, auxiliary storage and output devices.
• The input device is usually a keyboard where programs and data are entered into the computer. Examples of
other input devices are mouse, a pen or stylus, a touchscreen or an audio input unit.
• The Central Processing Unit (CPU) is responsible for executing instructions such as arithmetic calculations,
comparisons among data, movement of data inside the system. Todays computers have one, two or more CPU’s.
• Primary Storage, is also known as main memory, is a place where the programs and data are temporarily
stored during processing. The data in the primary storage is erased when we turnoff a computer.
• Auxiliary storage, is also known as secondary storage, is used for both input and output. In this storage both
programs and data stored permanently. Even when we turn off the computer also data remain in the secondary
storage.
• Output device is usually a monitor or a printer to show output. If the output is shown on the monitor it is
called soft copy and if it is printed on the printer, we say it is as a hard copy.
Computer software:
• Computer software is divided into two broad categories. They are System Software and
Application Software.
System software:
• System software manages the computer resources.
• Operating System is a system software.
• It provides the interface between hardware & the user and but does nothing to directly serve the user’s needs.
SIR CR REDDY COLLEGE OF ENGINEERING INFORMATION TECHNOLOGY
2
INTRODUCTION TO PROGRAMMING-R23
• It provides a platform for the application software to run.
Application Software:
It is a collection of programs written for a specific application.
Eg: M.S.Office, Windows media players, Web browsers etc.
• Application software on the other hand is directly responsible for helping users to solve their problems.
The relationship between system software and application software can be shown below.
• In the diagram each circle represents an interface point.
• To work with a system, user uses an application software.
• The application software interacts with the operating system which is part of the system software layer.
• The system software provides the direct interaction with the hardware.
History of Computers:
Generations of Computers:
A generation of computers refers to the specific improvements in computer technology with time. In
1946, electronic pathways called circuits were developed to perform the counting. It replaced the gears and
other mechanical parts used for counting in previous computing machines.
In each new generation, the circuits became smaller and more advanced than the previous generation
circuits. The miniaturization helped increase the speed, memory and power of computers. There are five
generations of computers which are described below;
In this generation, magnetic cores were used as the primary memory and magnetic disc and tapes were used
as the secondary storage. Assembly language and programming languages like COBOL and FORTRAN, and
Batch processing and multiprogramming operating systems were used in these computers.
o IBM 1620
o IBM 7094
o CDC 1604
o CDC 3600
o UNIVAC 1108
The third generation computers used integrated circuits (ICs) instead of transistors. A single IC can pack
huge number of transistors which increased the power of a computer and reduced the cost. The computers
also became more reliable, efficient and smaller in size. These generation computers used remote processing,
time-sharing, multi programming as operating system. Also, the high-level programming languages like
FORTRON-II TO IV, COBOL, PASCAL PL/1, ALGOL-68 were used in this generation.
o IBM-360 series
o Honeywell-6000 series
o PDP(Personal Data Processor)
o IBM-370/168
o TDC-316
The fourth generation (1971-1980) computers used very large scale integrated (VLSI) circuits; a chip
containing millions of transistors and other circuit elements. These chips made this generation computers
more compact, powerful, fast and affordable. These generation computers used real time, time sharing and
distributed operating system. The programming languages like C, C++, DBASE were also used in this
generation.
o DEC 10
o STAR 1000
o PDP 11
o CRAY-1(Super Computer)
o CRAY-X-MP(Super Computer)
In fifth generation (1980-till date) computers, the VLSI technology was replaced with ULSI (Ultra Large
Scale Integration). It made possible the production of microprocessor chips with ten million electronic
components. This generation computers used parallel processing hardware and AI (Artificial Intelligence)
software. The programming languages used in this generation were C, C++, Java, .Net, etc.
o Desktop
o Laptop
o NoteBook
o UltraBook
o ChromeBook
Control Unit:
The control unit of a CPU controls all the activities and operations of the computer. It is also responsible for
controlling input/output , memory and other devices connected to the CPU.
The control unit acts like the supervisor which determines the sequence in which computer programs and instructions
are executed.
ALU (Arithmetic Logic Unit) :
ALU (Arithmetic Logic Unit) is responsible for performing arithmetic and logical functions or operations.
It consists of two subsections, which are:
Arithmetic Section
Logic Section
Arithmetic Section: By arithmetic operations, we mean operations like addition, subtraction,
multiplication, and division, and all these operation and functions are performed by ALU. Also, all the
complex operations are done by making repetitive use of the mentioned operations by ALU.
Logic Section: By Logical operations(AND ,OR etc), we mean operations or functions like selecting,
comparing, matching, and merging the data, and all these are performed by ALU.
Note: CPU may contain more than one ALU and it can be used for maintaining timers that help run the
computer system.
Memory Unit:
Memory Unit is an essential part of the computer system which is used to store data and instructions
before and after processing.
There are two types of memory units:
1. Primary memory/Main memory
2. Secondary memory/Auxiliary memory
Primary Memory: Primary memory cannot store a vast amount of data.
The data stored in the primary memory is temporary. The data will be lost if they are disconnected from
the power supply.
Primary-storage is a fast-memory that operates at electronic-speed. Programs must be stored in the memory while they
are being executed.
Primary memory is also known as the Main Memory or temporary memory. Random Access Memory
(RAM) is an example of Primary memory.
Secondary Memory:
Secondary memory is also known as the Auxiliary Memory or permanent storage.
Secondary-storage is used when large amounts of data & many programs have to be stored.
The data stored in the secondary memory is safe even when there is a power failure or no power supply.
Hard Disk is usually considered a secondary memory.
Eg: Magnetic disks and optical disks(CD-ROMs).
Computer languages have been evolved from Low Level to High Level Languages. In the earliest
days of computers, only Binary Language was used to write programs.
The computer languages are classified as follows...
Low Level Language (Machine Language)
Low Level language is the only language which can be understood by the computer. . Low level
language is also known as Machine Language. Binary Language is an example of low level
language.
The binary language contains only two symbols 1 & 0. All the instructions of binary language are
written in the form of binary numbers 1's & 0's.
As the CPU directly understands the binary language instructions, it does not require any
translator.
CPU directly starts executing the binary language instructions, and takes very less time to execute
the instructions as it does not requires any translation. Low level language is considered as the
First Generation Language (FGL)
Advantages
A computer can easily understand the low level language.
Low level language instructions are executed directly without any translation.
Low level language instructions require very less time for their execution.
Disadvantages
Low level language instructions are very difficult to use and understand.
Low level language instructions are machine dependent, that means a program written for
particular machine does not executes on other machine.
In low level language, there is more chance for errors and it is very difficult to find errors, debug
From the above figure, we can observe the following key points...
The programming languages like C, C++, Java etc., are written in High level language which is
more comfortable for the developers.
High level language is more closer to the users.
Structure of C program:
The program written in C language follows this basic structure. The sequence of sections should be
as they are in the basic structure. A C program should have one or more sections but the sequence
of sections is to be followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration section
Executable section
}
6. Sub program or function section
1.Documentation Section:-
This comes first and is used to document the use of logic or reasons in your program. It can be
used to write the program's objective, developer and logic details. The documentation is done in C
language with /* and */. Whatever is written between these two are calledcomments.
2. Linking Section:-
This section tells the compiler to link the certain occurrences of keywords or functions in your
program to the header files specified in this section.
e.g. #include <stdio.h>
3. Definition Section:-
It is used to declare some constants and assign them some value.
e.g. #define MAX 25
Here #define is a compiler directive which tells the compiler whenever MAX is found in
the program, replace it with 25.
SIR CR REDDY COLLEGE OF ENGINEERING INFORMATION TECHNOLOGY
10
INTRODUCTION TO PROGRAMMING-R23
4. Global Declaration Section:-
Here the variables which are used throughout the program (including main and other functions)
are declared so as to make them global(i.e accessible to all parts of program)
e.g. int i; (before main())
5. Main Function Section :-
This has all the sub programs or the functions which our program needs.
Our first C program is very simple. it has only one preprocessor command, no global declarations,
and no local definitions. Its purpose will be simply to print a greeting to the user.
So, the statements section had only 2 statements. one that prints a greeting and one that stops the
program.
Preprocessor commands:
Preprocessor commands come at the beginning of the program. All preprocessor commands start
with a pound sign (#).
The preprocessor command tells the compiler to include the standard input/output library file in
the program.
We need this library file to print a message to the terminal. Printing is one of the input/output
processes identified in this library.
The complete syntax for this command is shown below.
#include <stdio.h>
A preprocessor command it must start with a pound symbol, there can be no space between the
pound sign and the keyword
include. it tells the preprocessor that we want the library include, it tells the preprocessor that we
want the library
The name of the header file is stdio.h, the abbreviation is standard input/ output header file.
main():
The executable part of our program begins with the function main, which is identified by the
function header.
In the main function int says that the function will return an integer value to the OS, that the
functions name is main, and it has no parameters (the parameters list is void).
int main(void)
Within main there are 2 statements.
o one to print the message and
o one to terminate the program.
The print statement uses a library function to execute this print function, printf, followed by a
parameters list enclosed in parentheses.
For example, whatever we want to display we place that in two double quote marks (".."). the \n at
the end of the message tells the computer to advance to the next line in the output.
The last statement in our program, return 0, terminates the program and returns control to the OS.
COMMENTS: C uses two different types of comments:
Comments are the non executable statements in a program.
The compiler ignores these comments when it translates the program into executable code.
Program
/* The greeting program. This program demonstrates some of the components of a simple C program.
Written by: your name Date: date*/
#include<stdio.h>
int main( )
{
// Local Declarations
// Statements
printf(“Hello World\n”);
return 0;
}// main
/* simple program in c */
#include<stdio.h>
main()
{
printf(“welcome to c programming”);
} /* End of main */
Decision Diamond symbol represents a decision point. Decision based operations such as
yes/no question or true/false are indicated by diamond in flowchart.
Connectors: Whenever flowchart becomes complex or it spreads over more than one page,
it is useful to use connectors to avoid any confusions. It is represented by a circle.
Flow lines: Flow lines indicate the exact sequence in which instructions are executed.
Arrows represent the direction of flow of control and relationship among different symbols
of flowchart.
Advantages of Flowchart:
Flowcharts are a better way of communicating the logic of the system.
Flowcharts act as a guide for blueprint during program designed.
Flowcharts help in debugging process.
With the help of flowcharts programs can be easily analyzed.
It provides better documentation.
Disadvantages of Flowchart:
It is difficult to draw flowcharts for large and complex programs.
There is no standard to determine the amount of detail.
Difficult to reproduce the flowcharts.
It is very difficult to modify the Flowchart.
Making a flowchart is costly.
Some developer thinks that it is waste of time.
It makes software processes low.
If changes are done in software, then the flowchart must be redrawn
Example : Draw a flowchart to input two numbers from the user and display the
largest of two numbers
Pseudo code:
The pseudo code in C is an informal way of writing a program for better human understanding.
Pseudo code is a method of representing logic in programming that is independent of any
programming language.
1.Pseudo code is easier to read and comprehend than actual programming code since it describes program logic in
everyday language.
2. Saving time: By working out the specifics of the program logic before creating the actual code, producing
pseudo code allows you to save time in the long run.
3.Reduces errors: Because pseudo code enables you to develop the logic of your program in a more streamlined
manner, it can help to decrease errors in your code.
4.Pseudo code is portable because it is language-independent and is simple to adapt to new programming
languages.
Compiling Programs:
The code in the source file to be converted into machine language, it is done by compiler.
The C compiler is 2 separate programs. They are preprocessor and translator.
Preprocessor reads the preprocessor commands. These commands tell the preprocessor to look
Executing Programs:
Once our program is linked it is ready for execution. To execute a program, , we use Operating
System command such as run to load the program into main memory..
Getting the program into main memory is the function of the operating system program is known as
loader. When the program is loaded execution takes place.
In today’s integrated environment all these processes are done in a single click or one pull down
window.
The program takes the input from a file or from the user. After processing/ execution is done output is
displayed on the monitor or stored in a file.
When the program has finished its job, it tells the operating system which then removes the program
from the memory.
Identifiers
Names of the variables and other program elements such as functions, array, etc, are known as
identifiers. There are few rules that govern the way variable are named (identifiers).
Identifiers can be named from the combination of A-Z, a-z, 0-9, _ (Underscore).
The first alphabet of the identifier should be either an alphabet or an underscore. Digitsare
not allowed.
First 63 characters of an identifier are significant.
It may not have a space or a hyphen (-). It may not have a special characters like $,@,% ,*, etc.
It should not be a keyword.Eg:
name, ptr, sum [valid]
Eg: sum-sal, 2name, std no, int [invalid]
Data Types:
A type defines a set of values and a set of operations that can be applied on those values.
The data type specifies the size and type of information the variable will store.
The integer datatype in C is used to store the integer numbers(any number including positive, negative
and zero without decimal part). Octal values, hexadecimal values, and decimal values can be stored in
int data type in C.
The storage size of int data type is 2 or 4 or 8 byte.
It varies depend upon the processor in the cpu that we use.
If we are using 16 bitprocessor, 2 byte(16 bit) of memory will be allocated for int data type.
like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memoryfor 64 bit
processor is allocated for int datatype.
int (2 byte) can store values from -32,768 to +32,767
int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
Syntax of Integer
We use int keyword to declare the integer variable:
int var_name;
1. unsigned int: Unsigned int data type in C is used to store the data values from zero to positive
numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768 to 32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.
Program:
#include <stdio.h>
int main()
{
Output:
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;
program:
#include <stdio.h>
int main()
{
char a = 'a';
char c ;
a++;
printf("Value of a after increment is: %c\n", a);
/*c is assigned ASCII value which corresponds to the character 'c' , a-->97 b-->98 c-->99 here c will
be printed.*/
c = 99;
return 0;
}
Output
Value of a: a
Value of a after increment is: b
Value of c: c
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;
program:
#include <stdio.h>
int main()
{
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);
return 0;
}
Output
9.000000
2.500000
0.000200
4.Double Data Type
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.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
Syntax of Double:
The variable can be declared as double precision floating point using the double keyword:
double var_name;
program:
#include <stdio.h>
int main()
{
double a = 123123123.00;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c);
return 0;
}
Output:
123123123.000000
12.293123
2312312312.123123
float 4 %f
1.2E-38 to 3.4E+38
double 8 %lf
1.7E-308 to 1.7E+308
Variables
Variables are containers for storing data values, like numbers and characters.
Variable is a name given to memory location that holds a value.
variable is a name of the memory location. It is used to store data. Its value can be changed, and it
can be reused many times.
Variable decleration:
datatype variable_list;
Eg: int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
Variable initialization
Datatype variable_name= value;
We can also provide values while declaring the variables as given below:
Global Variables:
A variable that is declared outside the function or block is called a global variable. Any function can
change the value of the global variable. It is available to all the functions.
The scope of the global variable is through out a program.
The identifier is only used to identify an entity uniquely in a program at the time of execution
whereas, a variable is a name given to a memory location that is used to hold a value.
Variable is only a kind of identifier, other kinds of identifiers are function names, class names,
structure names, etc.
Constants
Constants are data values that cannot be changed during the execution of a program. Like
variables, constants have a type.
Types of constants:
1.Numeric constants
a)Integer constants:
Decimal,Octal,Hexadecimal
b)Real constants
2.Character constants
Single character constants
String constants
1.Integer constants:
Decimal Constants:
A whole number represented in base 10 is known as a decimal constant. It has digits that range
from 0 to 9. Declaring a decimal constant has a simple syntax that just requires the value to be written.
Example:
#include <stdio.h>
int main()
{
int decimal = 42;
printf("The decimal constant is: %d\n", decimal);
return 0;
}
Output:
A base 8 value is represented by an octal constant. It is prefixed with a '0' (zero) to show that it is an
octal constant and has digits ranging from 0 to 7.
Example:
#include <stdio.h>
int main()
{
int octal = 052; // Octal representation of decimal 42
printf("The octal constant is: %o\n", octal);
return 0;
}
Output:
Hexadecimal Constant:
Example:
#include <stdio.h>
int main()
{
int hexadecimal = 0x2A; // Hexadecimal representation of decimal 42
printf("The hexadecimal constant is: %x\n", hexadecimal);
return 0;
}
Output:
#include <stdio.h>
int main()
{
float real = 3.14;
printf("The real constant is: %f\n", real);
return 0;
}
Output:
2.Character Constant:
Example:
#include <stdio.h>
int main()
{
char character = 'A';
printf("The character constant is: %c\n", character);
return 0;
}
Output:
A sequence of zero or more characters wrapped in double quotes is represented by a string constant. It
is a character array that ends with the null character \0.
Example:
“ “ // a null string
“h”
“computer”
“wide characters”
Example:
#include <stdio.h>
int main()
{
char string[] = "Hello, World!";
printf("The string constant is: %s\n", string);
return 0;
}
Output:
To define constant in C:
There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor
Syntax:
eg: const float PI=3.14; // Now, the value of PI variable can't be changed.
Program:
#include<stdio.h>
int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
If you try to change the the value of PI, it will render compile time error.
#include<stdio.h>
int main()
{
const float PI=3.14;
PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
Compile Time Error: Cannot modify a const object
Syntax:
Example program:
#include <stdio.h>
#define PI 3.14
int main()
{
printf("%f",PI);
return 0;
}
Output:
3.140000
Basic Input/output
Standard input-- used to take the input from the device such as Keyboard.
Standard output--used to send output to a device such as monitor or screen.
Types of Input Output:
There are 2 kinds of I/O functions as given below.
putchar() :
The putchar() writes the character type data to the output file stdout(screen). It is used to
print one character at a time.
Syntax:
Putchar(Variable_name);
gets()
The gets() is used to read string from standard input file stdin and places it into some
buffer which the programmer must p rovide. The gets() stops reading when an enter key is
pressed or EOF is reached.
Syntax:
gets(variablename);
puts() :
The puts() is used to send the string to the output file stdout, until it finds a NULL end of
string marker. The NULL is not written, instead the newline character is written to the
output stdout.
Syntax:
puts(variablename);
F o r ma t t e d I n p u t O u t p u t Fu n c t i o n s :
1 .s c a n f ( ) :
The scanf() reads all types of data values given by the user and these values are
assigned to the variables. It requires the conversion specification (such as %s and %d )
to identify the type of data to be read during the program execution.
You need to pass the address of the variable to the scanf function along with other
arguments so that the read values can be assigned to the correct destination.
Example:
int x;
float y;
scanf (“%d % f “, &x, &y);
Control string
It tells the function the type of data being Input and uses the same control sequences as the printf()
function.
It enclosed with double quotes (“ “).
It specifies the type of values that have to be read from keyboard. Control string consists of
format specification.
Example:
Integer - %d Float - %f double - %lf long double - %Lf char - %c
scanf() reads the characters from standard input and interprets them according to the
format string specification. It stops reading when it encounters a space or when some
input fails to match with the conversion specification.
2 .p r i n t f ( ) :
The printf() prints all types of data value to the standard output(typically the screen). It
requires a conversion symbol and variable name to print the data. The printf() is part of
every C compiler. Its header file is stdio.h.
Syntax:
The first argument is the format string which is composed of ordinary characters and
conversion specification. This is followed by zero or more optional arguments.
Control String
1. Format Specifier given in the form of % specifier.
2. Escape sequence characters such as \n (new line) \t(tab).
3. It can have a string that must be printed on the monitor.
The format of numbers displayed by printf() can be controlled by field with specifiers included as
part of each conversion control sequence.
printf(“sum of %.3d and %4d is %5d”,6,15,21);
Output: sum of ∧∧6 and ∧∧∧5 is ∧∧∧21
The value of a = 10
Float point
%5.2f – 42.30
%5.2f – 142.36
%10.3f – ∧∧∧∧25.670
Format Modifier (modifiers for printf formats)
A format specification can also include “modifiers” that can control how much of the item’s
values is printed and how much space it gets.
The modifiers come between the % and the format control letter.
Justification
It controls the placement of a value when it is shorter than the specified width.
Justification can be left or right. The format modifier (-) minus is used.
Left Justification
A format specification has (-) minus sign used before the width modifier says to left justify the
argument within its specified width.
Example: printf(“%-10d”,59);
Output: 59∧∧∧∧∧∧∧∧
Output:
right
left
abcd
abcd
Usually the format string is enclosed with the double quotation marks in both scanf()
and printf().
Type Conversion
Type converse on can be defined as converting one data type into another data type.
There are 2 different type conversions are there they are:
1. Automatic or implicit type conversion.
2. Type casting or explicit type conversion.
Implicit Type Conversion
When the type conversion is performed automatically by the compiler without programmer
intervention such type of conversion is known as implicit type conversion.
If operators are different types the lower type is automatically converted to higher type before
operation proceed.
The following Figure shows the ranks as we use them for conversion.
Types of Operators in C:
C operators can be classified into the following types:
1. Arithmetic operators
2. Increment and decrement operators
3. Relational operators
4. Logical operators
1. Arithmetic Operators :
Output:
Addition of a and b = 73
Subtraction of a and b = 27
Multiplication of a and b = 1150
Division of a and b = 2
modulus of a and b = 4
When we use the increment and decrement operator as a prefix (means before the operand), then,
first the increment operation is done and that value is used, like in the first two printf() functions,
we get the updated values of a and b.
Whereas when we use the increment and decrement operators as postfix (means after the
operand), then, first the larger expression is evaluated which is printf() in this case and then the
value of the operand is updated.
#include <stdio.h>
int main()
{
return 0;
Output:
Incrementing value of a = 11
Decrementing value of b = 19
Decrementing value of a = 11
Value of a = 10
Incrementing value of b = 19
Value of b = 20
The relational operators (or comparison operators) are used to check the relationship between two
operands.
It checks whether two operands are equal or not equal or less than or greater than, etc.
It returns 1 if the relationship checks pass, otherwise, it returns 0.
When we use relational operators, we get the output based on the result of the comparison.
If it's true, then the output is 1 and if it's false, then the output is 0.
Example
Operator Description
(a and b, where a = 10 and b =
11)
#include <stdio.h>
int main()
{
int a = 10, b = 20, result;
// Equal
result = (a==b);
printf("(a == b) = %d \n",result);
// less than
// greater than
result = (a>b);
printf("(a > b) = %d \n",result);
return 0;
Output:
(a == b) = 0
(a < b) = 1
(a > b) = 0
(a <= b) = 1
4.Logical Operators :
Example
Operator Description
(a and b, where a = 1 and b = 0)
|| Logical OR a || b, returns 1
These operators are used to perform logical operations and are used with conditional statements like if
else.
1. With the AND operator, only if both operands are true, the result is true.
2. With the OR operator, if a single operand is true, then the result will be true.
3. The NOT operator changes true to false, and false to true.
#include <stdio.h>
int main() {
int a = 1, b = 0, result;
// And
result = (a && b);
printf("a && b = %d \n",result);
// Or
result = (a || b);
printf("a || b = %d \n",result);
// Not
result = !a;
printf("!a = %d \n",result);
return 0;
Output:
a && b = 0
a || b = 1
!a = 0
5.Bitwise operators:
Bitwise operators perform manipulations of data at the bit level.
These operators also perform the shifting of bits from right to left.
Bitwise operators are not applied to float or double, long double, void, etc.
There are 6 bitwise operators in C programming.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
~ One’s complement
>> Shift Right
<< Shift Left
we have a truth table for showing how these operators work with different values.
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise operators can produce any arbitrary value as a result. It is not mandatory that the result will either
be 0 or 1.
The bitwise shift operator shifts the bit value, either to the left or right.
The left operand specifies the value to be shifted and the right operand specifies the number of
positions that the bits in the value have to be shifted.
Both operands have the same precedence.
Understand, how bits shift from left to right and vice versa.
a = 00010000
b=2
a << b = 01000000
a >> b = 00000100
In case of a << b, 2 bits are shifted to left in 00010000 and additional zeros are added to the opposite end,
that is right, hence the value becomes 01000000
And for a >> b, 2 bits are shifted from the right, hence two zeros are removed from the right and two are
added on the left, hence the value becomes 00000100
Please note, shift doesn't work like rotating, which means, the bits shifted are not added at the other end.
The bits that are shifted are lost.
#include <stdio.h>
int main()
{
int a = 0001000, b = 2, result;
// <<
result = a<<b;
printf("a << b = %d \n",result);
// >>
result = a>>b;
printf("a >> b = %d \n",result);
return 0;
}
Output:
a << b = 2048
a >> b = 128
6.Assignment Operators:
The assignment operators are used to assign value to a variable.
For example, if we want to assign a value 10 to a variable x then we can do this by using the
assignment operator like: x = 10; Here, = (equal to) operator is used to assign the value.
In the C language, the = (equal to) operator is used for assignment however it has several other
variants such as +=, -= to combine two operations in a single statement.
Example
Operator Description (a and b are two variables, with
where a=10 and b=5)
Example
Operator Description (a and b are two variables, with
where a=10 and b=5)
When we combine the arithmetic operators with the assignment operator =, then we get
the shorthand form of all the arthmetic operators.
#include <stdio.h>
int main()
{
int a = 10,b=30,c=10;
// += operator
a += 20;
printf("result = %d \n",a);
// -= operator
b -= 5;
printf("result = %d \n",b);
// *= operator
c *= 10;
printf("result = %d \n",c);
return 0;
}
Output:
result = 30
result = 25
result = 100
The ternary operator, also known as the conditional operator in the C language can be used
for statements of the form if-then-else.
#include <stdio.h>
int main()
{
printf("result = %d",result);
return 0;
}
Output:
result = 40
sizeof operator is used to find size of any entity(variable, array, etc.), & operator to find the address of a
variable, etc. You can see a list of such operators in the below table.
#include <stdio.h>
int main()
{
int a = 20;
char b = 'B';
double c = 17349494.249324;
// sizeof operator
printf("Size of a is: %d \n", sizeof(a));
printf("Size of b is: %d \n", sizeof(b));
printf("Size of c is: %d \n", sizeof(c));
// & operator
printf("Memory address of a: %d \n", &a);
return 0;
}
Output:
Size of a is: 4
Size of b is: 1
Size of c is: 8
Memory address of a: -1254020756
Auto variables
A variable is declared inside a function without any storage class specification, is by default an
automatic variable.
An automatic variables can also called local variable, because they are local to a function
By default they are assigned to the garbage value by the compiler.
They are created when a function is called and or destroyed automatically when the function
exists.
Syntax: storage class specification data type variable name;
Static variables can be declared within a function. These variables retain their values from
pervious call i.e., the value that they had before returning from the function.
Program using static variable
sun()
main()
{
int i;
for(i=1;i<=3;i++)
{
sun();
}
Part-2
Characterstics of an algorithm:
Algorithm:
Algorithm is a step by step procedure to solve a particular problem.
There are some characteristics which every algorithm should follow.There are five different characteristics
which deal with various aspects of algorithm.
They are as follows:
1.Input specified
2.Output specified
3.Definiteness
4.Effectiveness
5. Finiteness
6.Independent
have 0 or more well-defined inputs.Input precision requires that you know what kind of data, how much
or more well-defined outputs, and should match the desired output.Output precision also requires that you
know what kind of data, how much and what form the output should be (or even if there will be any output
at all!).
3)Definiteness
Algorithms must specify every step and the order the steps must be taken in the process.Definiteness
means specifying the sequence of operations for turning input into output. Algorithm should be clear and
unambiguous.Details of each step must be also be spelled out (including how to handle errors).It should
4)Effectiveness
For an algorithm to be effective, it means that all those steps that are required to get to output must be
feasible with the available resources.It should not contain any unnecessary and redundant steps which
For example,suppose you are cooking a recipe and you chop vegetables which are not be used in the
response that no solution is possible. Algorithms must terminate after a finite number of steps.An
algorithm should not be infinite and always terminate after definite number of steps.
There is no point in developing an algorithm which is infinite as it will be useless for us.
6)Independent
An algorithm should have step-by-step directions, which should be independent of any programming
code.It should be such that it could be run on any of the programming languages.
FLOW CHART
Terminal start/stop/begin/end
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.
The following table highlights all the major differences between top-down approach and bottom-up
approach −
In above calculation
Cost is the amount of computer time required for a single operation in each line.
Repeatation is the amount of computer time required by each operation for all its repeatations.
Total is the amount of computer time required by each operation to execute.
So above code requires '4n+4' Units of computer time to complete the task. Here the exact time is not fixed.
And it changes based on the n value. If we increase the n value then the time required also increases linearly.
Totally it takes '4n+4' units of time to complete its execution and it is Linear Time Complexity.
If the amount of time required by an algorithm is increased with the increase of input value then that
time complexity is said to be Linear Time Complexity.
Space complexity is usually referred to as the amount of memory consumed by the algorithm.
When we design an algorithm to solve a problem, it needs some computer memory to complete its
execution. For any algorithm, memory is required for the following purposes...
To calculate the space complexity, we must know the memory required to store different datatype values
(according to the compiler).
1. 2 bytes to store Integer value.
2. 4 bytes to store Floating Point value.
3. 1 byte to store Character value.
4. 6 (OR) 8 bytes to store double value.
If the amount of space required by an algorithm is increased with the increase of input value, then that
space complexity is said to be Linear Space Complexity.