C Unit1
C Unit1
UNIT – I
OVERVIEW OF C
C is a structured, high-level machine independent language. It allows software
developers to develop programs without worrying about the hardware platforms
where they will be implemented.
History of C
● ALGOL:
The root of all modern language, introduced in 1960s. It was the first computer
language to use the block structure.It gave the concept of structured
programming to computer science community.
● In 1967, Martin Richards developed a language called BCPL (Basic Combin
Programming Language) for writing system software.
● In 1970, Ken Thompson created a language using the features of BCPL and
named it as ‘B’.
● In 1972, C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell
Laboratories.
● In 1978, Dennis Ritchie and Brian Kernighan published the first edition
book, “The C Programming Language” and commonly known as K&R C
● 1983 American National Standard Institute (ANSI) appointed a committee to
define a standard for C.
● In Dec 1989, the committee approved the version of C which is known as ANSI
C.
● In 1990, the version of C was then approved by the International Standard
Organization (ISO) and referred it as C89.
● In 1999, C99 standard – Next revision was published that introduced new
features like advanced data types and other changes.
Importance of C (Features of C)
● It is a robust language whose rich set of built-in functions and operators can be
used to write any complex program.
● Program written in C are efficient due to several variety of data types and
powerful operators.
● The C compiler combines the capabilities of an assembly language with the
feature of high level language. Therefore it is well suited for writing both system
software and business package.
● There are only 32 keywords; several standard functions are available which can
be used for developing program.
● C is highly portable language; this means that C programs written for one
computer system can be run on another system, with little or no modification.
2
3
1. Documentation section :
The documentation section consists of a set of comment lines giving the name
of the program, the author and other details, which the
programmer would like to use later.
The comments are non executable statements which help the programmers and other
users in understanding various functions and operations of the program. The single
line comments begin with // and multi-line comments enclosed between /* and */
2. Link section :
The link section provides instructions to the compiler to link functions from the
system library.
3. Definition section :
The definition section defines all symbolic constants.
4. Global declaration section :
4
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 that is outside of all the functions.
5
Declaration part :The declaration part declares all the variables used in the executable
part.
Executable part :There is at least one statement in the executable part. It contains a
set of instructions to perform the given task.
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 statements in the
declaration and executable part end with a semicolon.
6. Subprogram section :
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.
NOTE:
● All section, except the main () function and linker section may be absent when
they are not required.
A Sample C Program
Example-1:
#include<stdio.h>
void main()
{
/* -------- Printing Begins -------- */
printf("Hello, Students, This is Our First C Program");
/* -------- Printing Ends -------- */
}
In the above program, main() is a special function. The execution of the program
begins at this line. The empty pair of parenthesis immediately following main
indicates that the function main has no arguments (or parameters). The opening
brace “{“in the second line marks the beginning of the function main and the closing
brace “}” in the last line indicates the end of the function. All the statements
between these two braces form the function body. The function body contains a set
of instructions to perform the given task.
6
In the above example, the function body contains three statements, out of which only
the printf line is an executable statement. The lines beginning with /* and ending
with */ are known as “comments”. Comment lines are not executable statements and
are ignored by the compiler. Comment lines help the programmers and other users in
understanding various functions and operations of the program. The fourth line in the
above program is a printf line. Printf is a pre-defined standard ‘C’ function used for
printing the output on the screen. The output of the above program will be
Note: Every program must have one main function. If a program contains more than
one main function, the computer gives error message.
Example-2:
/* Program to add two numbers */
#include<stdio.h>
void main()
{
int number;
float amount;
float total;
number = 100;
amount = 30.75;
total = number + amount;
printf("%d \n", number);
printf("%f \n", amount);
printf("%f \n", total);
}
Output: 100
30.75
130.75
The first line of the program is a comment line. number, amount, total are variable
names, int and float are the keywords which represent the data type of the variable.
Since we have declared that int number, the variable number stores integer type of
data and since we have declared that float amount, the variable amount stores
floating point type of data. In C, all variables should be declared to tell the compiler
what is the name of the variable and what is the type of data they hold. The variables
must be declared before they are used.
The statements number=100; amount=30.75; are called assignment statements. The
next statement is an output statement that prints the value of number on the screen.
The statementprintf("%d \n", number); contains two arguments. The first argument
“%d” tells the compiler that the value to be printed is an integer. In the next printf
statement, the argument “%f” tells the compiler that the value of the second
argument total is a floating point number.
7
8
Character Set
The characters that can be used to form words, numbers and expressions depend
upon the computer on which the program is run.
The characters in C are grouped into the following categories.
1. Letters: Uppercase A..Z and Lowercase a…z.
2. Digits: All decimal digits 0…9.
3. Special Characters: ‘, . ; : ? “ ! | / \ ~ _ $ % & ^ * + - <> () {} [] #
4. White Spaces: Blank space, Horizontal tabs, carriage return, new line, form feed.
[Note: Compiler ignores white spaces unless they are part of a string constant. White
spaces may be use to separate words, but are prohibited between the characters of
keywords and identifiers. ]
C Tokens
The smallest individual unit in a C program is called C tokens. There are 6 types of
tokens in C.
• Keywords
• Identifiers
• Constants
• Strings
• Special Symbols
• Operators
Keywords
● Keywords have fixed meanings and these meanings cannot be
changed.
● Keywords are building blocks for program
statements.
● The keywords are also known as reserved words.
● All keywords must be written in lowercase.
Identifiers:
Identifiers are used to the names of variables, functions and arrays. They are
user-defined names and consist of a sequence of letters and digits, with a
letter as first character. Both uppercase and lowercase are permitted.The
underscore character is also allowed as a C identifier, usually as a link
between two words in long identifiers
• Rules for Identifiers
1. First Character must be an alphabet (or underscore).
2. Must consists of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. cannot use a keyword.
5. must not contain white space.
Constants:
Constants in C refer to fixed values that do not change during the execution
of a program. Constants can be divided as below.
12
b. Real Constants: Real constants are numbers with fractional part. They are
also called as floating point constants.
A real number can be represented in 2 forms
Decimal notation :
Example: 0.00983, 435.88, -36.33
Exponential notation:
Example: 215.65 = 2.1565 X 102 = 2.1565e2→ This is called the
exponential notation. The general form of exponential notation is
Mantissa e Exponent
Variables
A variable is the symbolic name given to a location in the memory of the
computer where different values are stored. The variable names may consist of
letters, digits and underscore with the following conditions:
Data types
C supports three main categories of data types.
1. Primary (fundamental) data types.
2. User defined data types.
3. Derived data types.
Declaration of Variables
15
Where type refers to an existing data type and “identifier” refers to new name given
to the data type.
Example: typedef int marks;
marks C, FIT, Maths;
Here ‘marks’ is an identifier that represents integer data type. In the second
statement, C, FIT and Maths are defined as marks, which means that they are
defined as integers.
Note: typedef cannot create a new data type. It gives a new name for an existing
data type.
Where “identifier” is a user defined data type. After this definition, we can declare
variables of type identifier.
The enumerated variables v1, v2, v3, …..vn can only have one of the values value1,
value2, … valuen
Example: enum day {Monday, Tuesday, Wednesday, ……., Sunday}
enum day w;
The compiler automatically assigns integer digits beginning with 0 to all the
enumerated constants. Value1 is assigned 0, value2 is assigned 1 and so on.
#include <stdio.h>
main()
17
printf("m=%d \n",m);
printf("n=%ld \n",n);
printf("x=%f \n",x);
printf("y=%lf \n",y);
printf("k=%u \t p=%f \n",k,p);
}
Output:
m = 588
n = 1234567890
x = 1.234567
y =9.87654321
k = 54321 p = 1.000000
Symbolic Constants
A symbolic constant is a name, which substitutes either a numeric constant or a
character, or a string constant. When program is compiled, each occurrence of a
symbolic constant is replaced by its corresponding character sequence. Symbolic
constants are usually defined at the beginning of a program using #define statement.
Syntax: #define symbolic_name constant_value
Example: #define PI 3.142
#define MAX 100
18
The controlstring (or format string) contains the format of data being received. The
ampersand symbol ‘&’ before each variable name is an operator that specifies the
variable name’s address. The variable names are separated by commas.
When this statement is encountered, the program execution stops and control waits
until a value is typed through the keyboard. Once the value is typed and Enter key is
pressed, program execution continues.
(Refer the Table 2.1 for the different format specifiers of respective data types )
Example: printf(“%d”,sum);
[ Note: The no.of format specifiers and their data type should match with the no.of
arguments mentioned in argument list. ]
Const is a new data type qualifier defined by ANSI standard, which tells the
compiler that the value of the float variable PI must not be modified by the
program.
Reading a Character
The getchar() function is used to read single character from the keyboard.
Syntax:
variable_name = getchar();
Where variable_name is a valid C name that is declared as char type. When,
this statement is encountered, the computer waits until a key is pressed and
then assigns this that value to variable_name.
20
Writing a Character:
The function putchar() is used to display single character contained in a
variable at the terminal.
Syntax:
putchar(variable_name);
Where variable_name is any variable containing a character. This statement
displays the character contained in variable_name at the terminal.
Example:
char answer=’Y’;
putchar(answer);
will display Y on the screen. The statement putchar (‘\n’); would cause the
cursor on the screen to move to the beginning of the next line.
Formatted input
Formatted input refers to an input data that has been arranged in a particular
format. This is possible in C using the scanf() function.(scanf means scan
formatted).
Syntax: scanf(“control string”, arg1, arg2, …., argn);
The control.string specifies the field format in which the data is to be entered and
the arguments arg1, arg2,… , argn specify the address of locations where the data
is stored. Control string and arguments are separated by commas.
Control string (also known as format string) contains field specifications, which
direct the interpretation of input data. It may include:
● Field (or format) specifications, consisting of the conversion character %, a
data type character (or type specifier), and an optional number, specifying
the field width.
● Blanks, tabs, or newlines.
Blanks, tabs and newlines are ignored. The data type character indicates the type
21
-+Suppose the input data is 50, 31426, the value 50 is assigned to num1 and
31426 to num2.
-Suppose the input,data is 31426 50. The variable num1 will be assigned 31
(because of%2d), and num2 will be assigned 426 (unread, part of 31426). The
value 50 that is unread will be assigned to the first variable in the next scanf call.
-This kind of errors may be eliminated if we use the field specifications without the
field width specifications.
i.e. the statement scanf ("%d %d", &num1, &num2);
Formatted Output
It is necessary for the programmer to give careful consideration to the appearance
and clarity of the output produced by the program.
The general form of printf statement is
23
9 8 7 6
printf(“%6d”,9876) 9 8 7 6
printf(“%2d”,9876) 9 8 7 6
printf(“%-6d”,9876) 9 8 7 6
printf(“%06d”,9876) 0 0 9 8 7 6
possible to pad with zeros the leading blanks by placing a 0 (zero) before the field
width specifier as shown in the last item above. The minus (-) and zero (0) are
known as flags.