Module-1
Module-1
Faculty:
Dr Purushotham. U & Dr. Vikhyath K B
Ø Introduction to computers
Ø Input and output devices
Ø Designing efficient programs
Ø Structure of C program
Ø Files used in a C program
Ø Compilers - Compiling and Executing C programs
Ø Variables and Constants
Ø Input/output statements in C
üInput
üProcessing
üOutput
üStorage
In the event of an error, it is the user who has fed the incorrect
data/program is responsible.
If the input data is wrong, then the output will also be erroneous. In
computer terminology, this is known as garbage-in, garbage-out
(GIGO) .
The user just needs to assign the task to the computer, after which it
automatically controls different devices attached to it and executes
the program instructions.
For example, they are used as personal computers (PCs) for home
use, for business-oriented tasks, weather forecasting, space
exploration, teaching, railways, banking, medicine, and so on,
indicating that computers can perform different tasks simultaneously.
On the PC that you use at home, you may play a game, compose and
send e-mails, listen to music, etc.
While the internal memory of computers is very expensive and limited in size,
the secondary storage is cheaper and of bigger capacity.
The computer stores a large amount of data and programs in the secondary
storage space. The stored data and programs can be retrieved and used
whenever required. Secondary memory is the key for data storage.
Some examples of secondary devices include floppy disks, optical disks (CDs
and DVDs), hard disk drives (HDDs), and pen drives.
When data and programs have to be used, they are copied from the secondary
memory into the internal.
Ø Instructions are stored in the computer’s memory for execution in binary form (only 0s
and 1s).
Ø Processing starts with the first instruction in the program, which is copied into a control
unit which executes the instructions.
Ø Instructions written by the users are executed sequentially until there is a break in the
current flow.
Ø Input/output and processing operations are performed parallelly. While data is being
read/written, the central processing unit (CPU) executes another program in the
memory that is ready for execution.
Dr H N National College of Engineering 23
Types of Stored Program Concept
Ø Same memory for Instructions and Data
Ø Different memory for Instructions and Data
Today, our smart phones have much more computing power than that was
available in those early computers.
Timeline of Developments:
300 BC: The abacus was an early aid for mathematical computations and was
designed to aid human’s memory while performing calculations.
A skilled abacus operator can add and subtract with the same speed as that of a
person performing the same calculation using a hand calculator.
1946: Mauchly and Presper designed the UNIVAC, which was the first
commercial computer for business and government applications.
1947: William Shockley, John Bardeen, and Walter Brattain of Bell Laboratories
invented the transistor. Soon vacuum tubes in computers were replaced by transistors.
1953: Grace Hopper developed the first computer language COBOL. 1954: The
FORTRAN programming language was developed.
1958: Jack Kilby of Texas Instruments and Robert Noyce at Fairchild Semiconductor
Corporation separately invented integrated circuit, which is commonly known as the
computer chip.
1964: Douglas Engelbart developed a prototype of the modern computer, with a mouse
and a graphical user interface (GUI). This was a remarkable achievement as it shifted
computers from a specialized machine for scientists and mathematicians to general
public.
Memory: Electromagnetic relay was used as primary memory and punched cards were
used to store data and instructions.
Highlights:
Computers were too bulky and required a complete room for storage
Highly unreliable as vacuum tubes emitted a large amount of heat and burnt frequently
Required constant maintenance because vacuum tubes used filaments that had limited life time.
Therefore, these computers were prone to frequent hardware failures
Memory: Magnetic core memory was used as primary memory; magnetic tapes and
magnetic disks were used to store data and instructions. These computers had faster
and larger memory than the first generation computers.
Faster, smaller, cheaper, reliable, and easier to use than the first generation computers.
Dissipated less heat than first generation computers but still required air-conditioned
rooms
Costly
Difficult to use
Dissipated less heat than second generation computers but still required air-conditioned
rooms.
Costly
Programming is done in
Software Technology:
high-level programming languages such as
Java, Python, and C#. Graphical User
Interface (GUI)-based operating systems
such as Windows, Unix, Linux, Ubuntu, and
Apple Mac are being used.
Such computers are mainly used for weather forecasting, nuclear energy
research, aircraft design, automotive design, online banking, controlling
industrial units, etc.
These are very expensive and need a very large clean room with
air conditioning, thereby making them very costly to deploy.
Workstation:
Single user computer.
Same features as PCs with higher processing speed.
Have advanced processors, more RAM and storage capacity.
Can be used as servers in a networked environment.
Network Computers:
Designed to be used as terminals in a networked environment.
Have less processing power, memory and storage.
Those used to access internet or intranet are often known as
internet PCs or internet boxes.
Some used in homes do not even have a monitor. They may be
connected to a TV. They are called WebTV.
While users can easily type directly on the surface of a tablet, some
users prefer a wireless or bluetooth-connected keyboard. These days,
tablets also offer an optional docking station with keyboards that
transforms the tablet into a full-featured notebook.
View presentations
Video-conferencing
Reading e-books, e-newspaper Watching movies, Playing games
Sharing pictures, video, songs, documents
Keeping in touch with friends and family on popular social networks, sending
emails
Business people use them to perform tasks such as editing a document,
exchanging documents, taking notes, and giving presentations
Tablets are best used in crowded places such as airports and coffee shops,
where size and portability become more important.
Later on, computers were used in real-time control systems, like for landing on
the moon, radar/missile
However, with the advancement of technology, the cost of computers and their
maintenance declined. This opened the way for computers to be extensively
used in the business and commercial sector for information processing.
Today, computers are widely used in fields such as engineering, health care,
banking, education, etc.
Word processing: Word processing software enables users to read and write
documents. Users can also add images, tables, and graphs for illustrating a
concept. The software automatically corrects spelling mistakes and includes
copy–paste features (which is very useful where the same text has to be
repeated several times).
Internet: Network of networks that connects computers all over the world. It
gives the user access to an enormous amount of information, much more than
available in any library. Using e-mail, the user can communicate in seconds
with a person who is located thousands of miles away. Chat software enables
users to chat with another person in real-time. Video conferencing tools are
becoming popular for conducting meetings with people who are unable to be
present at a particular place.
Note that computers understand binary language, which consists of only two
symbols (0 and 1), so it is the responsibility of the input devices to convert the
input data into binary codes.
It is used to store the data and parts of programs, the intermediate results of
processing, and the recently generated results of jobs that are currently being
worked on by the computer.
An example is the magnetic disk used to store data, such as C and D drives, for
future use.
Output: The process of giving the result of data processing to the outside world
(external to the computer system).
Control Unit: It is the central nervous system of the computer system that
manages and controls all the other components.
The results are given through output devices such as monitor, and printer.
Since the computer accepts data only in binary form and the result of
processing is also in binary form, the result cannot be directly given to the user.
The output devices, therefore, convert the results available in binary codes into
a human readable language before displaying it to the user.
CPU is the combination of the arithmetic logic unit (ALU) and the CU. It is the
brain of the computer system because the entire processing of data is done in
the ALU, and the CU activates and monitors the operations of other units (such
as input, output, and storage) of the computer system.
Processing is the process of performing operations on the data as per the instructions
specified by the user (program) is called processing.
Data and instructions are taken from the primary memory and transferred to the ALU,
which performs all sorts of calculations. The intermediate results of processing may be
stored in the main memory, as they might be required again.
When the processing completes, the final result is then transferred to the main memory.
Hence, the data may move from main memory to the ALU multiple times before the
processing is over
Keyboards:
The most common of all input devices is the keyboard. Several versions of
keyboards are available. The best and most expensive of these is the full-stroke
keyboard.
This is ideal for word processing and other volume data and program entry
activities. This type of keyboard is available with most mainframe computer
terminals or the expensive microcomputer systems.
This QWERTY keyboard arrangement has been used for nearly a century.
Thus, Dvorak rearranged the keyboard so that the five more frequently used vowels (a,
o, e, u, and i) and the five most frequently used consonants (d, h, t, n, and s) were
positioned on the home row where the fingers of the left and right hands rest,
respectively.
Thus, 70 percent of the typing is done on the home row. He then placed the next most
frequently used characters in the row above the home row and the least frequently used
characters in the row below the home row. This resulted in a reduction of finger
movement of approximately 80 percent and overall, an increase in productivity of
nearly 40 percent.
Expert typists and word processors generally agree that using the Dvorak
arrangement increases productivity while simultaneously decreasing fatigue.
The world's fastest typing speed, nearly 200 words per minute, was achieved
on a Dvorak keyboard. Despite these improvements the QWERTY keyboard
arrangements is still the most common because of the difficulty of overcoming
inertia and retraining.
Monitors: most commonly used display device that utilizes a cathode ray tube
(CRT).
When the electron beam has scanned the entire screen and
illuminated each pixel, one can see a complete image.
The image that can be seen is the one traced on the retinas of eyes by
the light beam. However, this image will fade unless it is refreshed.
Thus, the electron beam must scan the screen very rapidly (a
minimum of 60 times per second), so that the intensity of the image
remains approximately the same and the screen does not appear to
flicker.
Printers are capable of printing from 150 to over 20,000 lines per minute, with
each line having up to 150 characters.
https://www.ebookbou.edu.bd/Books/Text/SST/DCSA/dcsa_1201/Un
it-04.pdf
https://www.scribd.com/presentation/460442828/computer-Chapter-2
Drum plotters
Used to draw graphics on paper that is wrapped around a drum
Usually used with mainframe and minicomputer systems
Flatbed plotters
The paper is spread on the flat rectangular surface of the plotter, and the pen is moved
over it
Less expensive, and are used in many small computing systems
Laser Printers
Work at very high speeds and produce high-quality text and graphics.
A laser beam ‘draws’ the document on a drum which is coated with a photo-
conductive material.
After the drum is charged , it is rolled in a toner (a dry powder type of ink)
The toner sticks to the charged image on the drum and transferred onto a piece
of paper.
Advantages
Produce prints of good quality
Noiseless, fast
Can print text in different fonts
Disadvantage
Expensive as ink cartridges used by them are costly
Dr H N National College of Engineering 109
Designing Efficient Programs
PROGRAMMING PARADIGMS
A programming paradigm is a fundamental style of programming that defines
how the structure and basic elements of a computer program will be built.
The style of writing programs and the set of capabilities and limitations that a
particular programming language has depends on the programming paradigm it
supports.
Although C was initially developed for writing system software, today it has become
such a popular language that a variety of software programs are written using this
language.
The greatest advantage of using C for programming is that it can be easily used on
different types of computers.
Many other programming languages such as C++ and Java are also based on C which
means that you will be able to learn them easily in the future. Today, C is widely used
with the UNIX operating system.
https://www.ebookbou.edu.bd/Books/Text/SST/DCSA/dcsa_1201/Unit-04.pdf
https://www.scribd.com/presentation/460442828/computer-Chapter-2
ALGOL’s introduced in 1960s led the way for the development of structured
programming concept.
In 1970, Ken Thompson developed a language called B, which was used to develop a
first version of UNIX.
C was developed by Dennis Ritchie in 1972 that took concepts from ALGOL, BCPL,
and B.
The traditional C was documented and popularized in the book The C Programming
Language by Brain W. Kernighan and Dennis Rictchie in 1978.
In 1995, some minor changes were made to C89; the new modified version
was known as C95.
Extension to the character type so that they can support even non-English
types.
Boolean Data Type
Extension to the integer data type
Inclusion of type definitions in the for statements
Inclusion of imaginary and complex types
Addition of //, better known as C++ style line comment
Characteristics of C language:
The main() function is the most important function and is a part of every C
program. Rather, the execution of a C program begins with this function.
C program can have any number of functions depending on the tasks that have
to be performed, and each function can have any number statements.
You can choose any name for functions with an exception that every program
must contain one function that has its name as main().
Note: Data declaration section within the functions are known as local
declaration as that data will be visible only within that function. The
statement section in a function contains the code that manipulates the
data to perform a specific task.
#include<stdio.h>: stdio basically stands for Standard Input/Output, which means it has
functions for input and output of data like reading values from the keyboard and printing
the results on the screen.
int main(): Every C program contains a main() function which is the starting point of the
program. int is the return value of the main function. After all the statements in the
program have been executed, the last statement of the program will return an integer
value to the operating system.
{ } The two curly brackets are used to group all the related statements of the main
function.
If there are any mistakes in the program, then the compiler will tell you what
mistake(s) you have made and on which line the error has occurred.
In case of errors, you need to re-open your .c file and correct the mistakes.
However, if everything is right, then no error(s) will be reported and the
compiler will create an .exe file for your program.
This .exe file can be directly run by typing "first.exe" for Windows and "./first"
for UNIX/Linux operating system. When you run the .exe file, the output of
the program will be displayed on screen. That is,
All the header files are referenced at the start of the source code file that uses one or
more functions from these files.
Ø Compile the subroutines once and use them many times in different programs
(where these subroutines are by linking to the object file at run time.
Ø If you want to make changes to the subroutines, then change is done at one
place and only Change is reflected in the programs wherever the subroutines
(defined in the header file) are called.
SourceFile->Preprocessor->Compiler->ObjectFiles->Linker->ExecutableFiles
While the C program is human-readable, the executable file on the other hand is
machine-readable.
The mechanical parts of running the C program begins with one or more program
source files, and ends with an executable file, which can be run on a computer.
The programming process starts with creating a source file and this is then processed
by a special program called a compiler.
The compiler translates the source code into an object code. The object code contains
the machine instructions for the CPU, and calls to the operating system API
(Application Programming Interface).
Source code lines which begins with the # symbol are actually not
written in C but in the preprocessor language.
The output of the preprocessor is a text file which does not contain
any preprocessor statements. This file is ready to be processed by the
compiler. The linker combines the object file with library routines to
produce the final executable file.
In modular programming, the source code is divided into two or more source files. All these
source files are compiled separately thereby producing multiple object files. These object files
are combined by the linker to produce an executable file.
#include<stdio.h>
int main()
{
printf(“ \n Welcome to the world of C \n”);
// prints message
return 0;
// return a value 0 to the operating system
}
In C character means any letter from English alphabet, a digit or a special symbol used to
represent information.
These characters when combined together form tokens that acts as basic building blocks of
a C program.
The character set of C is as below:
a. English alphabet: Include both lower case (a-z) as well as upper case (A-Z).
b. Digit: Include numerical digits from 0 to 9
c. Special character: Include symbols such as ~, @, %, ^, #, &, ….etc.,
d. White space characters: These characters are used to print a blank space on the screen.
e. Escape sequence: Escape sequences ‘\’
\b Blank Space
\t Horizontal Tab
\v Vertical return
\r Carriage Return
\f Form feed
\n New Line
The void type holds no value. It is primarily used in below three cases:
To specify the return type of a function (when the function returns no value).
To specify the parameters of the function (when the function accepts no arguments from the
caller).
To create generic pointers.
Unsigned int/char keeps the sign bit free and makes the entire word available for storage of
the non-negative numbers.
Sign bit is the leftmost bit of a memory word which is used to determine the sign of the
content stored in that word. When it is 0, the. Value is positive and when it is 1, the value is
negative.
Dr H N National College of Engineering 171
How are Float and Double stored?
In computer memory, float and double values are stored in mantissa and
exponent forms where the exponent represents power of 2 (not 10).
Floating point numbers use the IEEE (Institute of Electrical and Electronics
Engineers) format to represent mantissa and exponents. According to the
IEEE formats, a floating point value in its binary form is known as a
normalized form.
Constants are used to define fixed values like mathematical constant pi.
The value of the constant is known to the compiler at the compile time.
C allows the programmer to specify the constant of integer type, float type,
char type, and string type.
A literal like 0.07 is treated as of type double by default. To make it a float literal,
we must specify it using. Suffix F or f.
Another way to designate a constant is to use the pre-processor command define. Define is
preceded with # symbol.
Rule2: No blank spaces are permitted between the # symbol and define
keyword.
Rule3: Blank space must be used between #define and constant name and
between constant name and constant value.
9.14.1 Streams:
A stream is the source of data as well as the destination of data. Streams are associated with a
physical device such as a monitor or a file stored on the secondary memory.
Here the source of data is keyboard and destination of the data is the monitor.
Out
put
Scanf is used to concert the text stream coming from the keyboard to the data values and
stores them in program variables.
9.14.3 printf()
The printf function ( stands for print formatting) is used to display information required by
the user and also prints the values of the variables.
The printf function takes data values, convert them to a text stream using formatting
specifications in the control string and passes the resulting text stream to the standard output.
Each data value to be formatted into the text stream is described using a separate conversion
specification in the control string. The specification in the control string describes the data
values types , size and specific format information.
The function accepts two parameters – control string and variable list. The control string may
also contains the text to be printed like instruction to the user, captions, identifiers or any
other text.
The control characters can also be included in the printf statement. These control characters
include \n, \t,\r, \a, etc.
Flags: Is an optional argument which specifies output justification such as nunerical sign,
trailing zeros or octal, decimal, or hexadecimal prefixes.
Flags Description
¨ - ¨ Left-justify within the given field width
¨ + ¨ Display the data with its numeric sign (either + or -)
¨ # ¨ Used to provide additional specifiers like o, x, X, O, Ox, OX, for
octal and hexadecimal values, respectively, for values different
than zero.
¨ 0 ¨ The number is left-padded with zero (0) instead of spaces.
For integer specifiers (d, I, o, u, x, X): Precision flag specifies the minimum number of digits
to be written.
For character string, precision specifies the maximum number of character to be printed.
For floating point number, the precision flag specifies the number of decimal places to be
printed.
Length Description
¨ h ¨ When the argument is a short int or unsigned short int
¨ l ¨ When the argument is a long int or unsigned long int (Used for integer
specifier)
¨ L ¨ When the argument is a long double (Used for floating point specifier)
Type Description
¨ c ¨ For single character
¨ d ¨ For integer value
¨ f ¨ For floating type numbers
¨ E, e ¨ Floating point numbers in exponent format
¨ G, g ¨ Floating point numbers in the shorter of e format
¨ o ¨ For octal numbers
¨ s ¨ For a sequence of characters
¨ U ¨ For unsigned integer values
¨ X, x ¨ For hexadecimal values
Here, the minimum field width is 10, the precision is 4, and the value to be displayed is
1234.34
The scanf function takes a text stream from the keyboard, extracts and formats data from the
stream according to a format control string and then stores the data in specified program
variables.
Syntax:
The string specifies the type and format of the data that has to be obtained from the keyboard
and stored in the memory locations pointed by arguments arg1, arg2, arg3,….., argn, i.e.., The
arguments are the actually the variable addresses where each piece of data is to be stored.
Dr H N National College of Engineering 198
Formatting Input/Output
The prototype of the control string is:
%[*][width][modifier]type
Here * is an optional argument that suppresses assignment of the input field, i.e., it indicates
that data should be read from the stream but ignored.
Width: Is an optional argument that specifies the maximum number of character to be read.
Modifier: Is an optional argument that can be h, l, or L for the data pointed by the
corresponding additional arguments.
Type: Specifies the type of the data that has to be read. It also indicates how this data is
expected to be read from the user.
Rule2: Every variable that has to be processed must have a conversion specification associated with it.
Therefore the following scanf statement will generate an error as num3 has no conversion specification
associated with it.
¨ Example: scanf(“%d %d”, &num1, &num2, &num3);
Rule5: The data entered by the user must match the character specified in the control string,
otherwise an error will be generated and scanf will stop its processing.
Example: scanf(“%d / %d”, &num1, &num2, &num3);
Here the slash in the control string is neither a white space character nor a part of conversion
specification, so the user must enter data of the form 21/46.
Rule7: Any unread data value will be considered as a part of the data input in the next call to
scanf.
Rule8: When the field width specifier is used, it should be large enough to contain the input data
size.
int num;
scanf(“%d ”, &num);
float salary;
scanf(“%f ”, &salary);
char ch;
scanf(“%c”, &ch);
char str[10];
scanf(“%s”, str);
Dr H N National College of Engineering 203
Formatting Input/Output
Example: The below code combines reading of variables of different data types in one single
statement.
int num;
float fnum;
char ch;
char str[10];
scanf(“%d %f %c %s”, &num, &fnum, &ch, str);
float salary;
scanf(“%f”, &salary);
Printf(“.2%f”,salary);
The printf function prints the floating point value.
#include<stdio.h>
int main()
{
//Declare and initiaze the variables
int num=7;
float amt=123.45;
char code= 'A';
double pi=3.1415926536;
long int population=10000000000;
char msg[]= "Hi";
Output:
Num=7
AMT=123.450000
CODE=A
PI=3.141593e+00
POPULATION=10000000000
MESSAGE=Hi
#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, area, s;
printf("\n Enter the length of the three sides of the triangle \n");
scanf("%f %f %f", &a, &b, &c);
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf(" \n Area=%f", area);
return 0;
}
Output:
Enter the length of the three sides of the triangle
12
16
20
Area=96.000000
#include<stdio.h>
#include<math.h>
int main()
{
int x1, x2, y1, y2;
float distance;
printf("\n Enter the x and y coordinates of first point: ");
scanf("%d %d", &x1, &y1);
printf("\n Enter the x and y coordinates of second point: ");
scanf("%d %d", &x2, &y2);
distance=sqrt((pow(x2-x1),2)+pow((y2-y1),2));
printf(" \n Distance =%f", distance);
return 0;
}
Dr H N National College of Engineering 211
Write a program to calculate the distance between two points.
Output:
Distance = 2.236068
The control string specifies the type and format of the data that has to be obtained from
the keyboard and stored in the memory locations pointed by the arguments, arg1, arg2,
...,argn.
%[*][width][modifier]type
* is an optional argument that suppresses assignment of the input field. That is, it
indicates that data should be read from the stream but ignored (not stored in the
memory location).
Modifier h is used for short int or unsigned short int, l is used for long int,
unsigned long int, or double values.
Finally, L is used for long double data values. type specifies the type of data
that has to be read. It also indicates how this data is expected to be read from
the user.
The scanf function ignores any blank spaces, tabs, and newlines entered by the
user.
It is used to store values in memory locations associated with variables. For this,
the function should have the address of the variables which is denoted by an &
sign followed by the name of the variable.
int num;
scanf(" %4d ", &num); //read first four digits
flags is an optional argument, which specifies output justification like decimal point,
numerical sign, trailing zeros or octadecimal or hexadecimal prefixes
// Create variables
int myNum = 15; // Integer (whole
number)
float myFloatNum = 5.99; // Floating point
number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
However, if the number of characters is greater than the specified width, then
all the characters would be printed. precision is an optional argument which
specifies the number of digits to print after the decimal point or the number of
characters to print from a string.
// Create a string
char firstName[30];
// Ask the user to input some text
printf("Enter your first name: \n");
// Get and save the text
scanf("%s", firstName);
When the scanf function completes reading all the data values, it returns the
number of values that are successfully read. This return value can be used to
determine whether there was any error while reading the input.
Example:
scanf (“%d %f %c”, &a, &b, &c);
12 12.34 A
Dr H N National College of Engineering 223
Input/output Statements in C
It will return 1 if the user enters erroneous data like
12 ABC 12.34
This is because a string was entered while the user was expecting a floating
point value. So, the scanf function reads only first data value correctly and then
terminates as soon as it encounters a mismatch between the type of data
expected and the type of data entered.