CP - Unit-II - C Fundamentals
CP - Unit-II - C Fundamentals
CP - Unit-II - C Fundamentals
Introduction
History of ‘C’:
The ALGOL programming language is the root of all modern languages introduced in 1960s by
international committee. The purpose behind this is to develop all purpose language which is
used to program all types of application instead of using different languages for different
purposes as COBOL for commercial applications, FORTRAN for engineering and scientific
applications and so on. But ALGOL was too abstract and too general.
To overcome the drawback of ALGOL, new language called Combined Programming Language
(CPL) was developed in 1963. CPL was very big with many features and hence very hard to
learn and difficult to implement.
In 1967, Martin Richards developed a language called Basic CPL (BCPL). But it was less powerful
and too specific.
In 1970, Ken Thompson created new language called B. It was created for Unix operating
system at Bell Laboratories.
At last, C was created by Dennis Ritchie at the Bell Laboratories in 1972. It was initially
implemented on a system that used the Unix operating system.
In 1989 American National Standards Institute (ANSI) committee has approved a version of C
known as ‘ANSI C’.
And then in 1990 International Standards Organization has approved C ANSI/ISO C (C89).
BCPL and B were typeless languages whereas C provides a variety of data types. The fundamental
types are characters, integers, floating point numbers of several sizes.
Though, it has been closely associated with the UNIX system, C is not tied to any one operating
system or machine. It has been used equally well to write major programs in many different
domains.
Low Level languages: Assembly language and Machine language are called low level languages. Low
level languages provide nothing other than access to the machines basic instruction
set. Example: Assembler, etc.
Middle Level languages: Middle level languages provide facilities of both high level as well as low
level programming. Examples: C, etc.
C allows direct manipulation of bits, bytes and addresses. Thus, it is ideal for system level
programming. Compilers and Operating systems can be written using C language. C program is very
portable because it not hardware or system dependent.
Importance of C
The increasing popularity of C is probably due to its many desirable qualities. It is a robust
language whose rich set of built-in functions and operators can be used to write any complex
program.
Programs written in C are efficient and fast. This is due to its variety of data types and powerful
operators. It is many times faster than BASIC.
There are only 32 keywords in ANSI C and its strength lies in its built-in functions. Several
standard functions are available which can be used for developing programs.
C is highly portable. This means that C programs written for one computer can be run on
another with little or no modification.
C language is well suited for structured programming, thus requiring the user to think of a
problem in terms of function modules or blocks. A proper collection of these modules would
make a complete program. This modular structure makes program debugging, testing and
maintenance easier.
Another important feature of C is its ability to extend itself. A C program is basically a
collection of functions that are supported by the C library. We can continuously add our own
functions to C library. With the availability of a large number of functions, the programming
task becomes simple.
1. Preprocessor Directives:
These are special instructions that tell the computer how to prepare your code before it's
turned into a program.
Imagine it as a set of rules and notes you give to a helper before they start building
something for you.
2. Main Function:
Think of the main () function like the starting point of a race. It's where your program gets
going.
This is where your computer begins executing the instructions you've written.
3. Statements:
These are like individual steps or actions your program takes.
For example, telling it to do math, talk to you, or decide what to do next.
Editor: The text editor is used to write a source code. The code should be in the standard
form as required for execution. Generally notepad, word processor, etc are used to write a
code. Some compilers like Borland C/C++ also provide editor.
Source Code: This is the user readable plain text written using computer programming
language. It is the input for C compiler.
C Preprocessor: This is the initial processing before compilation. In this stage source code is
converted into an expanded C source code which is the input for C compiler.
C Compiler: Compiler converts the expanded high level source code into the machine
understandable low level code. Compiler checks for errors and ask user for corrections if any.
An error free code is then converted into object file. This code is user readable but not
executable.
Linker: Linker takes one or more object files and linked with other supported standard library
files to produce one executable file.
Loader: In this loading process the executable file loads from secondary memory to
main/primary memory. And then program run using systems loader.
Prof. Kuldeep S. Ratawa 3
Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]
C Programming Language
Learning any new language involves first know what are the different alphabets, numbers, symbols
which form that particular language and learning C programming language is also falls on the same
category.
C Character Set:
A character denotes any single alphabet, number, special symbol used to represent particular
information. The reach set of valid alphabets, numbers and special symbols allowed in C is as:
Data Types
There are five data types.
char - capable of holding one character. (size - 1 byte)
int - represents natural size of integers (size - 2 bytes)
float - hold numbers with six digits of precision. (size - 4 bytes)
double - hold numbers with ten digits of precision. (size - 8 bytes)
void - used to declare a function as returning no value (valueless)
signed: By default all the data types are of type signed. This modifier accepts both the values
positive as well as negative.
Example:
int x = 50;
int x = -50;
signed int x = 50;
signed int x = -50;
unsigned: This modifier is used to change the data type, so that it can only store positive
values.
Example:
unsigned int x = 100;
unsigned int x = - 100; (wrong)
short: This modifier is applied to data when a length shorter than the normal integer length is
sufficient.
Example:
short int a = 10; (consume less than 2 byte memory)
long: A long is used when a length of more than the normal integer length is required.
Example:
long int a; occupies 4 bytes
2 + 2 4 bytes
Constants
A constant can be defined as a quantity that does not change.
Integer constants
Integer constant is an integer quantity containing sequence of digits.
It has no decimal point.
It can be either positive or negative.
Blanks and commas are not allowed within integer constants.
It must lie within the range of integer values (-32768 to 32767).
Character constants
A character constant is character enclosed in single quotation marks.
It can contain only one character.
A character denotes an alphabet, digit or a special character.
Variables
A variable is the name of memory location that is used to hold a value which may vary during
program execution. Rules for naming a variable -
A variable name can be any combination of alphabets, digits or underscores.
The length of variable name can range from 1 to 8.
The first character of the variable name must be an alphabet.
No commas or blanks are allowed within a variable name.
No special symbol other than underscore can be used.
C is a case sensitive language i.e. variable name ‘NAME’ and ‘name’ is different. Any variable must be
declared before using it in program.
Variable declaration
data_type variable_name ;
Example:
int abc; Meaningful names must be given to variables. Two or more
char name; variables of the same type can be declared separating them with
float avg; comma
Example:
long int i,j;
unsigned int answer;
Storage Classes
In C, storage classes are used to define the scope, lifetime, and visibility of variables.
1. auto: This is the default storage class for local variables. Variables declared as "auto" are
created when the function is called and destroyed when the function exits. They have block
scope, which means they are only accessible within the block of code in which they are
defined.
Ex:
void myFunction()
{
auto int x; // Declared as auto by default
}
2. register: Variables declared as "register" are stored in CPU registers for faster access.
However, the "register" keyword is only a hint to the compiler, and it may or may not place
the variable in a register, depending on the compiler and system architecture.
Ex: register int counter;
3. static: Variables declared as "static" have a longer lifetime than "auto" variables. They retain
their values between function calls and have file scope, meaning they are visible throughout
the entire file in which they are declared.
Ex: static int globalCounter; // File scope variable
4. extern: Variables declared as "extern" are used to indicate that the variable is defined in
another source file. They are typically used when you want to access a global variable that is
defined in a different file.
Ex: extern int globalVariable; // Declares a variable defined elsewhere
Keywords
Keywords are predefined or reserved words whose meaning is already defined by compiler. They are
used only for specific task.
Restrictions:
Keywords can be used only for their intended purpose.
Keywords cannot be used as function name or user-defined variables.
All keywords must be written in lowercase.
Operators operate on operands. Operands can be constants or variables. If all operands are
constants in an expression it is called a constant expression. C constants can be any of the basic
data types.
Operators can be classified as either unary, binary or ternary operators.
Unary operators act on only one operand, binary operators act on two operands and ternary
operators operate on three operands.
Types of Operators
Arithmetic operators Assignment operators
Relational operators Conditional operators
Logical operators Special operators
Bitwise operators
Arithmetic operators:
Operator Meaning Example (a = 9, b = 2) Result
+ Addition a+b 11
- Subtraction a–b 7
* Multiplication a*b 18
/ Division (returns quotient) a/b 4
% Modulo operation (returns remainder) a%b 1
The remainder operator (%) requires that both operands be integers and the second operand be
nonzero. When one of the operands is negative, the sign of first operand is the sign of the result
operand.
5%2=1 -5 % 2 = -1
5 % -2 = 1 -5 % -2 = -1
Relational operators:
Operator Meaning Example ( a = 15, b =10) Result
> Greater than a>b True
< Less than a<b False
>= Greater than or equal to a>=b True
<= Less than or equal to a<=b False
== Equal to a==b False
!= Not equal to a!=b True
Note: Double equal to sign (= =) is used to compare two values. Single equal to sign (=) is used as
assignment operator.
Logical operators:
Operator Meaning Example Result
12 && 0 0
&& Logical AND
8 && 3 1
10 || 5.5 1
|| Logical OR
9 || 0 1
! 20 0
! Logical NOT
!0 1
Note: Any non-zero value = Logical True (1) and Zero = Logical False (0)
Bitwise operators:
Assignment operators:
It is the most common and well known operator in any language. This assignment operator (=) is
used in any valid c expression.
Example:
1. x = 5
2. c = a + b
3. p = q = r = 20 (multiple assignment)
Conditional operators:
The conditional operator ( ? : ) works on three operands and also known as ternary operator. Format
for using conditional operator is as follows:
Example:
If a = 100 ; b = 50 then
x = (a>b)? a :b (Answer: x = a )
Special operators:
Operator Meaning
* Pointer operator
& Address operator
sizeof ( ) Size of operator (returns size of operand in bytes)
We will study * and & operators in the pointer chapter.
Example:
int i,j;
float k;
j = sizeof(i); // Answer j = 2 [ i is an integer and occupies 2 bytes ]
j = sizeof(k); // Answer j = 4 [ k is a float and occupies 4 bytes ]
Type casting:
An arithmetic operation gives an integer result if both operands are integers. Operation between two
real integers gives a real result. Let us consider mixed mode expressions where both operands are of
different types.
Generally if operands in the expression are different types, then the lower type is promoted to the
higher type, before the expression proceeds.
Example:
int a;
float b;
a = 2.89; // a= 2 [ truncation of the fractional part ]
b = 4; // b = 4.000000
Operator precedence:
Precedence Operator Description Associativity
++ -- Suffix/postfix increment and decrement
() Function call
[] Array subscripting
1 . Structure and union member access Left-to-right
Structure and union member access through
->
pointer
(type){list} Compound literal(C99)
++ -- Prefix increment and decrement
+- Unary plus and minus
!~ Logical NOT and bitwise NOT
(type) Type cast
2 Right-to-left
* Indirection (dereference)
& Address-of
sizeof Size-of
_Alignof Alignment requirement
3 */% Multiplication, division, and remainder
4 +- Addition and subtraction
5 << >> Bitwise left shift and right shift
< <= For relational operators < and ≤ respectively
6
> >= For relational operators > and ≥ respectively Left-to-right
7 == != For relational = and ≠ respectively
8 & Bitwise AND
9 ^ Bitwise XOR (exclusive or)
10 | Bitwise OR (inclusive or)
Library functions
Library functions are inbuilt functions and stored in a common place called library. All standard C
library functions are declared in header files. For example if you want to use printf() & scanf(), then
you have to include stdio.h file. We will study preprocessor directives and function in a separate
chapter in detail.
printf() function
This function is used to display or print data on output screen.
Syntax:
printf(“Message to be display”);
Example:
printf(“Welcome to C programming”); // output is Welcome to C programming
printf() function is also used to display or print value of a variable on output screen.
Syntax:
printf(“format string”, list_of_variable);
Example:
A = 15;
printf(“Value = %d”, A); // output is Value = 15
Example:
scanf() function
This function is used to read values of different types from standard input device.
Syntax:
scanf(“format string”,list_of_variable_address);
Example:
scanf(“%d”,&a); // stores integer value in variable a
scanf(“%d %f”,&a,&b); // stores integer value in variable a and float value in variable b
Format specifiers:
Format String For Data Types Displays - printf() Reads - scanf()
%c Char Single character Single char
%d int Signed integer Signed decimal int.
%e float or double Exponential format Signed decimal
%f float or double Signed decimal Signed decimal
%o int Unsigned Octal Octal Value
%x %X int Unsigned Hex Unsigned Hex value
%u int Unsigned decimal int. Unsigned decimal int.
putchar() function
This function is used to display a single character on standard output screen.
Syntax:
putchar(variable_name);
Example:
putchar(ch); // this will display value of ch on output device (monitor)
getchar() function
This function is used to read a single character from standard input device (keyboard)
Syntax:
variable_name = getchar();
Example:
ch = getchar(); // this will read value from standard device and stored in variable ch
puts() function
This function is used to print of display string on output device (monitor)
Syntax:
puts(string);
Example:
char name[20]; Output:
Enter your name: Amol
printf(“Enter your name: ”); Amol
gets(name);
puts(name);
gets() function
This function is used to read string and stores it into character array. The gets() function reads string
or sequence of characters till null character()
Syntax:
gets(string);
Example:
char name[20]; Output:
Enter your name: Amol
printf(“Enter your name”);
Amol
gets(name);
puts(name);
Escape Sequences:
Escape sequences are the string argument of the printf() function used for printing hard-to-get
characters. A list of all escape sequences used in C is given below, each one of them represent one
character although they consist of two characters.
Structure of C program
Line no. 1:
This is the comment block – optional and non executable in nature. Comments are added to make a
program more readable to you but the compiler must ignore the comments. There are two types of
comments in C: (a) Multi-line comments (also called block comments) and (b) single-line comments
(also called line comments).
Opening delimiter /* & Closing delimiter */ Compiler ignores everything you have typed between
the delimiters /* and */. For single-line comment, simply type the symbol // and then type the text
of comment to the end of that line.
Line no. 2:
The pre processor is a phase which occurs prior to compilation of a program. The preprocessor has
two main uses: it allows external files, such as header files, to be included and it allows macros to be
defined. It is written just before the main()in the C program.
Line no. 3:
Every C program contains a function called main. This is the starting point of the program. A C
program must contain one or more function one of which must be main().
Line no. 5, 6, 7:
This is the executable block of instructions to perform a specific functionality. printf() function is a
‘library function’ provided by complier which is ready to use. When printf ( ) function is executed, its
built-in instructions process it, i.e. string enclosed in quotation called as string constant or character
string is displayed on the output device, usually on VDU.
Instruction in C
Instructions in C are formed using different types of constants, variables and keywords.
Example:
int sal;
float pi;
char name, dept;
Example:
printf(“Enter number”);
scanf(“%d” , &A);
3. Arithmetic instruction:
A C arithmetic instruction consists of a variable name on the left hand side of = and variable name
and constant on the right hand side of =. The variable and constants appearing on the RHS of = are
connected by arithmetic operators like +,-,* and /.
Example:
age = 30;
c = a + b;
avg = ( a+b+c+num)/4;
4. Control instruction:
It is used to control the sequence of execution of various statements in a C program. (Sequence,
selection/decision, repetition/loop, case control instructions)
Example:
do
{
--------- ;
--------- ;
} while (condition);
Points to Remember
The C language is developed by Dennis Ritche.
C is structured, middle level language programming language.
C programming is a case sensitive programming language.
There are basic 4 data types – character, integer, float, double.
The C language has 32 keywords.
Operator precedence and associativity determines the evaluation order of expressions.
A C program must contain one or more function one of which must be main().
Instruction = Keywords + Constants + Variables
C Programs
1. Hello World
2. Sum of Two Numbers
3. Product of Two Numbers
4. Division of Two Numbers
5. Average of Three Numbers
6. Cube of Integers
7. Area of a Rectangle
8. Area and Circumference of a Circle
9. Area of a Triangle
10. Conversion of Fahrenheit to Celsius
11. Conversion of Feet to Inches
12. Simple Interest Calculation
1. Compiler:
A compiler translates the entire source code of a program into machine code or an
intermediate code before execution.
It reads the source code files and generates object files or directly executable files.
Compilation is a separate process from execution. The compiled code can be executed
multiple times without the need for recompilation unless changes are made to the
source code.
Compilers are generally used for languages like C, C++, and Java.
Compiled programs tend to be faster in execution compared to interpreted programs
because the translation process is done upfront.
2. Interpreter:
An interpreter reads the source code line by line and executes it immediately.
It does not produce a standalone machine code or intermediate code file but
translates and executes the code directly.
Interpretation and execution occur simultaneously, without a separate compilation
step.
Interpreters are often used in scripting languages like Python, Ruby, and JavaScript.
Interpreted programs tend to have slower execution compared to compiled programs
because the code is translated and executed at runtime.
Here are some key differences between compilers and interpreters:
Performance: Compiled programs generally execute faster than interpreted programs
because they are translated into machine code or an intermediate representation
beforehand.
Portability: Interpreted programs are usually more portable since they do not rely on
machine-specific compiled binaries.
Error Detection: Compilers perform a comprehensive analysis of the entire code and can
catch errors at compile time, while interpreters may only detect errors as they encounter
them during runtime.
Ease of Debugging: Interpreters often provide better support for debugging since they can
give more detailed information about the state of the program during execution.
Flexibility: Interpreted languages are often more flexible as they allow dynamic typing and
runtime evaluation of code constructs.
// Executable statements
if (x < y) {
printf("x is less than y\n");
} else {
printf("x is greater than or equal to y\n");
}
Libraries for use by C programs really consist of two parts: header files that define types and macros
and declare variables and functions; and the actual library or archive that contains the definitions of
the variables and functions