Module - 2 - CP
Module - 2 - CP
Basic Elements of C
These features make the C language suitable for system programming like an operating
system or compiler development. C programming is considered as the base for other
programming languages, that is why it is known as mother language.
History of C
There is a close similarity between learning English language and learning C language.
The classical method of learning English is to first learn the alphabets used in the language,
then learn to combine these alphabets to form words, which in turn are combined to form
sentences and sentences are combined to form paragraphs. Learning C is similar and easier.
Instead of straight-away learning how to write programs, we must first know what
alphabets, numbers and special symbols are used in C, then how using them constants,
variables and keywords are constructed, and finally how are these combined to form an
instruction. A group of instructions would be combined later on to form a program.
MODULE – 2
C Character Set
As every language contains a set of characters used to construct words, statements, etc., C language
also has a set of characters which include alphabets, digits, and special symbols. C language supports
a total of 256 characters.
Every C program contains statements. These statements are constructed using words and these
words are constructed using characters from C character set. C language character set contains the
following set of characters...
1. Alphabets
2. Digits
3. Special Symbols
4. White space
1. Alphabets:
C language supports all the alphabets from the English language. Lower and upper case letters
together support 52 alphabets.
2. Digits:
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
3. Special Symbols:
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions and other special symbols.
4. White space
1. Documentation
This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the
form of comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this
will not interfere with the given code. Basically, it gives an overview to the reader of the
program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the
program. Header files help us to access other’s improved code into our code. A copy of
these multiple files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
Preprocessors are the programs that process our source code before the process of
compilation. There are multiple steps which are involved in the writing and execution of
the program. Preprocessor directives start with the ‘#’ symbol. The #define preprocessor
MODULE – 2
is used to create a constant throughout the program. Whenever this name is encountered
by the compiler, it is replaced by the actual piece of defined code.
Example:
#define long long ll
4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere
in the program.
Example:
int num = 18;
5. Main() Function
Every C program must have a main function. The main() function of the program is written
in this section. Operations like declaration and execution are performed inside the curly
braces of the main program. The return type of the main() function can be int as well as
void too. void() main tells the compiler that the program will not return any value. The int
main() tells the compiler that the program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the
program is shifted to the called function whenever they are called from the main or
outside the main() function. These are specified as per the requirements of the
programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
First C Program
#include <stdio.h>
int main(){
printf("Hello C Language");
return 0;
}
MODULE – 2
The compilation is the process of converting high-level language instructions into low-level
language instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.
MODULE – 2
The compilation is the process of converting high-level language instructions into low-
level language instructions.
Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On
receiving a source file, the compiler first checks for the Errors. If there are any Errors then
compiler returns List of Errors, if there are no errors then the source code is converted
into object code and stores it as a file with .obj extension. Then the object code is given to
the Linker. The Linker combines both the object code and specified header file code and
generates an Executable file with a .exe extension.
We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9,
the .exe file is submitted to the CPU. On receiving .exe file, CPU performs the task according
to the instruction written in the file. The result generated from the execution is placed in a
window called User Screen.
After running the program, the result is placed into User Screen. Just we need to open the
User Screen to check the result of the program execution. We use the shortcut key Alt +
F5 to open the User Screen and check the result.
C Language Components:
The four main components of C Language are
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are
used to perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. C Token – Keywords
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are
trying to assign a new meaning to the keyword which is not allowed. You cannot redefine
keywords. However, you can specify the text to be substituted for keywords before
compilation by using C preprocessor directives. C language supports 32 keywords which
are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and
arrays. These are user-defined names consisting of an arbitrarily long sequence of letters
and digits with either a letter or the underscore(_) as a first character. Identifier names
must differ in spelling and case from any keywords. You cannot use keywords as
identifiers; they are reserved for special use. Once declared, you can use the identifier in
later program statements to refer to the associated value. A special identifier called a
statement label can be used in goto statements.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character is
allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as
different.
MODULE – 2
For example,
main: method name.
a: variable name.
3. Constants:
A constant is a fixed value. It doesn’t change its value during the execution of the program.
The following are various types of constants.
Integer Constants
Floating Point Constants
Single Character Constants
String Constants
Integer constants: Any number without fractional part is called an integer constant. The
integer numbers can contain digits (0…9) and sign (+ or -). An integer constant must not
contain commas and spaces. Integers can be decimal, octal or hexa-decimal.
Ex: 3 -3 15 -15 2500 -9700 etc. Decimal Integers
03 0123 etc. Octal Integers
0x3 0x123 etc. Hexa-Decimal Integers
Floating Point (Real) Constants:
Floating point constants are also called real constants. A floating point number can contain
digits (0…9), a decimal point and/or exponent. The letter ‘E’ or ‘e’ represents the exponent.
Ex: 45.0 4520.2587 -6847.000 -74.56000 etc.
The exponent format (‘e’ notation) can be used to represent very small or large number.
Ex: 6.5E5 or 6.5E+5 means 6.5x105
6.5E-5 means 6.5x10-5
Single Character Constants:
A single character constant contains only one character enclosed within single quotes. It
may contain any alphabet, digit or special symbol. It can be used for arithmetic operations.
However, its ASCII value is used in arithmetic operation.
Ex: ‘A’ ‘h’ ‘4’ ‘+’ ‘&’ etc.
String Constants:
A string constant is a sequence of one or more characters enclosed within double quotes. It
can contain alphabets, digits or special symbols.
Ex: “A” “ABCDE” “%d” “Result = %d” etc.
MODULE – 2
MODULE – 2
Variable
A variable in C is a memory location with some name that helps store some form of data
and retrieves it when required. We can store different types of data in the variable and
reuse the same variable for storing some other data any number of times.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.
1. C Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the
given name and data type. When the variable is declared compiler automatically allocates
the memory for it.
2. C Variable Definition
In the definition of a C variable, the compiler allocates some memory and some value to it.
A defined variable will contain some random garbage value till it is not initialized.
Example
int var;
char var2;
MODULE – 2
3. C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to
the variable.
Example
int var; // variable definition
var = 10; // initialization
or
int var = 10; // variable declaration and definition
Types of Variables in C
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
void function1(){
int x=10;//local variable
}
Global Variable
A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.
MODULE – 2
A variable that is declared with the static keyword is called static variable.
void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default.
We can explicitly declare an automatic variable using auto keyword.
void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
External Variable
myfile.h
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the
variable can store like integer, character, floating, double, etc. Each data type requires
different amounts of memory and has some specific operations which can be performed
over it. The data type is a collection of data with values having fixed values, meaning as
well as its characteristics.
Size: 4 bytes
Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;
Syntax of Double
The variable can be declared as double precision floating point using the
double keyword:
double var_name;
Syntax:
// function return type void
void exit(int check);
// Function without any parameter can accept void.
int print(void);
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);
return 0;
}
stdin: This file is used to receive the input (usually is keyborad file, but can also take
input from the disk file).
stdout: This file is used to send or direct the output (usually is a monitor file, but can
also send the output to a disk file or any other device).
stderr: This file is used to display or store error messages.
Input and Output statement are used to read and write the data in C programming. These
are embedded in stdio.h (standard Input/Output header file).
Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.C
programming language provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.
There are mainly two of Input/Output functions are used for this purpose. These are
discussed as:
getchar()
putchar()
gets()
puts()
getch()
getche()
scanf()
printf()
scanf()
The scanf() function is an input function. It used to read the mixed type of data from
keyboard. You can read integer, float and character data by using its control codes or format
codes. The general syntax is as:
scanf("control strings",arg1,arg2,..............argn);
or
scanf("control strings",&v1,&v2,&v3,................&vn);
MODULE – 2
Where arg1,arg2,……….argn are the arguments for reading and v1,v2,v3,……..vn all are the
variables.
%s To read a string
%[^] To read string of words which are not from the defined range
printf()
This ia an output function. It is used to display a text message and to display the mixed type
(int, float, char) of data on screen. The general syntax is as:
printf("control strings",&v1,&v2,&v3,................&vn);
or
The control strings use some printf() format codes or format specifiers or conversion
characters. These all are discussed in the below table as:
%s To read a string
C Operators
The C language supports a rich set of built-in operators.
An operator is a symbol that tells the compiler to perform a certain operation
(arithmetic, comparison, etc.) using the values provided along with the operator.
Operators are used in programs to manipulate data and variables.
What is an Operand?
Every operator works with some values.
For example, when we say 4+5, numbers 4 and 5 are operands whereas + is an
operator.
MODULE – 2
Different operators work with different numbers of operands like the + operator
requires two operands or values, the increment operator ++ requires a single
operand.
1. Arithmetic Operators
These operators help perform primary arithmetic operations like multiplying, dividing,
adding, subtracting, finding modulus, etc.
These operators are useful in minimizing calculation. n=n+1 can be truncated to n++. The
operators are:
1. Increment (++)
MODULE – 2
2. Decrement (–)
There is a significant difference in usage of the operators depending on the place of
application.
1. Pre-increment operators: if we write the ++ operator before the variable name, one
is added to the operand, and after that, the result is assigned to the variable.
2. Post-increment operators: if we write the ++ operator after the variable name, the
value is first assigned to the variable, and increment by 1 occurs.
3. Assignment Operators
4. Relational Operators
Relational operators are used for comparing two values of quantities with each other. It
establishes a relation between two values.
Lesser than <= Checks if one value is lesser than or equal to the
equal to other one
Greater than >= Checks if one of the values is greater than or equal
equal to to another one
Lesser than < Checks whether one operand is lesser than the
other one
Greater than > Checks whether one parent is greater than the
other one
5. Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10 is
otherwise returns FALSE FALSE
|| Logical OR - Returns FALSE if all conditions are FALSE 10 < 5 || 12 > 10 is TRUE
otherwise returns TRUE
! Logical NOT - Returns TRUE if condition is FLASE and !(10 < 5 && 12 > 10) is
returns FALSE if it is TRUE TRUE
6. Conditional Operator
Conditional operator or ternary operator reduces the work of an if-else block 21 single
statement. It is constructed for conditional expressions.
MODULE – 2
Syntax:
VariableName = (condition) ? TrueValue : FalseValue;
Example:
a= (b>c) ? (b+c) : (b-c);
⇒ 16 (10000)
& the result of Bitwise AND is 1 if all the bits are 1 A&B
otherwise it is 0
⇒ 29 (11101)
| the result of Bitwise OR is 0 if all the bits are 0 A|B
otherwise it is 1
⇒ 13 (01101)
^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1
⇒ 6 (00110)
~ the result of Bitwise once complement is negation of ~A
the bit (Flipping)
⇒ 100 (1100100)
<< the Bitwise left shift operator shifts all the bits to the A << 2
left by the specified number of positions
⇒ 6 (00110)
>> the Bitwise right shift operator shifts all the bits to the A >> 2
right by the specified number of positions
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.
sizeof(variableName);
EXPRESSIONS
Operator precedence determines the grouping of terms in an expression and decides how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Example: x=3*2/2+3/2+2–2+3*2
=6/2+3/2+2–2+3*2
=3+3/2+2–2+3*2
=3+1+2–2+3*2
=4+2–2+6
=6–2+6
=4+6
= 10
C- TypeCasting
Typecasting in C is the process of converting one data type to another data type by the
programmer using the casting operator during program design.
In typecasting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called narrowing
conversion.
Example :
int x;
float y;
y = (float) x;
Types of Type Casting in C
In C there are two major types to perform type casting.