C Unit 1 Notes
C Unit 1 Notes
3 Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, 1st Edition,
Pearson Education, 2013.
Online Resources
1 Introduction to programming in C - Course (nptel.ac.in)
2 https://www.udemy.com/topic/c-programming/
ALGORITHM
The step-by-step procedure to solve any logical and mathematical problem is called an Algorithm.
Should be written in simple English
Each and every instruction should be precise and unambiguous.
Instructions in an algorithm should not be repeated infinitely.
Algorithm should conclude after a finite number of steps.
Should have an end point
Derived results should be obtained only after the algorithm terminates.
Characteristics of an algorithm.
Advantages of Algorithm
Constituents of algorithms
The three main constituents of algorithms—Sequence, Selection, and Repetition
Sequence:
Sequence means executing instructions in a specific order.
Example
Description: To find the sum of two numbers.
1. Start
2. Read the value of ‘a’
3. Read the value of ‘b’
4. Calculate sum=a+b
5. Print the sum of two number
6. Stop
Selection (if-else):
Selection means making decisions based on conditions.
It is also called as decision structure
Basic structure:
IFCONDITION is TRUE then
perform some action
ELSE IF CONDITION is FALSE then
perform some action
The conditional control flow is explained with the example of finding greatest of two numbers.
Example
Description: finding the greater number
1. Start
2. Read a
3.Read b
4. If a>b then
4.1. Print a is greater else
4.2. Print b is greater
5. Stop
Repetition (loops):
Repetition means repeating actions using loops.
Basic Structure:
Repeat untilCONDITIONis true Statements
Example
Description: to print the values from 1 to n
1. Start
2. Read the value of ‘n’
3. Initialize i as 1
4. Repeat step 4.1 until i< n
4.1. Print i
5. Stop
FLOWCHART:
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes, diamonds,
and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols
S.No Name of Symbo Type Description
symbol l
1. Terminal Oval Represent the start and
Symbol stop of the program.
Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for
variouspurposes.
Efficient Coding
The flowcharts act as a guide or blue print during the system analysis and program
development phase.
Systematic Testing and Debugging
The flowchart helps in testing and debugging the program
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart.
It helps the programmer to put efforts more efficiently on that part.
Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case
flowchart becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re-
drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
PSEUDOCODE:
Example:
Pseudocode: To find sum of two
numbers READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to
read theinput, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF,
ELSE, ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:
Pseudocode: Find greatest of two
numbers READ a, b
IF a>b then
PRINT a is greater
ELSE ENDIF
PRINT b is greater
5. Keep statements language independent.
Pesudocode must never written or use any syntax of any programming language.
Advantages of Pseudocode
Can be done easily on a word processor
Easily modified
Implements structured concepts well
It can be written easily
It can be read and understood easily
Converting pseudocode to programming language is easy as compared with flowchart
Disadvantages of Pseudocode
It is not visual
There is no standardized style or format
Algorithm
Step-1 Start
Step-4 SUM = A + B
Step-5 Display SUM
Step-6 Stop
6
2. Algorithm & Flowchart to find Area and Perimeter of Square
Algorithm
Step-1 Start
Step-2 Input Side Length of Square say L
Step-3 Area = L x L
Step-4 PERIMETER = 4 x L
Step-5 Display AREA, PERIMETER
Step-6 Stop
7
3.Algorithm & Flowchart to find the smallest of two numbers Algorithm
Step-1 Start
Step-2 Input two numbers say NUM1,NUM2
8
4.Addition of two numbers
Pseudo code Flowchart
READ a
Start
READ b
Result c=a+b
PRINT c
Print a is greater
9
6.Find the greater number
IF a>b THEN
PRINT a is greater a=10,b=20
Print a is greater
Print b is greater
10
11
C INTRODUCTION:
The programming language “C‟ was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. Although C was initially developed for writing system software, today it has become such a
popular language that a variety of software programs are written using this language.
The greatest advantage of using C for programming is that it can be easily used on different types
of computers. Many other programming languages such as C++ and Java are also based on C which means
that you will be able to learn them easily in the future. Today, C is widely used with the UNIX operating
system.
APPLICATION OF C:
OPERATING SYSTEM
EMBEDDED SYSTEM
GUI(GRAPHICAL USER INTERFACE)
NEW PROGRAMMING PLATFORMS
GOOGLE
MYSQL
ASSEMBLERS
DRIVERS
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:
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 uselater.
2. Link section:
The link section provides instructions to the compiler to link functions
from the system library such as using the #includedirective.
3. Definition section:
The definition section defines all symbolic constants such using
the #define directive.
4. 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.
5. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. 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.
6. 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.
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
}
VARIABLES
Variables are containers for storing data values, like numbers and characters.
In C, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Characters are surrounded by single quotes
Syntax
type variableName = value;
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
\” double quote tab
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.
Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True
Truth table of Logical Operator
In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.
Syntax:
variable++;
Example:
#include<stdio.h>
#include<conio.h>
void main() Output:
{ Pre-increment x::10
int x,i; i=10; i::10
x=++i; Post-increment x::10
printf(“Pre-increment\n”); i::11
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i++;
printf(“Post-increment\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}
Type of Decrement Operator:
pre-decrement
post-decrement
Pre-decrement (-- variable):
In pre-decrement first decrement the value of variable and then used inside the expression (initialize
into another variable).
Syntax:
--variable;
Example:
#include<stdio.h>
#include<conio.h> Output:
void main() Pre-decrement x::9
{ i::9
int x,i; i=10; Post-decrement x::10
x=--i; i::9
printf(“Pre-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i--;
printf(“Post-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}
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:
Expression 1? Expression 2: Expression 3;
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:
Operator Description
EXPRESSION:
An expression is a sequence of operators and operands that specifies computation of a value.
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
Simple Expressions & Compound Expressions:
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.
Types of Expressions in C
Arithmetic expressions
Relational expressions
Logical expressions
Conditional expressions
Arithmetic Expressions:
The arithmetic expression is evaluated in specific order considering the operator's precedence, and the
result of an expression will be based on the type of variable.
Eg: Z = 2 + 3 - (2 * 4)
Relational Expressions:
Relational operators >, <, ==,!= etc are used to compare 2 operands. Relational expressions consisting of
operands, variables, operators, and the result after evaluation would be either true or false.
Example:
C=a>b
Logical Expressions:
Relational expressions and arithmetic expressions are connected with the logical operators, and the result
after an evaluation is stored in the variable, which is either true or false.
Example:
C= (a+b)>c && a<b
Conditional Expressions:
The general syntax of conditional expression is:
Exp1? Exp2: Exp3
From the given above expressions, the first expression (exp1) is conditional, and if the condition is
satisfied, then expression2 will be executed; otherwise, expression3 will be performed.
Example:
2<3? 2 : 3
Expression evaluation:
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.
EVALUATION OF EXPRESSION
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the arithmetic
expression is evaluated from left to right. There are two priority levels of operators in C.
High priority: * /%
Low priority: + -
The evaluation procedure of an arithmetic expression includes two left to right passes through the entire
expression. In the first pass, the high priority operators are applied as they are encountered and in the
second pass, low priority operations are applied as they are encountered.
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.
Suppose, we have an arithmetic expression as: x = 9 – 12 / 3 + 3 *2 -1
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets changed.
For example, x = 9 – 12 / (3 + 3) * (2 –1)
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3:x=7
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
scanf(“%d %d”,&a,&b);
sum= a+b;
}
FORMATTED OUTPUT FUNCTION:
PRINTF():
The printf( ) function is used to print data of different data types on the console in a specified
format.
Syntax:
printf(“Control String”, var1, var2, …);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
printf(“enter two numbers:”); Enter two numbers: 5 4
scanf(“%d %d”,&a,&b); Sum is 9
sum= a+b;
printf(“sum is:%d”,sum);
}
UNFORMATTED INPUT FUNCTION:
getchar()
getch()
getche()
gets()
getchar():
This function reads a single character data from the standard input.
Syntax:
variable_name=getchar();
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
Char ch; Ch=a
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];
gets(ch); OUTPUT:
Printf(“ch=%s”,ch); cprogram
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
void main() j
{
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:
char ch; Press any character:
clrscr(); Pressed character is: e
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);
}