Module 1-INTRODUCTION TO C
Module 1-INTRODUCTION TO C
The programming language C was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories to be used by the UNIX operating system.
History of C
Characteristics of C
C is a robust language whose rich set of built-in functions and operators can be used to
write complex problems.
Structure of a C Program
A C program is composed of preprocessor commands, a global declaration section and
one or more functions.
The structure of a C program can be mainly divided into six parts, each having its
purpose. It makes the program easy to read, easy to modify, easy to document, and
makes it consistent in format.
Section Description
Documentation Consists of the description of the
program, programmer's name, and
creation date. These are generally written
in the form of comments.
Link All header files are included in this
section which contains different functions
from the libraries. A copy of these header
files is inserted into your code before
compilation.
Definition Includes preprocessor directive, which
contains symbolic constants.
E.g.: #define allows us to use constants in
our code. It replaces all the constants with
its value in the code.
Global Declaration Includes declaration of global variables,
function declarations, static global
variables, and functions.
It is a variable/function which is declared
after the preprocessor directives and
before the main() function.
main() function For every C program, the execution starts
from the main () function. It is mandatory
to include a main () function in every C
program. The statements in C program
are written in a logical sequence to
perform a specific task.
Subprograms Includes all user-defined functions
(functions the user provides). They can
contain the inbuilt functions and the
function definitions declared in the
Global Declaration section. These are
called in the main() function.
All functions (including main()) are divided into two parts- the declaration section
and the statement section. The declaration section precedes the statements and is used
to describe the data that will be used in the function.
The data declared within a function are known as local declaration as that data will
be visible only within that function. The lifetime of the data will be only till the
function ends. The statement section in the function contains the code that
manipulates the data to perform a specified task.
#include<stdio.h>
void main()
{
printf(“\n Welcome to the world of C”):
}
#include <stdio.h>
This is a pre-processor command. All pre-processor commands start with hash(#) symbol.
The # include statement tells the compiler to include the standard input output library or
header files The stdio.h header file contains functions for input and output of data . The
printf() function is defined in stdio.h .
void main()
void is the return value of the main function. The program execution will begin from main().
The two curly brackets{} are used to group all the related statements of the main function.
All the statements between the braces form the function body. The function body contains a
set of instructions to perform the given task.
The printf() function is defined in stdio.h file and is used to print text on the screen. The
message to be displayed on the screen is enclosed within double quotes and put inside
brackets.
2. At times the programmer may want to change or add the subroutines and reflect those
changes in all the programs. For doing this, he will have to only change the source file for the
subroutines, recompile the source code and then recompile and re-link the program.
This tells us that including a header file will make it easier at all levels of the program. If we
need to modify anything then changes are made only in the subroutines after which all the
changes will be reflected.
The header files are added at the start of the source code so that they can be used by more
than one function of the same file.
Object Files
They are the files that are generated by the compiler as the source code file is processed.
These files generally contain the binary code of the function definitions.
The object file is used by the linker for producing an executable file for combining the
object files together. It has a '.o' extension.
Library files
Library files
Binary
Executable file
Comments in C
Comments can be used to explain code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. The compiler ignore the comments when
forming the object file.
Single-line Comments
Any text between // and the end of the line is ignored by the compiler (will not be executed).
Example
// This is a comment
printf("Hello World!");
Block Comments
Example
printf(“Hello World!”);
Keywords
Keywords are a sequence of characters that have a fixed meaning. C has a set of reserved
keywords. They are written in lower case. In all there are 32 keywords.
Identifiers
Identifiers help us to identify data and other objects in the program. Identifiers are the names
given to the variables, constants, functions and the user-defined data. They may consist of an
alphabet, digit or an underscore.Identifiers are written by keeping in mind a set of rules.
1. Special characters or punctuation marks like #, $, ^,?, . etc cannot be included. But an '_'
underscore can be used.
2. Two successive underscores cannot be used at the same time.
3. Any keywords cannot be used as an identifier.
4. Identifiers are case-sensitive.
5. The identifier name can begin with an alphabet or an underscore.
6. An identifier can be of any reasonable length, but it should not contain more than 31
characters.
7. The identifier name is case sensitive. For example, „FIRST‟ is different from „first‟.
Some valid identifier name are as follows:
Roll_num, marks, DeptCode, EMP_NO
In the above table we have a data-type called 'void' which has no value but is used in the
following cases:
For specifying the return type of the function when the function returns no value.
For specifying the parameters of the function when no arguments are accepted by the
function from the caller.
For creating generic pointers.
The unsigned and signed char is used for ensuring the portability of the programs which store
the non-character data as char.
Variables
A meaningful name given to a data storage location in the computer memory is known as
a Variable.
When a variable is used it actually refers to an address of the memory where the data is
stored.
A variable name can comprise of letters, digits and underscore characters.
The first character has to be an alphabet.
There should be no commas or blank spaces between the variable names.
Variable declaration
All the variables that are used in the program need to be declared.
Syntax:
data-type variable-name;
int emp_code;
float salary;
Example:
float salary, bonus;
Constants
The identifiers whose value do not/ cannot change are known as Constants.
Variables can change their values but constants will never change their value.
Types of constants
1. Integer constants
0 03 056
Example: Hexadecimal integer begins with 0x or 0X followed by the combination of the
digits from 0 through 9 and a through f.
0x 0x4 0xcdf
Certain suffixes are given to the constants.
The suffixes are given for the following types:
Long – I or L
Example:
6000U unsigned (decimal)
These type of constants contain a decimal point or an exponent. They can be either negative
or positive. Commas or blanks are not allowed within a real constant.
Unlike the integer constants they too have a suffix for the following type:
Float– f or F
Long double – I or L
3. Character constant
The characters are stored by using the machines character set using the ASCII code.
4. String constant
Declaring constants.
A constant can be declared by using the const keyword and assigning it a value.
The const keyword tells us that the value of pi can never be changed.
Other way of declaring the constant is by using the pre-processor command define.
#define can be placed anywhere in the program
#define pi 3.14159
INPUT/OUTPUT STATEMENTS IN C
i) printf()
Syntax:
printf(“control string”, arg1, arg2, …..);
In the above syntax, 'control string' will contain the information that is formatted. They are
the general characters which will be displayed as they are.
arg1, arg2 are the output data items.
%[flags][width][.precision][length specifier]
1 -
Left-justify within the given field width; Right justification
is the default
2 +
Forces to precede the result with a plus or minus sign (+ or
-) even for positive numbers. By default, only negative
numbers are preceded with a -ve sign.
3 (space)
If no sign is going to be written, a blank space is inserted
before the value.
4 #
Used with o, x or X specifiers the value is preceded with 0,
0x or 0X respectively for values different than zero. Used
with e, E and f, it forces the written output to contain a
decimal point even if no digits would follow. By default, if
no digits follow, no decimal point is written. Used with g
or G the result is the same as with e or E but trailing zeros
are not removed.
5 0
Left-pads the number with zeroes (0) instead of spaces,
where padding is specified (see width sub-specifier).
Width specifies the minimum number of characters to print after being padded with zeros or
blank spaces , i.e. it specifies the minimum number of positions in the output.
1 .number
For integer specifiers (d, i, o, u, x, X) − precision specifies the
minimum number of digits to be written. If the value to be written is
shorter than this number, the result is padded with leading zeros. The
value is not truncated even if the result is longer. A precision of 0
means that no character is written for the value 0. For e, E and f
specifiers − this is the number of digits to be printed after the decimal
point. For g and G specifiers − This is the maximum number of
significant digits to be printed. For s − this is the maximum number of
characters to be printed. By default all characters are printed until the
ending null character is encountered. For c type − it has no effect.
When no precision is specified, the default is 1. If the period is
specified without an explicit value for precision, 0 is assumed.
2 .*
The precision is not specified in the format string, but as an additional
integer value argument preceding the argument that has to be
formatted.
Length
Sr.No. Length & Description
1 h
The argument is interpreted as a short int or unsigned short int (only
applies to integer specifiers: i, d, o, u, x and X).
2 l
The argument is interpreted as a long int or unsigned long int for integer
specifiers (i, d, o, u, x and X), and as a wide character or wide character
string for specifiers c and s.
3 L
The argument is interpreted as a long double (only applies to floating point
specifiers: e, E, f, g and G).
Specifier field
%c Signed character
%f Signed float
%e A floating-point number
A string or sequence of
%s
character
%lf Double
%x Hexadecimal integer
ii) scanf()
Syntax:
scanf (“control string”, &arg1, &arg2, …..);
Format string consists of the conversion specifier. 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,etc.
Arguments can be variables or array name and represent the address of the variable.
Each variable must be preceded by an ampersand (&). Array names should never begin
with an ampersand.
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade);
scanf works totally opposite to printf. The input is read, interpret using the conversion
specifier and stored it in the given variable.
The conversion specifier for scanf is the same as printf.
Rules to be followed while using scanf():
scanf reads the characters from the input as long as the maximum number of
characters has been processed , a whitespace character is encountered or an error is
encountered. The order of the characters that are entered are not important.
It requires an enter key in order to accept an input.
Every variable must have a conversion specification associated with it.
There must be a variable address for each conversion specification.
A fatal error will be generated if the format string ended with a white space character.
The data entered by the user must match the character specified in the control string.
Input data values must be separated by spaces.
Any unread data value will be considered as a part of the data input in the next call to
scanf.
When the field width specifier is used, it should be large enough to contain the input
data size.