0% found this document useful (0 votes)
11 views31 pages

Unit 1 CP (R23)

Uploaded by

uma.kumpatla000
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)
11 views31 pages

Unit 1 CP (R23)

Uploaded by

uma.kumpatla000
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/ 31

INTRODUCTION TO PROGRAMMING UNIT-1

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,
Operators.
1. HISTORY OF COMPUTERS:
What is Computer?
A computer is an electronic device used to store retrieve and manipulate data. A computer
also defines as a programmable electromechanical device that accept instruction (program) to direct
the operations of the computers. Four words can be deducted from the above definition for further
illustration.
Examples
i. Store: To put data somewhere for safe keeping
ii. Retrieve: To get and bring the data back.
iii. Process: To calculate compare arrange.
HISTORICAL BACKGROUND OF COMPUTERS

The history of computer is considered with the generations of a computer from first
generation to fifth generation. In 19th century English mathematics professor name Charles Babbage
referred as a “Father of Computer”.
Generally, computers can be classified into five generations. The generations of computer are
as follows:

First Generation of Computer (1937 – 1946):

In 1937 the first electronic digital computer was built by Dr. John V. Atanasoff and Clifford
Berry. It was called the Atanasoff-Berry Computer (ABC). In 1943 an electronic computer name the
Colossus was built for the military. Other developments continued until in 1946 the first general–
purpose digital computer, the Electronic Numerical Integrator and Calculator (ENIAC) was built. It is
said that this computer weighed 30 tons, and had 18,000 vacuum tubes which was used for
processing. When this computer was turned on for the first time lights dim in sections of
Philadelphia. Computers of this generation could only perform single task, and they had no operating
system.

Characteristics:

i. Sizes of these computers were as large as the size of a room.


ii. Possession of Vacuum Tubes to perform calculation.
iii. They used an internally stored instruction called program.
iv. Use capacitors to store binary data and information.
v. They use punched card for communication of input and output data and information
vi. They generated a lot of heat.
vii. They have about One Thousand 1000 circuits per cubic foot.

Second Generation of Computer (1947 – 1962):

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 1


INTRODUCTION TO PROGRAMMING UNIT-1

Second generation of computers used transistors instead of vacuum tubes which were more
reliable. In 1951 the first computer for commercial use was introduced to the public; the Universal
Automatic Computer (UNIVAC 1). In 1953 the International Business Machine (IBM) 650 and 700
series computers made their mark in the computer world. During this generation of computers over
100 computer programming languages were developed, computers had memory and operating
systems. Storage media such as tape and disk were in use also were printers for output.

Characteristics:

i. The computers were still large, but smaller than the first generation of computers.
ii. They use transistor in place of Vacuum Tubes to perform calculation.
iii. They were produced at a reduced cost compared to the first generation of computers.
iv. Possession of magnetic tapes as for data storage.
v. They were using punch cards as input and output of data and information. The use of
keyboard as an input device was also introduced.
vi. These computers were still generating a lot of heat in which an air conditioner is
needed to maintain a cold temperature.
vii. They have about one thousand circuits per cubic foot.

Third Generation of Computer (1963 – 1975):

The invention of integrated circuit brought us the third generation of computers. With this
invention computers became smaller, more powerful more reliable and they are able to run many
different programs at the same time.

Characteristics:

i. They used large-scale integrated circuits, which were used for both data processing
and storage.
ii. Computers were miniaturized, that is, they were reduced in size compared to
previous generation.
iii. Keyboard and mouse were used for input while the monitor was used as output
device.
iv. Use of programming language like COBOL and FORTRAN were developed.
v. They have hundred thousand circuits per cubic foot.

Fourth Generation of Computer (PC 1975 – Current):

At this time of technological development, the size of computer was redivided to


what we called Personal Computers, PC. This was the time the first Microprocessor was
created by Intel. The microprocessor was a very largescale, that is, VLS integrated circuit
which contained thousands of transistors. 15 Transistors on one chip were capable
performing all the functions of a computer’s central processing unit.

Characteristics:

i. Possession of microprocessor which performs all the task of a computer


system use today.
Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 2
INTRODUCTION TO PROGRAMMING UNIT-1

ii. The size of computers and cost was reduced.


iii. Increase in speed of computers.
iv. Very large scale (VLS) integrated circuits were used.
v. They have millions of circuits per cubic foot.

Fifth Generation of Computers (Present and Beyond)

Fifth generations computing devices, based on artificial intelligence (AI) are still in
development, although there are some application such as voice recognition, facial face detector and
thumb print that are used today.

Characteristics:

i. Consist of extremely large scale integration.


ii. Parallel processing
iii. Possession of high speed logic and memory chip.
iv. High performance, micro-miniaturization.
v. Ability of computers to mimic human intelligence, e.g. voice recognition, facial face
detector, thumb print.
vi. Satellite links, virtual reality.
vii. They have billions of circuits per cubic

2. BASIC ORGANIZATION OF A COMPUTER:


Any computer can perform the four basic operations of Input, Processing, Output, and
Storage. The internal design or structure of a computer may differ from one system to another
though the basic operations remain the same. Figure 1.1 provides a block diagram of a computer.
The figure displays all the functional units of a computer which carry out the basic computer
operations. The lines in the figure indicate the flow of instructions and data, while the Control
Unit and the Arithmetic/Logical Unit together direct the flow of control in the central processing
unit.

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 3


INTRODUCTION TO PROGRAMMING UNIT-1

Input Unit

Data and instructions are entered into the computer through the input unit to get processed
into information. Input devices like the keyboard, the mouse, or the microphone are used to
enter the data. The data is entered in various forms depending on the type of input devices. For
instance, a keyboard can be used to input characters, numbers, and certain symbols; a mouse is a
device that has an on-screen pointer that enables the users to select items and choose options; a
microphone can be used if the user wishes to enter instructions by making a voice entry.
Regardless of the ways in which the input devices receive the inputs, the input interfaces convert
them into binary codes, i.e., 0s and 1s, as the primary memory of the computer is designed to
accept data only in this format.

Central Processing Unit

The actual processing of the data is carried out in the Central Processing Unit (CPU), which is
the brain of computer. The CPU stores the data and instructions in the primary memory of the
computer, called the Random Access Memory (RAM) and processes them from this location. The
Arithmetic Logic Unit (ALU) and the Control Unit (CU) are the two subcomponents of the CPU.
The ALU carries out the arithmetic and logical operations while the CU retrieves the information
from the storage unit and interprets this information. The CPU also consists of circuitry devices
called cache and registers.

Arithmetic logic unit

The data and instructions stored in the RAM are transferred to the ALU for processing. The
ALU performs the logical and the arithmetic operations on the data and the results are
temporarily stored in the RAM. After the processing, the final results are stored in the secondary
memory, i.e., the storage unit, and are released through an output device.

Control unit (CU)

The CU obtains the program instructions stored in the primary memory of the computer,
interprets them, and issues signals that result in their execution. It helps in maintaining order and
directs the operations of the entire system. It selects, interprets, and ensures the proper
execution of the program instructions.

Output Unit

The output unit passes on the final results of computation to the users through the output
devices like the monitor, printer, etc. A monitor displays the final results of the processed data on
the screen while a printer can be used for obtaining the output in a printed format. These output
devices link the computer with the users. The output interfaces convert the binary code produced
by the computer into the human-readable form.

Storage Unit

Before the actual processing takes place, the data and instructions that enter the computer
system have to be stored internally. Also, the final results generated by the computer after
processing has to be stored before being sent to the output unit. The storage unit of a computer

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 4


INTRODUCTION TO PROGRAMMING UNIT-1

system is designed to store the data generated at various stages of processing. Storage media like
hard disks, floppy disks, etc., aid in storing the data in various forms. The hard disk is an integral
part of the computer system.

Program Counter
A program counter is a register in a computer processor that contains the address (location)
of the instruction being executed at the current time. As each instruction gets fetched, the
program counter increases its stored value by 1. After each instruction is fetched, the program
counter points to the next instruction in the sequence. When the computer restarts or is reset, the
program counter normally reverts to 0.

3. INTRODUCTION TO PROGRAMMING LANGUAGES


A programming language is a set of symbols, grammars and rules with the help of which one
is able to translate algorithms to programs that will be executed by the computer. The
programmer communicates with a machine using programming languages.
The primary classifications of programming languages are: Machine Languages, Assembly
Languages, High level Languages.
Machine Language (Low level language)
Machine language is a collection of binary digits or bits that the computer reads and
interprets. Machine language is the only language a computer is capable of understanding.
Machine level language is a language that supports the machine side of the programming or does
not provide human side of the programming. It consists of (binary) zeros and ones. Each
instruction in a program is represented by a numeric code, and numerical addresses are used
throughout the program to refer to memory locations in the computer’s memory.
Assembly language
Assembly language is easier to use than machine language. An assembler is useful for
detecting programming errors. Programmers do not have the absolute address of data items.
Assembly language encourage modular programming.
High level language
High level language is a language that supports the human and the application sides of the
programming. A language is a machine independent way to specify the sequence of operations
necessary to accomplish a task. A line in a high level language can execute powerful operations,
and correspond to tens, or hundreds, of instructions at the machine level. Consequently more
programming is now done in high level languages. Examples of high level languages are BASIC,
FORTRAN etc.

4. BASICS OF A COMPUTER PROGRAM

ALGORITHM

An algorithm is a set of instructions for solving a problem or accomplishing a task. One


common example of an algorithm is a recipe, which consists of specific instructions for preparing a
dish or meal. Every computerized device uses algorithms to perform its functions in the form of
hardware- or software-based routines. Starting from an initial state the instructions describe a
process or computational process that, when executed, proceeds through a finite number of well-
defined successive states, eventually producing "output" and terminating at a final ending state.

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 5


INTRODUCTION TO PROGRAMMING UNIT-1

All Algorithms must satisfy the following characteristics -

1) Input : There are more quantities that are extremely supplied.

2) Output : At least one quantity is produced.

3) Definiteness : Each instruction of the algorithm should be clear and unambiguous.

4) Finiteness : The process should be terminated after a finite number of steps.

5) Effectiveness : Every instruction must be basic enough to be carried out theoretically or by using
paper and pencil.

Eg: Step 1: Start


 Step 2: Declare variables num1, num2 and sum.
 Step 3: Read values for num1, num2.
 Step 4: Add num1 and num2 and assign the result to a variable sum.
 Step 5: Display sum
 Step 6: Stop

FLOWCHART

Flowchart is a graphical or pictorial representation of an algorithm. A flowchart is a picture of the


separate steps of a process in sequential order. Elements that may be included in a flowchart are a
sequence of actions, materials or services entering or leaving the process (inputs and outputs),
decisions that must be made, people who become involved, time involved at each step, and/or
process measurements.

ANSI/ISO Shape Name Description

Shows the process's order of operation. A line


coming from one symbol and pointing at
Flowline (Arrowhead)
another. Arrowheads are added if the flow is not
the standard top-to-bottom, left-to right.

Indicates the beginning and ending of a program


or sub-process. Represented as a stadium,oval or
rounded (fillet) rectangle. They usually contain
Terminal
the word "Start" or "End", or another phrase
signaling the start or end of a process, such as
"submit inquiry" or "receive product".

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 6


INTRODUCTION TO PROGRAMMING UNIT-1

Represents a set of operations that changes


Process value, form, or location of data. Represented as
a rectangle.

Shows a conditional operation that determines


which one of the two paths the program will
Decision take. The operation is commonly a yes/no
question or true/false test. Represented as a
diamond (rhombus).

Indicates the process of inputting and outputting


Input/Output data, as in entering data or displaying results.
Represented as a rhomboid.

Shows named process which is defined


Predefined Process elsewhere. Represented as a rectangle with
double-struck vertical edges

Pairs of labeled connectors replace long or


On-page Connector confusing lines on a flowchart page. Represented
by a small circle with a letter inside.

Represented by an elongated hexagon, originally


Preparation or
used for steps like setting a switch or initializing a
Initialization
routine.

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 7


INTRODUCTION TO PROGRAMMING UNIT-1

PSEUDOCODE

Pseudocode is defined as a method of describing a process or writing programming code


and algorithms using a natural language such as English. It is not the code itself, but rather a
description of what the code should do.

Consider the following source code example:


int n = 10
for( i=0;i<n;i++)
printf(n);
The above source code is converted into a pseudo-code to understand in a better way.
The value ten is assigned to the variable n.
For value = zero to less than a number.
Display the numbers.

5. INTRODUCTION TO COMPILATION AND EXECUTION


Compilation
The compiler program translates the instructions of a high level language to a machine level
language. A separate compiler is required for every high level language. High level language is simply
a programmer’s convenience and cannot be executed in their source. The actual high - level program
is called a source program. It is compiled (translated) to machine level language program called
object program for that machine by the compiler. Such compilers are called self- resident compilers.
Compiler compiles the full program and reports the errors at the end.

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 8


INTRODUCTION TO PROGRAMMING UNIT-1

Compilation Process
The compilation and execution process of C can be divided into 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.

Linking
 After all of the files are compiled, they must be "merged together" to produce a single
executable file that the user use to run the program.
 In C, most compiled programs produce results only with the help of some standard programs,
known as library files that reside in the computer. This process is called linking.
 The result obtained after linking is called the executable file.
 The linker′s primary function is to bind symbolic names to memory addresses.
 To do this, it first scans the files and concatenates the related file sections to form one large
file. Then, it makes a second pass on the resulting file to bind symbol names to real memory
addresses.
 Loading is loading the executable into memory prior to execution.
 There are two types of linking: Static linking. Dynamic linking.
 Static linking occurs at compilation time; hence it occurs prior to loading a program. With
static linking the external symbols that are used by the program (e.g. function names) are
resolved at compile time.
 Dynamic linking occurs at run time, so it occurs after or at the time of the loading of a
program. With dynamic linking the symbols are resolved either at loading time, or at run time

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 9


INTRODUCTION TO PROGRAMMING UNIT-1

when the symbol is accessed (lazy binding).


Loading
 After the files are compiled and linked the executable file is loaded in the computer′s memory
for executing by the loader. This process is called Loading.
 Program loading is basically copying a program from secondary storage into main memory so
it ′s ready to run.
 In some cases, loading us just not copying the data from disk to memory, but also setting
protection bits, or arranging for virtual memory map virtual addresses to disk pages.

6. PRIMITIVE DATA TYPES

A data type specifies the type of data that a variable can store such as integer, floating, character,
etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 10


INTRODUCTION TO PROGRAMMING UNIT-1

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

Int:

Integers are entire numbers without any fractional or decimal parts, and the int data type is used to
represent them. It is frequently applied to variables that include values, such as counts, indices, or
other numerical numbers. The int data type may represent both positive and negative
numbers because it is signed by default.

An int takes up 4 bytes of memory on most devices, allowing it to store values between around -2
billion and +2 billion.

Char:

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 11


INTRODUCTION TO PROGRAMMING UNIT-1

Individual characters are represented by the char data type. Typically used to hold ASCII or UTF-8
encoding scheme characters, such as letters, numbers, symbols, or commas. There are 256
characters that can be represented by a single char, which takes up one byte of memory. Characters
such as 'A', 'b', '5', or '$' are enclosed in single quotes.

Float:

To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.

The float type is usually used for variables that require very good precision but may not be very
precise. It can store values with an accuracy of about 6 decimal places and a range of about 3.4 x
1038 in 4 bytes of memory.

Double:

Use two data types to represent two floating integers. When additional precision is needed, such as
in scientific calculations or financial applications, it provides greater accuracy compared to float.

Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places, yields
larger values. C treats floating point numbers as doubles by default if no explicit type is supplied.

1. int age = 25;


2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;

In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two variables for
the number pi.

7. VARIABLES AND CONSTANTS

Variables
The variable is used to store the value. As the name indicates its value can be changed or also it can
be reused many times. We have to define its Data Types in C as shown below.
Syntax :
Datatype variable_name;
e.g. int a;
Where ‘a’ is the variable.

Types of Variables in C:
There are many types of variables in c:

 local variable
 global variable
 static variable
 external variable
 Automatic variable

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 12


INTRODUCTION TO PROGRAMMING UNIT-1

1. Local variable – A variable which is declared inside the function is known as local variable. It is
used only inside the function in which it is declared.
2. Global variable – A variable which is declared outside the function is known as global variable. It
can be used throughout the program.
3. Static variable – It is used to retain its value between multiple function calls. It is declared using
static keyword.
4. External variable – You can share a variable in multiple C source files by using external variable. It
is declared using extern keyword.
5. Automatic variable – Variable which is declared inside the block is known as automatic variable by
default.

Constants:

Its value is fixed throughout the program that means constants are those variables which value is not
changed throughout the program.
C constants can be divided into two major categories:

 Primary Constants
 Secondary Constants

There are two simple ways in C to define constants:

1. Using #define
#include <stdio.h>
#define value 10
void main() {
int data;
data = value*value;
printf("value of data : %d",data);
}

Output
value of data : 100

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 13


INTRODUCTION TO PROGRAMMING UNIT-1

2. Using const keyword


#include <stdio.h>
void main() {
const int value = 10;
int data;
data =value*value;
printf("value of data : %d",value);
}

Output
value of data : 100

8. BASIC INPUT AND OUTPUT

 Input means to provide the program with some data to be used in it.
 Output means to display data on the screen or write the data to a printer or a file.
There are two types of input output functions:
i. Unformatted Input/Output functions
ii. Formatted Input/Output functions

i. Unformatted Input/Output functions:


Unformatted I/O functions are used only for character data type or character array/string and
cannot be used for any other datatype. These functions are used to read single input from the user
at the console and it allows to display the value at the console. These functions are called
unformatted I/O functions because we cannot use format specifiers in these functions,

The following are unformatted I/O functions -

1. getchar()
2. putchar()
3. gets()
4. puts()
5. getch()

1. getchar(): The getchar() function is used to read only a first single character from the
keyboard whether multiple characters is typed by the user and this function reads one
character at one time until and unless the enter key is pressed. This function is declared in
stdio.h(header file)

Syntax: Variable-name = getchar();


Example: char ch;
ch=getchar()
Ex: // C program to implement
// the getchar() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 14


INTRODUCTION TO PROGRAMMING UNIT-1

{
// Declaring a char type variable
char ch;

printf("Enter the character: ");

// Taking a character from keyboard


ch = getchar();

// Displays the value of ch


printf("%c", ch);
return 0;
}
Output:
Enter the character: a
a

2. putchar(): The putchar() function is used to display a single character at a time by passing that
character directly to it or by passing a variable that has already stored a character. This
function is declared in stdio.h(header file)

Syntax: putchar(variable_name);
Ex: // C program to implement
// the putchar() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
char ch;
printf("Enter any character: ");

// Reads a character
ch = getchar();

// Displays that character


putchar(ch);
return 0;
}
Output:
Enter any character: Z
Z

3. gets(): gets() function reads a group of characters or strings from the keyboard by the user and
these characters get stored in a character array. This function allows us to write space-separated
texts or strings. This function is declared in stdio.h(header file).

Syntax: gets(variable_name)

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 15


INTRODUCTION TO PROGRAMMING UNIT-1

Ex: char str[length of string in number]; //Declare a char type variable of any length
gets(str);
Ex: //C program to implement
// the gets() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
// Declaring a char type array of length 50 characters
char name[50];
printf("Please enter some texts: ");

// Reading a line of character or a string


gets(name);

// Displaying this line of character or a string


printf("You have entered: %s",name);
return 0;
}
Output:
Please enter some texts: Welcome to BVCITS
You have entered: Welcome to BVCITS

4. puts(): In C programming puts() function is used to display a group of characters or strings which
is already stored in a character array. This function is declared in stdio.h(header file).

Syntax: puts(identifier_name );

Ex: // C program to implement


// the puts() function
#include <stdio.h>
#include <conio.h>
// Driver code
int main()
{
char name[50];
printf("Enter your text: ");

// Reads string from user


gets(name);

printf("Your text is: ");

// Displays string
puts(name);

return 0;
}

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 16


INTRODUCTION TO PROGRAMMING UNIT-1

Output:
Enter your text: Welcome to BVCITS
Your text is: Welcome to BVCITS

5. getch(): getch() function reads a single character from the keyboard by the user but doesn’t
display that character on the console screen and immediately returned without pressing enter
key. This function is declared in conio.h(header file). getch() is also used for hold the screen.

Syntax: getch();
or variable-name = getch();
Ex: // C program to implement getch() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
printf("Enter any character: ");

// Reads a character but


// not displays
getch();

return 0;
}
Output:
Enter any character:
ii. Formatted Input/Output functions:

Formatted I/O functions are used to take various inputs from the user and display multiple
outputs to the user. These types of I/O functions can help to display the output to the user in
different formats using the format specifiers. These I/O supports all data types like int, float, char,
and many more. These functions are called formatted I/O functions because we can use format
specifiers in these functions.

List of some format specifiers-

Format Specifier
S NO. Type Description

int/signed
1 %d used for I/O signed integer value
int
2 %c char Used for I/O character value
3 %f float Used for I/O decimal floating-point value
Used for I/O string/group of characters
4 %s string

5 %ld long int Used for I/O long signed integer value
6 %u unsigned int Used for I/O unsigned integer value

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 17


INTRODUCTION TO PROGRAMMING UNIT-1

7 %i unsigned int used for the I/O integer value


8 %lf double Used for I/O fractional or floating data

The following are formatted I/O functions -

1. printf()
2. scanf()

1. printf(): printf() function is used in a C program to display any value like float, integer, character,
string, etc on the console screen. It is a pre-defined function that is already declared in the
stdio.h(header file).

Syntax 1:

To display any variable value.

printf(“Format Specifier”, var1, var2, …., varn);

Ex: // C program to implement


// printf() function
#include <stdio.h>
// Driver code
int main()
{
// Declaring an int type variable
int a;

// Assigning a value in a variable


a = 20;

// Printing the value of a variable


printf("%d", a);

return 0;
}
Output
20

Syntax 2:

To display any string or a message

printf(“Enter the text which you want to display”);

Ex:// C program to implement


// printf() function

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 18


INTRODUCTION TO PROGRAMMING UNIT-1

#include <stdio.h>

// Driver code
int main()
{
// Displays the string written
// inside the double quotes
printf("This is a string");
return 0;
}
Output
This is a string

2. scanf(): scanf() function is used in the C program for reading or taking any value from the
keyboard by the user, these values can be of any data type like integer, float, character, string,
and many more. This function is declared in stdio.h(header file), that’s why it is also a pre-defined
function. In scanf() function we use &(address-of operator) which is used to store the variable
value on the memory location of that variable.

Syntax: scanf(“Format Specifier”, &var1, &var2, …., &varn);

Ex: // C program to implement scanf() function


#include <stdio.h>

// Driver code
int main()
{
int num1;

// Printing a message on
// the output screen
printf("Enter a integer number: ");

// Taking an integer value


// from keyboard
scanf("%d", &num1);

// Displaying the entered value


printf("You have entered %d", num1);

return 0;
}
Output:
Enter a integer number: 56
You have entered 56

9. TYPE CONVERSION, AND CASTING


C Type Conversion
In C programming, we can convert the value of one data type (int, float, double, etc.) to another. This

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 19


INTRODUCTION TO PROGRAMMING UNIT-1

process is known as type conversion. Let's see an example,


#include <stdio.h>
#include<conio.h>
int main() {
int number=34.78;
printf("%d", number);
return 0;
}
Output: 34
Here, we are assigning the double value 34.78 to the integer variable number. In this case, the double
value is automatically converted to integer value 34.
This type of conversion is known as implicit type conversion. In C, there are two types of type
conversions:
1. Implicit Conversion
2. Explicit Conversion
Implicit Type Conversion In C
As mentioned earlier, in implicit type conversion, the value of one type is automatically converted to
the value of another type. For example,
#include<stdio.h>
int main() {
// create a double variable
double value = 4150.12;
printf("Double Value: %.2lf\n", value);
// convert double value to integer
int number = value;
printf("Integer Value: %d", number);
return 0;
}

Output

Double Value: 4150.12


Integer Value: 4150

The above example has a double variable with a value 4150.12. Notice that we have assigned the
double value to an integer variable.

int number = value;

Here, the C compiler automatically converts the double value 4150.12 to integer value 4150. Since
the conversion is happening automatically, this type of conversion is called implicit type conversion.

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 20


INTRODUCTION TO PROGRAMMING UNIT-1

Example: Implicit Type Conversion

#include<stdio.h>
#include<conio.h>
int main() {
// character variable
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);
// assign character value to integer variable
int number=alphabet;
printf("Integer Value: %d", number);
return 0;
}

Output

Character Value: a
Integer Value: 97

The code above has created a character variable alphabet with the value 'a'. Notice that we are
assigning alphabet to an integer variable.

int number = alphabet;

Here, the C compiler automatically converts the character 'a' to integer 97. This is because, in C
programming, characters are internally stored as integer values known as ASCII Values.
ASCII defines a set of characters for encoding text in computers. In ASCII code, the character 'a' has
integer value 97, that's why the character 'a' is automatically converted to integer 97.
If you want to learn more about finding ASCII values, visit find ASCII value of characters in C.

Explicit Type Conversion In C


In explicit type conversion, we manually convert values of one data type to another type. For example,
#include<stdio.h>
int main() {
// create an integer variable
int number = 35;
printf("Integer Value: %d\n", number);
// explicit type conversion
double value=(double) number;
printf("Double Value: %.2lf", value);
return 0;
}

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 21


INTRODUCTION TO PROGRAMMING UNIT-1

Output

Integer Value: 35
Double Value: 35.00

We have created an integer variable named number with the value 35 in the above program. Notice
the code,

// explicit type conversion


double value = (double) number;

Here,
(double) - represents the data type to which number is to be converted.
number - value that is to be converted to double type.

Example: Explicit Type Conversion

#include<stdio.h>
#include<conio.h>
int main() {
// create an integer variable
int number = 97;
printf("Integer Value: %d\n", number);
// (char) converts number to character
char alphabet = (char) number;
printf("Character Value: %c", alphabet);
return 0;
}

Output

Integer Value: 97
Character Value: a

We have created a variable number with the value 97 in the code above. Notice that we are
converting this integer to character.

char alphabet = (char) number;

Here,

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 22


INTRODUCTION TO PROGRAMMING UNIT-1

 (char) - explicitly converts number into character


 number - value that is to be converted to char type

Data Loss In Type Conversion

In our earlier examples, when we converted a double type value to an integer type, the data after
decimal was lost.
#include<stdio.h>
int main() {
// create a double variable
double value = 4150.12;
printf("Double Value: %.2lf\n", value);
// convert double value to integer
int number=value;
printf("Integer Value: %d", number);
return 0;
}

Output

Double Value: 4150.12


Integer Value: 4150

Here, the data 4150.12 is converted to 4150. In this conversion, data after the decimal, .12 is lost.
This is because double is a larger data type (8 bytes) than int (4 bytes), and when we convert data
from larger type to smaller, there will be data loss..
Similarly, there is a hierarchy of data types in C programming. Based on the hierarchy, if a higher data
type is converted to lower type, data is lost, and if lower data type is converted to higher type, no
data is lost.

Possible Data Loss During C Type Conversion


Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 23
INTRODUCTION TO PROGRAMMING UNIT-1

Here,
 data loss - if long double type is converted to double type
 no data loss - if char is converted to int

10. PROBLEM SOLVING STRATEGIES: TOP-DOWN APPROACH, BOTTOM-UP APPROACH

Top-Down Approach:
In the top-down approach, a complex algorithm is broken down into smaller fragments, better
known as ‘modules.’ These modules are then further broken down into smaller fragments until they
can no longer be fragmented. This process is called ‘modularization.’
By breaking a bigger problem into smaller fragments, the top-down approach minimizes the
complications usually incurred while designing algorithms. In this approach, each function in a code is
unique and works independently of other functions. The top-down approach is mainly used by
Structured programming languages like C, Fortran, etc.

How the Top-Down Approach Works?


The working of top-down approach is as follows:

 Identify the goal or problem:


The goal or problem needs to be clearly identified and measurable.
 Break it down into sub-goals:
The sub-goals/sub-problems are what the top-up approach is all about.
 Solve each sub-goal/sub-problem:
Using the same top-up approach, the sub-problems/sub-goals/problems are broken down
into smaller manageable parts.
 Repeat steps 2 and 3 until the overall goal/problems are resolved:
The top-up approach may involve multiple iterations.

Advantages

 Each module of code is to be tested separately.


 Breaking a problem down into smaller chunks makes it far easier to understand, solve and
manage.
 Testing and debugging are efficient and easier.
 Project implementation is smoother and shorter.

Disadvantages

 Specification tends to change over time and in a top-down approach, all decisions made from
the beginning of the project depend directly or indirectly on the high-level specification.
 In Dynamic Programming, the top-down approach is slow as compared to the bottom-up
approach, as it involves recursion.
 There is a chance of stack overflow here.
 It takes more memory space as it involves recursion

Bottom-Up Approach

Contrary to the top-down approach, bottom-up programming focuses on designing an algorithm by


beginning at the very basic level and building up as it goes. In this approach, the modules are

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 24


INTRODUCTION TO PROGRAMMING UNIT-1

designed individually and are then integrated together to form a complete algorithmic design.
Moreover, the bottom-up approach is more suitable when a system needs to be created from some
existing components.

So, in this method, each and every module is built and tested at an individual level (unit testing) prior
to integrating them to build a concrete solution. The unit testing is performed by leveraging specific
low-level functions. The bottom-up approach is used by Object-Oriented programming languages like
C++, C#, Java, etc.

How the Bottom-Up Approach Works?

The working of bottom-up approach is as follows:

 Identify the components or tasks:


The components or tasks need to be clearly identified and measurable.

 Build the system or solution:


The system or solution gets its name from the fact that it is built from the individual
components/tasks.

 Test:
The system/solution needs to be tested to meet the requirements. This can be done by
running a series of tests on the system/solution.

 Repeat steps 2 and 3:


This may involve several iterations of the bottom-up approach.

Advantages

 Test conditions are easier to create.


 Observation of test results is easier.
 Contains less redundancy due to the presence of data encapsulation and data-hiding.
 Reusability of the code.

Disadvantages

 In the Bottom-Up approach, we solve all sub-problems (even though some of the solutions of
the subproblems aren’t needed to solve), which requires additional calculations.
 In the Bottom-Up approach, sometimes it is difficult to identify the overall functionality of the
system in the initial stages.
 As this is an iterative approach, more code needs to be written.
 It is more difficult to implement.

11. TIME AND SPACE COMPLEXITIES

 The efficiency of an algorithm can be computed by measuring the performance of an


algorithm. We can measure the performance of an algorithm in two(2) ways.
1. Time Complexity

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 25


INTRODUCTION TO PROGRAMMING UNIT-1

2. Space Complexity
1. Time Complexity:
 The time complexity of an algorithm is the amount of computing time required by an
algorithm to run its completion.
 There are 2 types of computing time 1. Compile time 2. Run time
 The time complexity generally computed at run time (or) execution time.
 The time complexity can be calculated in terms of frequency count.
 Frequency count is a count denoting the number of times the statement should be executed.
 The time complexity can be calculated as Comments – 0
Assignment / return statement – 1
Conditional (or) Selection Constructs – 1
Example 1: Sum of the elements in an Array

Statements Step count/ Execution Frequency Total Steps


Algorithm Addition (A,n) 0 - 0
{ 0 - 0
//A is an array of size ‘n’ 0 - 0
Sum :=0; 1 1 1
for i:=1 to n do 1 n+1 n+1
Sum:=Sum+A[i]; 1 n n
return Sum; 1 1 1
} 0 - 0
Total 2n+3

Example 2: Subtraction of two matrices

Statements Step count/ Execution Frequency Total Steps


Algorithm Subtract (A,B,C,m,n) 0 - 0
{ 0 - 0
for i:=1 to m do 1 m+1 m+1
for j:=1 to n do 1 m(n+1) mn+m
C[i,j] := A[i,j] – B[i,j]; 1 mn mn
} 0 - 0
Total 2mn+2m+1

2. Space Complexity:
 Space Complexity can be defined as amount of memory (or) space required by an
Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 26
INTRODUCTION TO PROGRAMMING UNIT-1

Algorithm to run.
 To compute the space complexity we use 2 factors i. Constant ii. Instance characteristics.
 The space requirement S(p) can be given as S(p) = C+Sp
Where C- Constant, it denotes the space taken for input and
output. Sp – Amount of space taken by an instruction,
variable and identifiers.

Example 1: Sum of three numbers


Algorithm Add(a,b,c)
{
//a,b,c are float type
variables return
a+b+c;
}
 The space required for this algorithm is: Assume a,b,c are occupies 1 word size each, total
size comes to be 3.

Example 2: Sum of Array values


Algorithm Addition (A,n)
{
//A is an array
of size ‘n’ Sum
:=0;
for i:=1 to n
do
Sum:=Su
m+A[i];
return Sum;
}
 The space required for this algorithm is:
One word space for each variable then i,sum,n 3

For Array A[ ] we require the size n


Total space complexity for this algorithm is S(p) ≥ (n+3)

What to Analyze in an algorithm:


An Algorithm can require different times to solve different problems of same size
1. Worst case: Maximum amount of time that an algorithm require to solve a problem
of size ‘n’. Normally we can take upper bound as complexity. We try to find worst
case behavior.
2. Best case: Minimum amount of time that an algorithm require to solve a problem
Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 27
INTRODUCTION TO PROGRAMMING UNIT-1

of size ‘n’. Normally it is not much useful.


3. Average case: the average amount of time that an algorithm require to solve a
problem of size ‘n’. Some times it is difficult to find. Because we have to check all
possible data organizations

12. TYPES OF OPERATORS

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.
C language is rich in built-in operators and provides the following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators

Arithmetic Operators

The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators

The following table shows all the relational operators supported by C. Assume variable A holds 10
and variable B holds 20 then –

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 28


INTRODUCTION TO PROGRAMMING UNIT-1

Operator Description Example

(A == B)
Checks if the values of two operands are equal or not. If yes, then the
== is not
condition becomes true.
true.

Checks if the values of two operands are equal or not. If the values are not (A != B)
!=
equal, then the condition becomes true. is true.

Checks if the value of left operand is greater than the value of right (A > B) is
>
operand. If yes, then the condition becomes true. not true.

Checks if the value of left operand is less than the value of right operand. If (A < B) is
<
yes, then the condition becomes true. true.

(A >= B)
Checks if the value of left operand is greater than or equal to the value of
>= is not
right operand. If yes, then the condition becomes true.
true.

Checks if the value of left operand is less than or equal to the value of right (A <= B)
<=
operand. If yes, then the condition becomes true. is true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0, then −

Show Examples

Operator Description Example

Called Logical AND operator. If both the operands are non-zero, then the (A && B)
&&
condition becomes true. is false.

Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is


||
the condition becomes true. true.

Called Logical NOT Operator. It is used to reverse the logical state of its !(A && B)
!
operand. If a condition is true, then Logical NOT operator will make it false. is true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows –

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 29


INTRODUCTION TO PROGRAMMING UNIT-1

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then −

Show Examples

Operator Description Example

(A & B) =
& Binary AND Operator copies a bit to the result if it exists in both operands. 12, i.e.,
0000 1100

(A | B) =
| Binary OR Operator copies a bit if it exists in either operand. 61, i.e.,
0011 1101

(A ^ B) =
^ Binary XOR Operator copies the bit if it is set in one operand but not both. 49, i.e.,
0011 0001

Binary One's Complement Operator is unary and has the effect of 'flipping' (~A ) =
~
bits. ~(60), i.e,.

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 30


INTRODUCTION TO PROGRAMMING UNIT-1

-0111101

A << 2 =
Binary Left Shift Operator. The left operands value is moved left by the
<< 240 i.e.,
number of bits specified by the right operand.
1111 0000

A >> 2 =
Binary Right Shift Operator. The left operands value is moved right by the
>> 15 i.e.,
number of bits specified by the right operand.
0000 1111

Assignment Operators

The following table lists the assignment operators supported by the C language −

Show Examples

Operator Description Example

C = A + B will
Simple assignment operator. Assigns values from right side operands to left assign the
=
side operand value of A +
B to C

C += A is
Add AND assignment operator. It adds the right operand to the left operand
+= equivalent
and assign the result to the left operand.
to C = C + A

C -= A is
Subtract AND assignment operator. It subtracts the right operand from the
-= equivalent
left operand and assigns the result to the left operand.
to C = C - A

C *= A is
Multiply AND assignment operator. It multiplies the right operand with the
*= equivalent
left operand and assigns the result to the left operand.
to C = C * A

C /= A is
Divide AND assignment operator. It divides the left operand with the right
/= equivalent
operand and assigns the result to the left operand.
to C = C / A

C %= A is
Modulus AND assignment operator. It takes modulus using two operands
%= equivalent
and assigns the result to the left operand.
to C = C % A

Prepared by N.Sushuma, Assoc. Prof., Dept. of CSE, BVCITS Page 31

You might also like