Module 1
Module 1
Introduction to C: Introduction to computers, input and output devices, designing efficient programs.
Algorithm
Def 1: Step-by-step procedure to solve a problem using a computer is called an algorithm.
Def 2: In Computer Science, A finite sequence of unambiguous steps to solve a problem is called an
algorithm.
Example 1: Algorithm for adding any two numbers.
Step 1: Start
Step 2: Input the two numbers to be added and assign them to variables X & Y respectively.
Step 3: Compute value Z such that Z = X+ Y
Step 4: Display the value of Z.
Step 5: Stop
Example 2: Algorithm for checking a given number is +ve or –ve (Assume 0 is positive)
Step 1: Start
Step 2: Input the number and assign it to variable X.
Step 3: Check if X is less than 0, then display “ The given number is –ve”. Otherwise display
“ The given number is +ve”
Step 4: Stop
Flowchart
C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories to be used by UNIX
operating system.
It was named ‘C’ because many of its features were derived from an language called ‘B’.
C was initially developed for writing system software
Today, C has become a popular programming language and various software programs are
written using this language.
Many other commonly used programming languages such as C++ and Java are also based on C
Background
C is derived from ALGOL. It was introduced in 1960s led the way for the development of
structured programming concept.
In 1967, Martin Richards developed a language called BCPL (Basic Combine Programming
Language). It is basically a type-less language (no concept of data-types).
In 1970, Ken-Thompson developed a language called B. It was used to develop the first version
of UNIX.
C was developed by Dennis Ritchie in 1972 that took the concept from ALGOL, BCPL and B.
In addition to that C also supports the concepts of data types.
C was documented and popularized in the book The C programming language by Brian W.
Kernighan and Dennis Ritchie in 1978. This book was popular and the language came to known
as ‘K & RC’.
Characteristics of C
1. A high level programming language enables the programmer to concentrate on the problem
and not worry about the machine code on which the program would be run.
2. Small size. C has only 32 keywords. This makes it relatively easy to learn.
3. Makes extensive use of function calls.
4. C is well suited for structured programming. In this programming approach, C enables the user
to think of problems in terms of functions/modules where the collection of all the modules
makes up a complete program.
5. It supports loose typing (as a character can be treated as an integer and vice versa)
6. Stable language. ANSI C was created in 1983 and since then it has not been revised.
7. Quick language
8. Facilitates low level (bitwise) programming.
9. Supports pointers to refer computer memory, array, structures and functions.
10. C is a core language. Other programming languages are based on C.
11. C is a portable language. i.e., a C program written for one computer can be run on another
computer with little or no modification.
12. C is an extensible language as it enables the user to add his own functions to the C library.
Uses of C
C language is primarily used for system programming. The portability, efficiency, the ability to
access specific hardware addresses and low runtime demand on system resources makes it a
good choice for implementing operating systems and embedded system applications.
C has been so widely accepted by professionals that compilers, libraries, and interpreters of
other programming languages are often implemented in C.
3. STRUCTURE OF C PROGRAM
A C program is composed of preprocessor commands, a global declaration and one or more functions.
Pre-processor directives
It contains special instructions that indicate how to prepare the program for compilation. One of the
most important and commonly used preprocessor commands is include which tells the compiler that to
execute the program, some information is needed from the specified header file.
The global variables that can be used anywhere in the program are declared in the global declaration
section. This section also declares the user defined functions.
A C program contains one or more function, where a function is defined as a group of C statements
that are executed together. The statements in a C program are written in a logical sequence to perform
a specific task.
The main () function is the most important function and is a part of every C program. The execution
of a C program begins at this function.
All functions are divided into two parts – the declaration section and statement section.
The declaration part declares all the variables that are used in the executable part. Data
declared within a function 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
specified task.
These two parts must be written in between the opening and closing braces { }. Each statement in the
declaration and statement part must end with a semicolon (;). The execution of program starts at
opening braces and ends at closing braces. All the statement between the braces forms the function
body. That contains a set of instructions to perform the given task.
int is the return value of the main function. After all the statements in the program have been written,
the last statement of the program will return an integer value to the operating system.
The printf function is defined in the stdio.h file and is used to print text on the screen. The message
that has to be displayed on the screen is enclosed within double quotes and put inside brackets.
The ‘\n’ is an escape sequence and represents a newline character. It is used to print the message on a
new line on the screen.
return 0;
This is a return command that is used to return the value 0 to the operating system to give an
indication that there were no errors during the execution of the program.
Sometimes, it is necessary to use characters which cannot be typed or have special meaning in
C programming. For example: newline (enter), tab etc. In order to use these characters, escape
sequences are used.
For example: \n is used for newlines. The backslash ( \ )causes "escape" (or deviation) from the
normal way the characters are interpreted by the compiler. So instead of the character ‘n’, the meaning
of \n is a newline.
1. Source File
It contains the source code of the program. The file extension of C source code file is “.c”. This file
contains C source code that defines the main function and maybe other functions. The main() is the
starting point of execution when you successfully compile and run the program.
2. Header File
When working with large projects, it is often desirable to make sub-routines and store them in a
different file known as header file.
The advantage of header files can be realized when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those changes be
reflected in all other programs.
3. Object Files
Object files are generated by the compiler as a result of processing the source code file. Object files
contain compact binary code of the function definitions. Linker uses this object file to produce an
executable file (.exe file) by combining the of object files together. Object files have a “.o” extension,
although some operating systems including Windows and MS-DOS have a “.obj” extension for the
object file.
The binary executable file is generated by the linker. The linker links the various object files to
produce a binary file that can be directly executed. On Windows operating system, the executable files
have “.exe” extension.
C is compiled language. So once the C program is written, you must run it through a C compiler.
The source file (human-readable) is first processed with special program called a Compiler
that translate the source code into an object code. The object code contains the machine
instructions for the CPU. However, even the object file is not an executable file.
Therefore, in the next step the object file is processed with another special program called a
linker. That translates the object file into executable file (machine-readable). The output of
the linker is an executable or runnable file.
6. USING COMMENTS
It helps the reader to understand the code clearly. Comments are just a way of explaining what a
program does. The compiler ignores the comments when forming the object file. This means that the
comments are non-executable statements.
C supports two types of commenting.
// is used to comment a single statement. This is known as a line comment. A line comment
can be placed anywhere on the line and it does not require to be specifically ended as the end
of the line automatically ends the line.
/* is used to comment multiple statements. A /* is ended with */ and all statements that lie
within these characters are commented.
7. KEYWORDS
Keywords are the reserved words in C whose meanings are fixed by the language.
Keywords are case sensitive. i.e. while and While are not the same.
In C, All keywords are of lowercase.
Keywords cannot be used as variable names. ( E.g. int char = 10; is not allowed in C since
char is keyword)
There are 32 keyword in ANSI C:
9. DATA TYPES
Every data used in a C program must have a type associated with it. That is referred to as data type.
E.g: 25 is Integer data type. 2.53 is floating point type etc.
Since data is normally stored in variables, we specify the data type of a variable when we declare the
variable name (i.e creating a variable). Hence language has defined a set of DATA TYPES that can be
used to declare variables.
The data type categories supported by ANSI C are:
1. Primary(Fundamental) data types
2. Derived Data types
22POP12 - Principle of Programming Using C Page 12
3. User-defined data types
Primary Data Types
The 5 Primary Data Types are following
(The difference between signed and unsigned numeric variable is that signed variables can be either
negative or positive but unsigned variable can be only positive.)
Declaring Variable
To declare a variable specify data type of the variable followed by its name. The data type indicates
the kind of data that the variable will store. Variable names should always be meaningful and must
reflect the purpose of their usage in the program.
Variable declaration always ends with a semicolon.
data_type variable_name;
Example,
int emp_num;
float salary;
char grade;
double balance_amount;
11. COSTANTS
Constants are fixed values that do not change during execution of the program.
E.g: 5, 100, “hello”, 14.52, ‘A’, ‘b’
Constants are used to define fixed values like PI or the charge on an electron so that their value does
not get changed in the program even by mistake.
1. Integer Constant
An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
Decimal constant (base 10): It consist of a set of digits, 0 through 9, preceded by an optional –
or + sign.
Eg: 0, -9, 22 etc
Octal constant (base 8): An Integer constant preceded by a zero (0) is an octal number. It
consists of a set of digits, 0 through 7.
Eg: 021, 077, 033 etc.
Hexadecimal constant (base 16): It is preceded with 0x or oX. It contains digits from 0-9 and
alphabets A through F,
Eg: 0x7f, 0x2a, 0x521 etc
Integers are inadequate to represent quantities such as distance, heights, temperature, price and so on.
These quantities are represented by a number containing fractional parts like 12.32, 7.34 etc. Such
numbers are called floating point constants.
Eg:
0.0000234 // Fractional form
-0.22E-5 // Exponent form: mantissa E exponent
Note: E-5 is same as 10-5
3. Character Constant
A character constant consists of a single character enclosed in single quotes.
For example: 'a', 'l', 'm', 'F', ‘@’
4. String Constant
A string is sequence of characters enclosed in double quotes.
For example:
"good" //string constant
"" //null string constant
" " //string constant of six white spaces
"x" //string constant having a single character.
"Earth is round\n" //prints string with newline
Declaring Constants
To declare a constant, precede the normal variable declaration with const keyword and assign it a
value.
For Eg:
const float pi = 3.14;
The const keyword specifies that the value of pi cannot change.
Another way to designate a constant is to use the pre-processor command define.
#define PI 3.14159
Rules that need to be applied to a #define statement
Rule 1: Constant names are usually written in capital letter
Rule 2: No blank space are permitted in between # and define.
Formatted I/O
1. Formatted Output - THE PRINTF() FUNCTION
The printf function is used to display information required to the user and also prints the values of the
variables.
Its syntax can be given as
printf(“Control string", arg1,arg2,arg3,…,argn);
The parameter control string is a C string that contains the text that has to be written on to the standard
output device.
E.g.:
int a = 10,b=5,sum;
sum = a+b;
printf("The sum of %d and %d is %d. \n",a,b,sum);
Output:
The sum of 10 and 5 is 15.
Outputting Integers:
General format specification: %wd
w==> Specify minimum field width for the output.
That many (w) spaces is reserved on screen for the data displayed
"%ld" ==> For long int
"%hd" ==> For short int
Formatted Input refers to input data expected/inputted in predefined format in the program.
E.g.: Entered data: 15.75 123 John
This data is read to corresponding type variables. Function used for formatted Input: scanf
General format:
scanf("control string",arg1,arg2,…,argn);
Control string(format string): specifies order in which data to be entered and the type of the
data expected.
arg1,arg2,…,argn : variables where data is stored.
E.g: scanf("%d %c %f", &num,&ch,&fno);