Module 1 - SBL ATME
Module 1 - SBL ATME
Module-1
Number of Hours: 6
Module 1
INTRODUCTION TO COMPUTERS:
HISTORY OF C
• C is a general purpose, procedural, structured computer programming language
developed by Dennis Ritchie in the year 1972 at AT&T Bell Labs.
• C language was developed on UNIX and was invented to write UNIX system
software.
• C is a successor of B language.
• There are different C standards: K&R C std, ANSI C, ISO C. Characteristics of C:
• C is easy to learn.
• C is a general purpose language.
• C is a structured and procedural language.
• It is portable.
• It can extend itself
• Databases
Input devices are needed to interact with the OS to perform tasks. Ex: Keyboard, Mouse, Joystick,
Stylus, Scanner etc.
• Keyboard: Every computer supports a keyboard – either a physical or touchscreen. The keyboard
has QWERTY layout and contains large number of symbols. Each letter, numeral or symbol is
known as a character, which represents smallest piece of information. Each character has unique
values called the ASCII (American Standard Code for Information Interchange) value.
• Pointing Devices: GUI (Graphical User Interfaces) like windows need a pointing device to
control the movement of cursor on the screen. This is implemented as mouse in desktop and
touchpad in laptop. The earliest form has a rotating ball and two buttons. The left button is used for
selecting (by clicking once) and execute (by clicking twice). The right button is used to check and
change attributes. The optical mouse uses infrared laser/LED, the wireless mouse uses radio
frequency technology.
• Scanner: A scanner is a device that creates a digital image of a document by optically scanning
it. The flatbed scanner doesn‟t exceed more than A4 size. It is operated with by using special
software. The document to be scanned is placed on a glass plate covered by lid. Modern scanners
have
• OCR (Optical Character Recognition) facility which extracts text as a stream of characters i.e.
converting image file to text file and MICR (Magnetic Ink Character Recognition) reads the
codes using hand held barcode readers.
OUTPUT DEVICES
The information produced can be heard or seen with the help of output devices. Some of the output
devices are monitor, speaker, printer, plotter etc.
Monitor: The monitor is an integral part of computer which displays both text and graphics. The
performance is measured in terms of image quality, resolution, energy consumption.
CRT (Cathode Ray Tube) Monitors: The CRT monitors have a rarefied tube containing three
electron guns. The guns emit electrons create images. They usually have resolution of 640*840
pixels. They are large, heavy, energy efficient and produces lot of heat.
LCD (Liquid Crystal Display) Monitors: The image is formed by applying voltage on crystals.
The backlight is provided by fluorescent light. They consume less power, generate less heat and
have increased life span.
Impact Printers: It produces the hardcopy of output. The impact printers are old, noisy. But, still
dot-matrix printer is in usage.
Dot-Matrix Printer: The print head of the dot-matrix printer has either 9 or 24 pins. When the
pins fire against the ribbon, an impression is created on the paper. The speed is 300 cps and doesn‟t
produce high quality output. It can produce multiple copies.
Daisy-wheel Printer: It employs a wheel with separate characters distributed along its outer edge.
The wheels can be changed to obtain different set of fonts.
Line Printer: For heavy printing, the line printer is used. It uses a print chain containing the
characters. Hammers strike the paper to print and it rotates at the speed of 1200 lpm. It is also noisy
and is of low-quality.
Non-Impact Printers: They are fast, quiet and of high resolution. The most commonly used non-
impact printers are laser and ink-jet printers. The thermal printer is not discussed here because it
uses heat to print on high-sensitive paper.
Laser Printer: It works like a photocopier and uses toner i.e. black magnetic powder. The image is
created in the form of dots and passed from drums on to the paper. It has built-in RAM which acts
as buffer and RAM to store fonts. The resolution varies from 300 dpi to 1200 dpi and the speed is
about 20 ppm.
Ink-jet Printer: These are affordable printers. It sprays tiny drops of ink at high pressure as it
moves along the paper. The separate cartridges are available for different colors. The resolution is
about 300 dpi, can print 1 to 6 pages/min.
Plotters: The plotter can make drawings. It uses one or more automated pens. The commands are
taken from special file called vector graphic files. Depending on type of plotter either paper or pen
moves. It can handle large paper sizes and it is used for creative drawings like buildings and
machines. They are slow and expensive.
INTRODUCTION TO C:
C Language was designed and developed by Dennis Ritchie at BELL Laboratories in 1972. C
programming language is derived from earlier languages B, BCPL (Basic Combined
Programming Language) and CPL (Combined Programming Language).
ALGORITHM
An algorithm is a step by step procedure to solve a given problem. The good algorithm
should contain the following
• Finite number of steps.
• Each step should be clear and meaningful.
• The input and output should be defined precisely.
• An algorithm should not have computer code. ( C program)
Example 4: Write an algorithm to find sum and average of given three numbers.
Step 1: Start
Step 2: Declare variables a, b, c, sum and avg. Step 3:
Read values of a, b and c.
Step 4: Find the sum of a, b, c.
sum= a+b+c
Step 5: Find the average of a, b, c.
avg= sum/3;
Step 6: Display sum, avg. Step
7: Stop.
STRUCTURE OF C PROGRAM:
Documentation Section
Link Section
Definition Section
Global Declaration Section
main () function section
{
Declaration part;
Executable part;
}
Subprogram section
Function 1
Function 2
.
.
.
.
Function n
(i) Documentation Section
Documentation section consists of set of comment lines. This comment lines
indicate name of the program, author and other details.
(ii) Link Section
The Like section provides instruction to the compiler to link functions from the
system library such as using the #include directive.
(iii) Definition Section
The definition section defines all symbolic constants such as using the #define
directive.
(iv) Global declaration section
There are some variables that are used in more than one function such variables are
called global variables and are declared in the global declaration section. This section also
declares all the user-defined functions.
(v) Main() function Section
Every C program must have one main function section. This section contains two parts:
a) Declaration Part:
The declaration part declares all the variables used in the executable part.
b) Executable part:
There is at least one statement in the executable part. These two parts must
appear between the opening and closing braces. The program execution
begins at the opening brace and ends at the closing brace. The closing brace of
the main function is the logical end of the program. All the statements in the
declaration and executable part end with a semicolon.
(vi) Subprogram section:
If the program is a multi function program then the subprogram section contains
all the user defined functions that are called in the main() function. User defined
functions are generally placed immediately after the main () function, although they may
appear in any order.
Example:
//Documentation section
/* Program Name: Sample
Program Author:aaa
*/
//Link section #include <stdio.h>
// Definition Section
#define MAX_ARRAY_LENGTH 20
// Global declaration section
int max_input_length=15;
// Declaring user defined function
float addNumbers(float a, float b);
//Main() function section
int main()
{
int localvariable=50; //Declaration part
clrscr();
//Executable part
printf (“Max array length is %d\n”, MAX_ARRAY_LENGTH);
printf (“Max input length is %d\n”, max_input_length);
printf(Sum of 5.5 and 8.5=%f\n”, addNumbers(5.5,8.5));
return 0;
}
//defining an user defined function which has been declared.
float addNumbers(float a, float b)
{
return (a+b);
}
Files in a C Program
a ‘.o’ extension, although some operating systems including Windows and MS-DOS have a
‘.obj’ extension for the object file.
Binary Executable File:
The binary executable file is generated by the linker. The linker links thevarious object files to
produce a binary file that can be directly executed. On Windows operating system, the
executable files have ‘.exe’ extension.
COMPILERS:
A compiler is a special program that translates a programming language's source code into
machine code, bytecode or another programming language.
COMPILING AND EXECUTING C PROGRAMS:
Let’s look at how to save the source code in a file, and how to compile and run it.
Following are the simple steps:
1. Open a text editor and add the above-mentioned code.
2. Save the file as hello.c
3. Open a command prompt and go to the directory where you saved the file. 4. Type gcc hello.c
and press enter to compile your code.
5. If there are no errors in your code, the command prompt will take you to the next line and
would generate a.out executable file.
6. Now, type a.out to execute your program.
7. You will be able to see "Hello World" printed on the screen
$ gcc hello.c
$ ./a.out
Hello, World!
Make sure that gcc compiler is in your path and that you are running it in the directory
containing source file hello.c.
VARIABLES:
Declaration of variables
There are two methods of declaration of variables
Primary type declaration
User defined type declaration
Variables
Variables are named memory locations that have type such as integer or character to store data
values, these data values will change during program execution. Variables are also called identifier,
because it is used to identify value.
Rules for naming variable
1) The first character must be an alphabetic character (lower-case or capital letters) or an underscore
„_‟.
2) All characters must be alphabetic characters, digits, or underscores.
3) The first 31 characters are significant; however length should not be more than 8 characters.
4) Cannot duplicate a reserved word. A reserved word is one which has special meaning to C.
5) Uppercase and lowercase are significant.
6) White space is not allowed
Primary Variable declaration: All variables must be declared before use, although certain
declarations can be made implicitly by content. A declaration specifies a type, and contains a list of
one or more variables of that type.
Syntax of variable declaration data-type v1,v2,---vn ;
Where data-type can be any basic datatype, and v1, v2 .. vn are the names of the variable. Variables
are separated by commas. A declaration ends with semicolon(;).
example
int lower, upper, step;
Variables can be distributed among declarations in any fashion; the lists above could well be written
as
int lower;
int upper;
int step;
The latter form takes more space, but is convenient for adding a comment to each declaration for
subsequent modifications.
Variable Initialization: Once you declared variable, the next step is to assign value to variable. The
process of assigning values to a variable is called initialization of variable. You can assign values to a
variable by using (= ) assignment operator.
Syntax:
Variable _name=value;
Following examples illustrates the same: int a=25, x=55,c=77;
float p=25.5, q=30.55; char ch=‟A‟;
User defined type declaration
C supports a feature known as “type definition” that allows user to define an identifier that
would represent an existing data type. The user-defined data type identifier can later be used to
declare variables.
Syntax
Where
typedef is a keyword
type refers to an existing data type
identifier refers to new name given to the datatype
Examples
1. typedef int units;
2. typedef float marks;
units symbolizes int and marks symbolizes float. i.e., units batch1, batch2; and marks n1, n2;
Another user-defined data type is enumerated data type provided by ANSI standard. It is defined as
follows (syntax).
The “identifier” is a user-defined enumerated data type which can be used to declare variables that
can have one of these values enclosed with in braces (known as enumeration constants). Example
enum day {Monday, Tuesday, ..........Sunday};
enum day week_st, week_end;
CONSTANTS:
Constants are values that will not change during execution of the program.
Constants are classified as
(a) Integer Constants
(b) Floating point constants
(c) Character constants
(d) String constants
(e) Enumeration constants
Example 2: 5.5 e3 [i.e: 5.5 x 103], 6.6 e-4 [i.e: 6.6 x 10-4]
Example:
enum days{sun, mon, tue, wed, thur, fri, sat};
Where
• enum is keyword.
• Days is variable name
• sun, mon, tue, wed, thur, fri, sat are enumeration constants having
value 0,1,2,3,4,5,6 respectively by default.
INPUT/OUTPUT STATEMENTS IN C:
• Reading, processing and writing of data are the three essential functions of a
computer program.
• Most programs take some data as input and display the processed data.
• We have two methods of providing data to the program variables.
• One method is to assign values to variables through the assignment statements
like x=5, a=0 and so on. Another method is to use the input function scanf, which can
read data from a keyboard.
• We have used both the methods in programs. For outputting results, we have used
extensively the function printf, which sends results out to a terminal.
Input – Output functions:-
The program takes some I/P- data, process it and gives the O/P.
We have two methods for providing data to the program
i) Assigning the data to the variables in a program.
ii) By using I/P-O/P statements.
C language has 2 types of I/O statements; all these operations are carried out through function
calls.
1. Unformatted I/O statements
2. Formatted I/O statements
Unformatted I/O Functions
1. getchar( ):- It reads single character from standard input device. This function don‘t
require any arguments.
Syntax:- char variable_name = getchar( );
Ex:- char x;
x = getchar( );
2. putchar ( ):- This function is used to display one character at a time on the standard
output device.
Syntax:- putchar(char_variable);
Ex:- char x;
putchar(x);
program:
main( )
{
char ch;
printf(“enter a character);
ch = getchar( );
printf(“entered chaacter is”); putchar(ch);
}
Output: enter a char a
entered char is a
3. getc() :- This function is used to accept single character from the file.
Syntax: char variable_name = getc();
Ex:- char c;
c = getc();
4. putc():- This function is used to display single character.
c = getche();
program:
main()
{
char ch, c;
printf(“enter character”);
ch = getch();
printf(“%c”, ch);
printf(“enter character”);
c = getche();
printf(“%c”,c);
}
Output :- enter character a
enter character b
Character test functions:-
Function Test
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character
isdigit(c) Is c a digit?
islower(c) Is c alower case letter?
isprint(c) Is c a character?
ispunct(c) Is c a punctuation mark?
isspace(c) Is c a white space character?
isupper(c) Is c an upper case letter?
tolower(c) Convert ch to lower case
toupper(c) Convert ch to upper case
program:
main()
{
char a;
printf(“enter char”);
a = getchar();
if (isupper(a))
{
x= tolower(a);
putchar(x);
}
else
putchar(toupper(a));
}
Output:- enter char A
a
Formatted I/O Functions:
• Formatted I/O refers to input and output that has been arranged in a particular format.
• Formatted I/P functions: scanf( ) , fscanf()
• Formatted O/P functions: printf() , fprintf()
scanf( ) :-
scanf() function is used to read information from the standard I/P device.
Syntax:- scanf(“controlstring”, &variable_name);
• Control string (also known as format string) represents the type of data that the user is
going to accept and gives the address of variable. (char-%c , int-%d , float - %f , double-%lf).
• Control string and variables are separated by commas.
• Control string and the variables going to I/P should match with each other.
Ex:- int n;
scanf(“%d”,&n);
Inputting Integer Numbers:
• The field specification for reading an integer number is: %w d
• The percentage sign(%) indicates that a conversion specification follows.
• w is an integer number that specifies the field width of the number to be read and d
known as data type character indicates that the number to be read is in integer mode.
Ex:- scanf(“%2d %5”,&a&b);
The following data are entered at the console: 50 31426
Here the value 50 is assigned to a and 31426 to b
Inputting Real Numbers:
• The field width of real numbers is not to be specified unlike integers.
• Therefore scanf reads real numbers using the simple specification %f.
Ex: scanf(“%f %f”,&x,&y);
Suppose the following data are entered as input: 23.45 34.5
The value 23.45 is assigned to x and 34.5 is assigned to y.
Inputting character strings:
• The field specification for reading character strings is %ws or %wc
• %c may be used to read a single character.
Ex: scanf(“%s”,name1);
Suppose the following data is entered as input: Griet
Griet is assigned to name1.
Formatted Output:
printf( ):
• This function is used to output any combination of data.
• The outputs are produced in such a way that they are understandable and are in an easy to
use form.
• It is necessary for the programmer to give clarity of the output produced by his program.
Syntax:- printf(“control string”, var1,var2……);
Control string consists of 3 types of items
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the O/P format for display of each item.
3. Escape sequence chars such as \n , \t and \b…..
The control string indicates how many arguments follow and what their types are.
The var1, var2 etc.. are variables whose values are formatted and printed according to the
specifications of the control string.
The arguments should match in number, order and type with the format specifications.