C Programming54!4!40
C Programming54!4!40
BASICS OF C PROGRAMMING
Introduction to programming paradigms – Applications of C Language - Structure of C program - C
programming: Data Types - Constants – Enumeration Constants - Keywords – Operators: Precedence and
Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Preprocessor directives - Compilation process .
PROGRAMMING PARADIGMS:
In computing, a program is a specific set of ordered operation for a computer to perform.The process
of developing and implementing various sets of instruction to enable a computer to perform a certain task
is called PROGRAMMING.
PROGRAMMING PARADIGMS INCLUDE:
1. IMPERATIVE PROGRAMMING PARADIGMS:
Command show how the computation takes place, step by step. Each step affects the global
state of the computation.
2. STRUCTURED PROGRAMMING PARADIGMS:
It is a kind of imperative programming where the control flow is defined by nested loops,
conditionals, and subroutines, rather than via gotos. Variables generally local to blocks.
3. OBJECT ORIENTED PROGRAMMING(OOP) PARADIGMS:
It is a programming paradigms based on the concepts of objects, which may contain data, in the
form of fields, often known as attributes, and code, in the form of procedures, often known as
methods.
4. DECLARATIVE PROGRAMMING PARADIGMS:
The programmer states only what the results should look like , not how to obtain it. No loops,
no assignments, etc. Whatever engines that interprets this code is just supposed go gets the
desired information and can use whatever approach its wants.
5. FUNCTIONAL PROGRAMMING PARADIGMS:
In functional programming, control flow is expressed by combining functional calls, rather than
by assigning values to variables.
6. PROCEDURAL PROGRAMMING PARADIGMS:
This paradigms includes imperative programming with procedure calls.
7. EVENT DRIVEN PROGRAMMING PARADIGMS:
In which the flow of the program is determined by events such as user action(mouse clicks, key
presses), sensor output, or message from other program/threads. It is the dominant paradigms
used in GUI and other applications that are centred on performing certain action in response to
user input.
8. FLOW DRIVEN PROGRAMMING PARADIGMS:
Programming processes communicating with each other over predefined channels.
9. LOGIC PROGRAMMING PARADIGMS:
Here programming is done by specifying a set of facts and rules. An engine infers the answer
to question.
10. CONSTRAINTS PROGRAMMING PARADIGMS:
An engine finds the value that meet the constraints.
One of the characteristics of a language is its support for particular programming
paradigms. For example: small talks has direct support for programming in the object oriented
way, so it might called an object oriented language.
Very few language implement a paradigms 100%, when they do, they are “PURE”. It is
incredibly rare to have a “pure OOP language” or a “pure functional language”.
A lot of language will facilitate programming in one or more paradigms. If a language is
purposely designed to allow programming in many paradigms is called a “multi paradigms
language”.
APPLICATION OF C:
1. OPERATING SYSTEM
2. EMBEDDED SYSTEM
3. GUI(GRAPHICAL USER INTERFACE)
4. NEW PROGRAMMING PLATFORMS
5. GOOGLE
6. MOZILLA FIREBOX AND THUNDERBIRD
7. MYSQL
8. COMPILER DESIGN
9. ASSEMBLERS
10. TEXT EDITORS
11. DRIVERS
12. NETWORK DEVICES
13. GAMING AND ANIMATION
FEATURES OF C PROGRAMMING/ADVANTAGES:
• C is a robust language with rich set of built in function.
• Programs written in c are efficient and fast.
• C is highly portable, programs once written in c can be run on another machine with minor or no
modification.
• C is basically a collection of c library functions, we can also create our own function and add it to
the c library.
• C is easily extensible.
DISADVANTAGE OF C:
• C doesnot provide OOP.
• There is no concepts of namespace in c.
• C doesnot provides binding or wrapping up of a single unit.
• C doesnot provide constructor and destructor.
STRUCTURE OF C:
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.
Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include directive.
Definition section: The definition section defines all symbolic constants such using the
#define directive.
Global declaration section: 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. This section also declares all the user-defined functions.
Main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part.
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. 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.
Subprogram section:
If the program is a multi-function program then 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.
All section, except the main () function section may be absent when they are not required.
C PROGRAMMING: DATA-TYPES
A data-type in C programming is a set of values and is determined to act on those
values. C provides various types of data-types which allow the programmer to select the
appropriate typefor the variable to set its value.
The data-type in a programming language is the collection of data with values having
fixed meaning as well as characteristics. Some of them are integer, floating point, character etc.
Usually, programming languages specify the range values for given data-type.
C Data Types are used to:
Pointers These are powerful C features which are used to access the
memory and deal with their addresses.
C allows the feature called type definition which allows programmers to define their own
identifier that would represent an existing data type. There are three such types:
Structure It is a package of variables of different types under a single name. This is done
to handle data efficiently. “struct” keyword is used to define a structure.
Union These allow storing various data types in the same memory location. Programmers
can define a union with different members but only a single member can contain
a value at given time.
Enum Enumeration is a special data type that consists of integral constants and each of them
is assigned with a specific name. “enum” keyword is used to define the enumerated data
type.
int a = 4000; // positive integer data type float b = 5.2324; // float data type
char c = 'Z'; // char data type
long d = 41657; // long positive integer data type long e = -21556; // long -ve integer data type
int f = -185; // -ve integer data type
short g = 130; // short +ve integer data type short h = -130; // short -ve integer data type
double i = 4.1234567890; // double float data type float j = -3.55; // float data type
}
Let's see the basic data types. Its size is given according to 32 bit architecture.
Data Types Memory Size Range
float 4 byte
double 8 byte
long double 10 byte
The storage representation and machine instructions differ from machine to Machine.
sizeof operator can use to get the exact size of a type or a variable on a particular platform.
Example: #include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int is: %d \n", sizeof(int));
printf("Storage size for char is: %d \n", sizeof(char)); return 0
}
CONSTANTS
A constant is a value or variable that can't be changed in the program, for example: 10,
20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
C const keyword:
The const keyword is used to define constant in C programming.
Example:
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
The value of PI is: 3.140000
If you try to change the value of PI, it will render compile time error.
#include<stdio.h>
int main(){
const float PI=3.14; PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
Compile Time Error: Cannot modify a const object.
C #define preprocessor
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.
Syntax: #define token value
Let's see an example of #define to define a constant.
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output:
3.140000
Backslash character constant:
C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as “Escape
Sequence”.
Example:
\t is used to give a tab
\n is used to give new line
Constants Meaning Constants Meaning
\a beep sound \n newline
\v vertical tab \\ backslash
\b backspace \r carriage return
\’ single quote \0 null
\f form feed \t horizontal tab
\” double quote
ENUMERATION CONSTANTS:
An enum is a keyword, it is an user defined data type. All properties of integer are
applied on Enumeration data type so size of the enumerator data type is 2 byte . It work like
the Integer. It is used for creating an user defined data type of integer. Using enum we can
create sequence of integer constant value.
• In above syntax tagname is our own variable. tagname is any variable name.
It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list. If constant one value is not initialized then by default sequence will be start
from zero and next to generated value should be previous constant value one.
Example:
• In above code first line is create user defined data type called week.
Example:
#include<stdio.h>
#include<conio.h>
enum abc{x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf(“sum: %d”,a);
getch();
}
Output:
Sum: 3
KEYWORDS:
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are
only 32 reserved words (keywords) in C language.
A list of 32 keywords in c language is given below:
OPERATORS :
Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Ternary or Conditional Operators
Arithmetic Operators:
Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A
hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators:
Which can be used to check the Condition, it always return true or false. Lets suppose variable
hold 8 and B hold 3.
Logical Operator:
Which can be used to combine more than one Condition?. Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is
Logical Operator.
Assignment operators:
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
Ternary Operator:
If any operator is used on three operands or variable is known as Ternary Operator. It can be
represented with ? : . It is also called as conditional operator
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of application.
Syntax:
In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
value Or variable or statement or any mathematical expression. If condition will be true expression-2 will
be execute otherwise expression-3 will be executed.
Conditional Operator flow diagram
Example:
Special Operators:
C supports some special operators
Operator Description
* Pointer to a variable.
Expression evaluation
In C language expression evaluation is mainly depends on priority and associativity.
Priority
This represents the evaluation of expression starts from "what" operator.
Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.
Precedence of operators :
The precedence rule is used to determine the order of application of operators in evaluating sub
expressions. Each operator in C has a precedence associated with it. The operator with the highest
precedence is operated first.
Associativity of operators :
The associativity rule is applied when two or more operators are having same precedence in the sub
expression. An operator can be left-to-right associative or right-to-left associative.
Rules for evaluation of expression:
•First parenthesized sub expressions are evaluated first.
•If parentheses are nested, the evaluation begins with the innermost sub expression.
•The precedence rule is applied to determine the order of application of operators in evaluating
sub expressions.
•The associability rule is applied when two or more operators are having same precedence in the sub
expression.
EXPRESSION:
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
An expression that has only one operator is known as a simple expression. E.g: a+2
An expression that involves more than one operator is called a compound expression.
E.g: b=2+3*5.
IO STATEMENT:
• Formatted Functions
• Unformatted functions
FORMATTED INPUT FUNCTION:
SCANF():
It is used to get data in a specified format. It can accept different data types.
Syntax:
scanf(“Control String”, var1address, var2address, …);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
scanf(“%d %d”,&a,&b);
sum= a+b;
}
sum= a+b;
printf(“sum is:%d”,sum);
}
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> j
void main()
{
Char ch;
ch=getchar();
Printf(“%c”,ch);
}
getch():
getch() accepts only a single character from keyboard. The character entered through getch() is not
displayed in the screen (monitor).
Syntax:
variable_name = getch();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ Ch=a
Char ch;
ch=getch();
Printf(“ch=%c”,ch);
}
getche():
getche() also accepts only single character, but getche() displays the entered character in the
screen.
Syntax:
variable_name = getche();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ a
Ch=a
Char ch;
ch=getche();
Printf(“ch=%c”,ch);
}
gets():
This function is used for accepting any string through stdin (keyboard) until enter key
is pressed.
Syntax:
gets(variable_name);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Char ch[10]; OUTPUT:
cprogram
gets(ch); Ch=cprogram
Printf(“ch=%s”,ch);
getch();
}
UNFORMATTED OUTPUT FUNCTION:
• putchar()
• putch()
• puts()
putchar():
This function prints one character on the screen at a time.
Syntax :
putchar(variable name);
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> enter a character: j
j
void main()
{
Char ch;
printf(“enter a character:”);
ch=getchar();
putchar(ch);
getch();
}
putch():
putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.
Syntax:
putch(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Press any character:
char ch; Pressed character is: e
clrscr();
printf(“Press any character: ”);
ch = getch();
printf(“\nPressed character is:”);
putch(ch);
getch();
}
puts():
This function prints the string or character array.
Syntax:
puts(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Enter a string: cprogramming
char ch[20]; cprogramming
clrscr();
puts(“enter a string”);
gets(ch);
puts(ch);
}
ASSIGNMENT STATEMENT:
The assignment statement has the following form:
Syntax:
variable = expression/constant/variable;
Its purpose is saving the result of the expression to the right of the assignment operator to the
variable on the left. Here are some rules:
• If the type of the expression is identical to that of the variable, the result is saved in the variable.
• Otherwise, the result is converted to the type of the variable and saved there.
❖ If the type of the variable is integer while the type of the result is real, the fractional
part, including the decimal point, is removed making it an integer result.
❖ If the type of the variable is real while the type of the result is integer, then a decimal
point is appended to the integer making it a real number.
• Once the variable receives a new value, the original one disappears and is no more available.
Examples of assignment statements,
b = c ; /* b is assigned the value of c */
a = 9 ; /* a is assigned the value 9*/
b = c+5; /* b is assigned the value of expr c+5 */
• The expression on the right hand side of the assignment statement can be: An arithmetic
expression;
❖ A relational expression;
❖ A logical expression;
❖ A mixed expression.
For example,
int a;
float b,c ,avg, t;
avg = (b+c) / 2; /*arithmetic expression */
a = b && c; /*logical expression*/
a = (b+c) && (b<c); /* mixed expression*/
DECISION MAKING STATEMENTS:
Decision making statement is depending on the condition block need to be executed or not which
is decided by condition.
If the condition is "true" statement block will be executed, if condition is "false" then statement
block will not be executed.
In this section we are discuss about if-then (if), if-then-else (if else), and switch statement. In C
language there are three types of decision making statement.
• if
• if-else
• switch
if Statement:
if-then is most basic statement of Decision making statement. It tells to program to execute a
certain part of code only if particular condition is true.
Syntax:
if(condition)
{
Statements executed if the condition is true
}
FLOWCHART:
Constructing the body of "if" statement is always optional, Create the body when we are having multiple
statements.
For a single statement, it is not required to specify the body.
If the body is not specified, then automatically condition part will be terminated with next semicolon ( ; ).
Example:
#include<stdio.h>
int main()
{
int num=0;
printf(“enter a number:”); OUTPUT:
scanf(“%d”,&num); Enter a number: 4
4 is even number
if(num%2==0)
{
printf(“%d is even number”,num);
}
return 0;
}
if-else statement:
In general it can be used to execute one block of statement among two blocks, in C language if
and else are the keyword in C.
Syntax:
if(expression)
{
else
Flowchar
t:
In the above syntax whenever condition is true all the if block statement are executed remaining
statement of the program by neglecting else block statement. If the condition is false else block statement
remaining statement of the program are executed by neglecting if block statements.
Example:
#include<stdio.h>
void main()
{
int age;
printf(“enter age:”)
scanf(“%d”,&age);
Output:
if(age>=18) Enter age: 18
Eligible to vote
{ Enter age: 17
Not eligible to vote
printf(“age:%d”,age);
printf(“eligible to vote” );
}
else
{
printf(“age:%d”,age);
printf(“not eligible to vote” );
}
Nested if:
When an if else statement is present inside the body of another “if” or “else” then this is called
nested if else.
Syntax of Nested if else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Flowchart:
EXAMPLE:
#include<stdio.h>
void main() Output:
Enter age and salary: 55 55000
{ 65000
int age, salary;
printf(“enter age and salary”);
scanf(%d %d”, &age,&salary);
if(age>50)
{
if(salary<60000)
{
salary=salary+10000
;printf(“%d”,salary);
}
else
{
salary=
salary+5000;
printf(“%d”,salary);
}
}
else
{
salary=salary+1000;
printf(“%d”,salary);
}
printf(“end of program”);
getch();
}
Switch:
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax:
switch(expression/variable)
{
case value1:
statements;
break;//optional
case value2:
statements;
break;//optional
default:
statements;
break;//optional
}
Rules for apply switch:
1. With switch statement use only byte, short, int, char data type.
2. You can use any number of case statements within a switch.
3. Value for a case must be same as the variable in switch
Flowchart:
Example:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
// declaration of local variable op;
int op, n1, n2;
printf (" enter 2 number: ");
scanf(%d %d”,&n1,&n2);
printf (" \n 1 Addition \t \t 2 Subtraction \n 3 Multiplication \t 4 Division \n 5 Exit \n \n Please,
Make a choice ");
scanf ("%d", &op); // accepts a numeric input to choose the operation
switch (op)
{
case 1:
printf ("sum is :%d ",n1+n2);
break;
case 2:
printf ("difference is :%d ",n1-n2);
break;
case 3:
printf ("multiplication :%d ",n1*n2);
break;
case 4:
printf ("division :%d ",n1/n2);
break;
case 5:
printf ("exit”);
break;
default:
printf(“enter the number between 1 to 5:”);
}
}
LOOPING STATEMENTS
Sometimes it is necessary for the program to execute the statement several times, and C loops
execute a block of commands a specified number of times until a condition is met.
What is Loop?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do a task
tens of thousands of times. Every programming language has the feature to instruct to do such repetitive
tasks with the help of certain form of statements. The process of repeatedly executing a collection of
statement is called looping . The statements get executed many numbers of times based on the condition.
But if the condition is given in such a logic that the repetition continues any number of times with no
fixed condition to stop looping those statements, then this type of looping is called infinite looping.
C supports following types of loops:
• while loops
• do while loops
• for loops
while loops:
C while loops statement allows to repeatedly run the same block of code until a condition is met.
while loop is a most basic loop in C programming. while loop has one control condition, and executes as
long the condition is true.
The condition of the loop is tested before the body of the loop is executed, hence it is called an
entry-controlled loop.
Syntax:
while (condition)
{
statement(s); Increment statement;
}
Flowchart:
Flowchart:
Output:
1 2 3 4 5 6 7 8 9 10
Do..while loops:
C do while loops are very similar to the while loops, but it always executes the code block at least
once and furthermore as long as the condition remains true. This is an exit- controlled loop.
Syntax:
do{
statement(s);
}while( condition );
Flowchart:
EXAMPLE:
#include<stdio.h>
void main ()
{ Output:
int i=1; 1 2 3 4 5 6 7 8 9 10
clrscr();
do
{
printf(“%d”,i);
i++;
} while(i<=10);
getch();
}
For loop:
C for loops is very similar to a while loops in that it continues to process a block of code until a
statement becomes false, and everything is defined in a single line. The for loop is also entry-controlled
loop.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Flowchart:
Example:
#include<stdio.h>
void main ()
{ Output:
int i; 1 2 3 4 5 6 7 8 9 10
clrscr();
for(i=1;i<=10;i++)
{
printf(“%d”,i);
getch();
}
PRE-PROCESSOR DIRECTIVES
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros. Preprocessor directives are
executed before compilation.
• We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
compile it using below command.
$ gcc –Wall filename.c –o filename
The option -Wall enables all compiler’s warning messages. This option is recommended to generate
bettercode. The option -o is used to specify output file name. If we do not use this option, then an output
file with name a.out is generated.
After compilation executable is generated and we run the generated executable using below
command.
$ ./filename
What goes inside the compilation process?
Compiler converts a C program into an executable. There are four phases for a C program to
become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current directory along with the
executable.
$gcc –Wall –save-temps filename.c –o filename
The following screenshot shows all generated intermediate files.
Let us one by one see what these intermediate files contain
Pre-processing:
This is the first phase through which source code is passed. This phase include:
• Removal of Comments
• Expansion of Macros
• Expansion of the included files.
The preprocessed output is stored in the filename.i. Let’s see what’s inside
filename.i:using $vi filename.i
In the above output, source file is filled with lots and lots of info, but at the end our code is
preserved.
Analysis:
• printf contains now a + b rather than add(a, b) that’s because macros have expanded.
• Comments are stripped off.
• #include<stdio.h> is missing instead we see lots of code. So header files has been
expanded andincluded in our source file.
Compiling:
The next step is to compile filename.i and produce an; intermediate compiled output file
filename.s.
This file is in assembly level instructions. Let’s see through this file using $vi filename.s
Assembly:
In this phase the filename.s is taken as input and turned into filename.o by assembler.
This file contain machine level instructions. At this phase, only existing code is converted into
machine language, the function calls like printf() are not resolved. Let’s view this file using $vi
filename.o
Linking:
This is the final phase in which all the linking of function calls with their definitions are
done. Linkerknows where all these functions are implemented.
Linker does some extra work also, it adds some extra code to our program which is
required whenthe program starts and ends.
For example, there is a code which is required for setting up the environment like passing
commandline arguments. This task can be easily verified by using $size filename.o and $size
filename.
Through these commands, we know that how output file increases from an object file to
an executable file. This is because of the extra code that linker adds with our program.