C Programming
C Programming
Alphabets Constant
Instructions Program
Digits Variables
Special Symbols Keywords
Features Of C Programming
Features Of C Programming cont.…
Procedural Language
step by step predefined instructions are carried out
C program may contain more than one function to perform a particular task, so is easy for
beginners
Fast and Efficient
been middle-level language provides programmers access to direct manipulation with the
computer hardware, so is fast and effective in comparison to other high level languages
Modularity
The concept of storing of C programming language code in the form of libraries for further future
uses is known as modularity
C language has it’s own library to solve common problems like in this we can use a particular
function by using a header file stored in its library.
Statically Type
Meaning the type of variable is checked at the time of compilation but not at run time
Means each time a programmer type a program they have to mention the type of variables used.
Features Of C Programming cont.…
General Purpose Language
From system programming to photo editing software, C programming language is used in various
applications
Rich set of built-in Operators
It is a diversified language with a rich set of built-in operators which are used in writing complex
or simplified C programs.
Middle-Level Language
As it is a middle-level language so it has the combined form of both capabilities of assembly
language and features of the high level language.
Portability
C language is portable as programs which are written in C language can run and compile on any
system with either none or small changes.
Easy to Extend
Programs written in C language can be extended means when a program is already written in it
then some more features and operations can be added into it.
Advantages of c programming
Building block for many other programming languages: Many programming
languages such as Python, C++, Java, etc are built with the base of the C language
Powerful and efficient language: contains many data types and operators to give
you a vast platform to perform all kinds of operations
Portable language: flexible, machine independent that helps you to run your code
on any machine without making any change or just a few changes in the code
Built-in functions: There are only 32 keywords in ANSI C, having many built-in
functions
Structured programming language: complex problems are divided into smaller
blocks or functions
Middle-level language: it supports high-level programming as well as low-level
programming
Dynamic memory allocation: you are free to allocate memory at run time. For
example, if you don’t know how much memory is required by objects in your
Disadvantages of c programming
Concept of OOPs: it does not support the concept of OOPs, it follows the procedural
programming approach.
Run-time checking: compiler shows the errors after compiling whole program so its
difficult to detect the errors
Its takes more time to design and implement the software
C does not have any constructor or destructor, which is the main feature of OOP
Does not provides "namespace features", so you are not able to use the same
variable name again in one scope
Structure of C program
A program is a sequence of instructions
A statement is known as instruction in c programming
Semicolon ; determines the ends of statement
Collection of statements forms a block of statements which are enclosed inside
braces { }
here all the statements must be inside a function, where the function is a collection
of statements which performs specific tasks
There may be present of one or more function in a program and every program
contain a special function named main ()
Simple example of C program code
#include<stdio.h> /* input output header file */
#include<conio.h> /*console input output header file ie takes input and gives output*/
Void main() /*main function */
{
Printf(Hello World); /* display the content */
Getch();
}
Compiling Process
Editor
Word processor to write source code
We write code in human unvendable form in editor and save it to specified location with
appropriate file extensions.
We generally use .c extension to save c programming files
Pre-processor
It is not a part of the compiler, but is a separate step in the compilation process
a C Preprocessor is just a text substitution tool and it instructs the compiler to do
required pre-processing before the actual compilation
All preprocessor commands begin with a hash symbol (#)
It must be the first nonblank character, and for readability, a preprocessor directive
should begin in the first column
#define, #include, #if are some common examples
Compiling Process cont.
Compiler
Responsible to convert Source Code to Object Code
Linker
a linker is a computer program that takes one or more object files generated by
a compiler and combines them into one, executable program
Often the program may be divided into small blocks and after compiling the source code
created by the user all those blocks along with the header files defined must be linked
together
Finally it is responsible to create executable file with .exe extension
Executable file
We create .c source file in editor, convert it to .obj object file through compiling, and
finally produce .exe executable files by linker which on execution gives output if debug
is successful otherwise display the error message
Character set used in C
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
Alphabets
Lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits 0123456789
Special Symbols
~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | etc
Use of comment
A comment is an explanation or description of the source code of the program
it helps a developer explain logic of the code and improves program readability
At run-time, a comment is ignored by the compiler.
It starts with a slash asterisk /* and finishes with an asterisk slash */, we basically
call it as a multi line comment
While Single-line Comments uses a double slash //
// this is single line comment
/* this is
Multi line command */
C tokens
Operator Description
+ adds two operands
- subtract second operands from
first
* multiply two operand
/ divide numerator by
denominator
% remainder of division
++ Increment operator - increases
integer value by one
-- Decrement operator - decreases
integer value by one
Relational operators
Used to define relations between two different operands
Following are the basic types of relational operators
Operator Description
== Check if two operand are equal
!= Check if two operand are not
equal.
> Check if operand on the left is
greater than operand on the
right
< Check operand on the left is
smaller than right operand
>= check left operand is greater
than or equal to right operand
<= Check if operand on left is
smaller than or equal to right
operand
Logical operators
Used to connect logical expressions
Some of its common types with the assumption that a=1 and b=0 are as follow
Operator Description Example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false
Assignment Operators
Use to assign a value or a result of an expression to an identifier
Common type are
+= adds right operand to the left operand and assign the result to a+=b is same as
left a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as a=a-
result to left operand b
*= mutiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b
%= calculate modulus using two operands and assign the result to a%=b is same as
left operand a=a%b
Bitwise operators
Bitwise operators perform manipulations of data at bit level
These operators also perform shifting of bits from right to left so are not applied to float of double data type
Common types are as follow
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Conditional operator
Also called ternary operator or ? Operator
Actually it’s the if condition that we use in c language decision making process
Its syntax is: expression 1 ? Expression 2 : expression 3
The question mark "?" in the syntax represents the if part.
The first expression (expression 1) generally returns either true or false, based on
which it is decided whether (expression 2) will be executed or (expression 3)
If (expression 1) returns true then the expression on the left side of " : " i.e
(expression 2) is executed.
If (expression 1) returns false then the expression on the right side of " : " i.e
(expression 3) is executed.
Special operator
The comma operator : helps to put multiple expressions in a single expression
where the comma separates one expression from others
Size of an operator: returns the number of bytes that the operator occupies
Control Structures in c Programming
In C programs, statements are executed sequentially in the order in which they appear in
the program.
Sometimes it may happen that the programmer requires to alter the flow of execution, or to
perform the same operation for fixed iterations or whenever the condition does not satisfy.
In such a situation control statements enable us to specify the order in which the various
instructions in the program are to be executed
A statement that is used to control the flow of execution in a program is called control
structure
They define how the control is transferred to other parts of the program
Types of control structure in c programming are
Sequence
Decision
Loop
Jump
Label
Sequence Structure
Control flows form top to bottom of program
Here the statements will execute one after another in sequential order
Flow chart
Syntax
Statement 1
Statement 2
.
.
.
Statement n
Decision making statements
Decision making is about deciding the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified conditions
are meet.
Following are decision-making statements:
The if statement
The switch statement
Decision making with if statement
The if statement may be implemented in different forms depending on the
complexity of conditions to be tested. The different forms are:
Simple if statement
The if...else statement
Nested if...else statement
The if-else-if statement
Simple if Statement
if statement is the most simple decision making statement.
It is used to decide whether a certain statement or block of statements will be
executed or not i.e. if a certain condition is true then a block of statement is
executed otherwise not
Its general form is
if (Test Expression) /* no semi-colon */
{
statement 1;
...........
statement n;
}
statement x;
Example: a program to find is a number is even or not?
The if...else Statement
An if statement can be followed by an optional else statement, which executes
when the Test Expression is false.
The general form of a simple if...else statement is:
if(Test Expression)
{
statement block 1; // here the block may contain 1 or more statements
}
else
{
statement block 2;
}
statement x;
Example: a program to read age from user and determine if he/she can vote or not?
Nested if…else Statement
We can add if...else statement inside if block or else block. This is called nesting of if...else.
The general form is
if(Test Expression 1)
{
if(Test Expression 2)
{
statement block 1;
}
else
{
statement block 2;
}
}
else
{
if(Test Expression 3)
{
statement block 3;
}
else
{
statement block 4;
}
}
Example: program to find the greatest number among given three numbers
The if-else-if Statement
C language supports if-else-if statements to test additional conditions apart from the initial Test Expression.
The if-else-if construct works in the same way as a normal if statement.
Its construct is given below:
if(Test Expression 1)
{
statement block 1;
}
else if(Test Expression 2)
{
statement block 2;
}
...........................
else
{
statement block x;
}
statement y;
Example: program to determine if the given number is positive negative or zero
The switch statement
The switch statement allows us to execute one code block among many alternatives
Switch statement in C tests the value of a variable and compares it with multiple
cases
Once the case match is found, a block of statements associated with that particular
switch (expression)
case is executed.
{
Example: program to read arithmetic operator case constant1:
// statements
From user and perform the calculation accordingly break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
Looping in c programming
Also called iteration or repetition
used for executing a block of statements repeatedly until a given condition returns
false
consists of two parts
a body of a loop and
a control statement
Basic purpose is to repeat the same code a number of times
Types of looping statements are:
For
While
Do ….while
For Statement
most frequently used loop
Basic syntax is as follow
for (initialization; test condition; increment/decrement operator)
{
//Statement 1
//Statement 2
………
//Statement n
}
Consists of three expressions separated by ;
Initialization: starts with it, where initialization of counter variable is done, execute only once
Test Condition: value of counter variable is tested and if true, execute statements inside for loop
Increment & decrement operator: helps to increase decrease counter variable end of iteration
Example: program to print first 10 natural numbers and find their sum:
Nested for loop
process of defining for loop inside a for loop is called nested for loop
Example: write a program to produce following output
*****
****
***
**
*
While loop in c
A loop is used for executing a block of statements repeatedly until a given condition
returns false.
Syntax
while(condition) {
statement(s);
increment, decrement;
}
Example: program to print even number between first n natural number
Do ….. While loop in C
Used when we need to repeatedly execute a block of statements
Like while the do-while loop execution is also terminated on the basis of a test
condition
The main difference between a do-while loop and while loop is in the do-while loop
the condition is tested at the end of the loop body
i.e. do-while loop is exit controlled whereas the other two loops are entry
controlled loops
Note that in do-while loop the loop body will execute at least once irrespective of
test condition.
Syntax:
do
Example: program to allow user enter {
// loop body
their name and number of time they update_expression;
}
Want to print and print it while (test_expression);
The jump statement in c programming
It makes the control jump to another section of the program unconditionally when
encountered
It is usually used to terminate the loop or switch-case instantly
It is also used to escape the execution of a section of the program.
Basically we have four types of jump statements
Break
Continue
Go to
Return
The Break Statement
A break statement is used to terminate the execution of the rest of the block where
it is present and takes the control out of the block to the next statement
It is mostly used in loops and switch-case to bypass the rest of the statement and
take the control to the end of the loop
We have already discussed break statement in switch control statement
lets take a simple example
Continue jump statement
like any other jump statement it interrupts or changes the flow of control during the
execution of a program.
It is commonly used in loop.
Rather than terminating the loop it stops the execution of the statements
underneath and takes control to the next iteration
Similar to a break statement, in the case of a nested loop, the continue passes the
control to the next iteration of the inner loop where it is present and not to any of
the outer loops
Example: program to print even numbers present in between given list of natural
numbers
Go to Jump statement
used to transfer the flow of control to any part of the program desired
When the compiler reaches the goto statement, then it will jump unconditionally (
both forward and backward ) to the location specified in the goto statement (we
called it as a label)
The programmer needs to specify a label or identifier with the goto statement
Example: a program do display result on basis of marks entered by the users
Array Introduction
An array is defined as finite ordered collection of homogenous data, stored in
contiguous memory locations.
Where finite indicate that data range must be finite, ordered means data must be
stored in continuous memory address
Homogeneous means data must be of similar data type
They may be of one dimensional (list) or two dimensional (table)
Declaration of an array
Before using array we need to declare it
Array variables are declared identically to variables of their data type, except that
the variable name is followed by one pair of square [ ] brackets for each dimension
of the array
data-type variable-name[size];
Example
int arra[10];
Here int is the data type of array, arra is the name of array and 10 is the size of
array.
It means arra is a array which can hols 10 different data of integer type
Diagrammatically it can be represented as
Arra [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
Need of Array
Codes are organized and readable
Suppose we need to store marks of 100 students, then basically we need to create
100 different variables which will increase the size of our program as well as
program looks clustered and messy.
The solution to this is creation of array
Here we can create an array and store the consecutive marks corresponding to the
roll number.
Advantages of array
Used to represent multiple data items of same type by using a single name
Access to data in a given array is very fast
2D makes it easy in mathematical applications and matrix implementation
data are sored in contagious memory locations
Array have elements of fixed size
Disadvantages of array
Required time for insertion and deletion of items
Wastage of memory because array are of fixed size
It required free space in contagious form, so free space which are not in contagious
form cannot be used
Its is not possible to increase size of array once we declare it
Examples
Write a program to enter 10 different numbers and display them using array
Write a program to enter salary of employees and compute the total salary using
array
Write a program to enter marks of student in computer science and count the
number of student scoring marks between 70 to 95 using array
2 Dimensional Array
Basic type of declaration of array
Data_type name_of_the_array[X][Y];
visualization of 2D array
Lets consider an example int arr[4][5];
Using row index and column index we can access 2D array element
For example we can access element stores in first row and second columns of above
array as a[0][1] ie 2
Similarly a[0][2]=3
Lets take an example:
For practical portion
Header file in C
Files with extension .h containing c function declaration or definition
Stdio.h: Standart input output
Printf (), scanf (), getc(), putc(), getchar(). Putchar() etc
Conio.h: consel input output
Clrscr(), getch(),
Math .h :
Sqrt(), pow (x,y),
String .h
Strlen(), strcon()