PPS Basics
PPS Basics
PPS Basics
History of C Language
The C Language is a general purpose, high level and structured oriented programming
language developed at Bell laboratories in 1972, by Dennis M. Ritchie.
C programming features, where derived from an earlier language called ‘B’ (BCPL- Basic
Combined Programming Language).
C language was invented for implementing UNIX operating system.
In 1978, Dennis Ritchie and Brian Kernighan published the first edition “ The C
Programming Language” and commonly known as “K & R C”
In 1983, the ANSI (American National Standard Institute) established a committee to
provide a modern, comprehensive definition of C. The resulting definition is the ANSI C,
completed in 1988.
Features of C Language
The following are the standard features of C Language as follows.
1. Portability: Programs written in C language can be run on any compiler with little or no
modifications of a program.
2. Flexibility: C language has number of reserved keywords, which helps the programmers
to take control over the usage of language and to modify the structure of program.
3. Modularity: C language provides feature of modularity, i.e. we can breakdown a large
program into manageable modules. This feature provides easy to understand and
debugging of the program will become faster.
4. Robustness: C language is a robust language, with rich set of built-in functions and
operators that can be used to write any complex programs.
5. Extensibility: In C language program, the new features can be added at any time by the
programmer to the existing program.
6. Efficiency and effectiveness: Programs written in C language are fast and efficient, due
to the variety of data types and powerful operators.
Applications of C Language
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to
develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11
computer in 1972.
Documentation Section: It consists of a set of comment lines giving the name of the program
and other details.
Preprocessor Directives: This section contains header file section, it provides instructions to
the compiler to link functions from the system library and macro definition section, used
defines all symbolic constants.
Function Prototyping: This includes nature of the functions, such as return type, name of
function and list of arguments.
Main Function: Every C program must have one main function section. This section contains
two parts, declaration and executable part. Declaration Part (i.e. Local variable Declaration)
declares all the variables used in the executable part. There should be at least one statement in
the executable part (i.e. Code of the Program) which contains instructions to perform certain
task.
The declaration and executable part must appear between the opening and closing braces. All
statements in the declaration part should end with the semicolon.
Functions (Sub Programs): The Subprogram Section contains all the user defined functions that
are called in the main function. It is a reusable block of statements that are executed upon
calling from the main function by the function name. A program may have any number of user
defined functions.
Comments in C Program
Comments are non-executable code used to provide documentation to the program, by the
programmer.
Comments provide clarity to the C source code allowing others to better understand
what the code was intended to accomplish and greatly helping in debugging the code.
Comments are especially important in large projects containing hundreds or thousands
of lines of source code or in projects in which many contributors are working on the
source code.
1. Single Line Comments: We can create a comment on a single line in the following ways.
2. Multiple Line Comments: We can create a comment on multiple lines using /* */.
For example: /*
* Author: TechOnTheNet.com
* Purpose: To show a comment that spans multiple lines.
* Language: ANSI C */
C Language Syntax Rules
C language syntax specifies rules for sequence of characters to be written in C language. The rule specify
how character sequence will be grouped together to form tokens. A smallest individual unit in C
program is known as C Tokens. Tokens are keywords, identifiers, constants, variables or any symbol
which has some meaning in C language. A C program can also be called as collection of various tokens.
C is a case sensitive language, so all C instructions must be written in lower case letter.
All C statement must be end with a semicolon.
Whitespace is used in C to describe blanks and tabs.
Whitespace is required between keywords and identifiers.
Input Functions: In any programming language, input means to feed some data into the
program. This can be given in the form file or from the command line. Some of input functions
are:
1. Scanf (): This function is used to read character, string, and numeric data from keyboard.
The format string must be a text enclosed in double quotes. It contains the information for
interpreting the entire data for connecting it into internal representation in memory.
The argument list contains a list of variables each proceeded by the address operator (‘&’) and
separated by comma.
2. getchar (): This function reads a single character at a time from the command line or
from the file.
It returns the unsigned char that they read. If end-of-file or an error is encountered then
getchar () functions return EOF.
3. gets(): It reads characters from the standard input (stdin) and stores them as a C string
into string variable, until a newline character or the end-of-file is reached.
Output Functions: In any programming language, output means to display some data on
screen, to printer or to any file. C programming language provides set of built-in functions to
output required data.
2. putchar(): This functions outputs or prints a single character on the screen at a time.
Syntax: putchar(variable_name);
3. puts(): This function writes or puts a line of string on the screen at a time.
Syntax: puts(variable_name);
NOTE:
printf() returns the number of characters printed by it and scanf() returns the number
of characters read by it.
scanf() stops reaching characters when it encounters a blank space, but gets() reads a
space as a character too.
C Tokens
C programs contain many elements which are identified by the compiler, are known as tokens.
Tokens can be categorized as,
1) Keywords
2) Identifiers
3) Variables
4) Constants
5) Special symbols
6) Operators
For example, consider following program,
void main()
{
int x, y, sum;
x = 5, y = 10;
sum = x + y;
printf (“Sum = %d\n”, sum);
}
From above program C Tokens can be categorized as follows:
Identifier: main
Special symbols: {,}, (,)
Keyword: int
Variables: x, y, sum
Operators: +, =
Tokens: main, {,}, (,), int, x, y, sum
1. Keywords
In C language identifiers are the names, which are given to variables, user-defined
functions and arrays.
Syntax Rules:
1. An identifier should only have alphanumeric characters (a-z, A-Z, 0-9) and
underscore (_) symbol.
2. The first character of an identifier should only have alphabets (a-z, A-Z) or
underscore (_) symbol.
3. Identifiers are case sensitive in C language. For example, “name” and “Name”
are two different identifiers in C language.
4. Keywords are not allowed to be used as identifiers.
5. Special characters (Ex: ;, ., white spaces, slash etc.,) are not permitted to use as
identifiers.
Identifier keyword
Identifiers are names that are given to C take some reserved word called keyword,
various program elements, such as variable, they have predefine meaning in C.
function and arrays.
Identifiers consist of letters and digits. Keyword consist only letter.
Identifier’s first character must be a letter. Keyword’s all character is letter.
Identifiers Upper and lowercase letter is use. Keywords are all lowercase.
Upper and lowercase are not equivalent. Upper and lowercase are also not
equivalent.
Like: X, sum_5, _weather, 9_name etc. Like: auto, short, long etc.
But 4th is not identifier because identifier
first character must a letter.
3. Variables
A variable is a name that is used to store a value. Variable are simply names used to
refer some locations in memory i.e. a location that holds a value.
Variable declaration: Declaration of variable must be done before they are used in the
program. It tones three things:
Example: auto int sum, age, total; (or) int sum, age, total;
Example:
NOTE: the name of variable must not change, but the value stored in the variable may change
during execution of the program.
C Constants are like normal variables. But, only difference is their values cannot
be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals.
Constants may be belonging to any of the data type.
Integer Constants:
An integer constant can be a decimal, octal, or hexadecimal constant. A prefix specifies the base
or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. Some examples are:
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Rules of floating constants:
Symbols other than the alphabets and digits and white-spaces are called special symbols. C has
following list of special symbols.
Symbol Meaning
~ Tilde
! Exclamation mark
# Number sign or hash
$ Dollar sign
% Percent sign
^ Caret
& Ampersand
* Asterisk
( Left parenthesis
) Right parenthesis
_ Underscore
+ Plus sign
| Vertical bar
\ Backslash
` Apostrophe
- Minus sign
= Equal to sign
{ Left brace
} Right brace
[ Left bracket
] Right bracket
: Colon
" Double Quotation mark
; Semicolon
< Less than
> Greater than
? Question mark
, Comma
. Period
/ Forward Slash
Operators
Operators are symbols that trigger an action when applied to C variables and other objects.
The data items on which operators act upon are called operands.
Depending on the number of operands that an operator contains, operators can be classified as
follows:
1. Unary Operators: Those operators that require only single operand to act upon are
known as unary operators.
2. Binary Operators: Those operators that require two operands to act upon are called
binary operators.
3. Ternary Operators: These operators require three operands to act upon.
1. Primitive Data Types: Primitive data types are predefined data types, which are
supported by the programming language. For example, integer, character, and string are
all primitive data types.
Data Types and its range:
2. Derived Data Types: The data types which derived from fundamental or primitive
data types is known as derived data types. For example, arrays, functions, structures
and unions etc.
3. Void Data Type: void data type means “no values” (or) “empty” i.e. it take or returns
empty value. The void data type usually used with functions to specify its return type or
with parameters list.
4. Enumerated Data Type:
Specifier Meaning
%d (or) %i Used to read and displays integer values
%f Used to read and display real values in decimal notations. Example:
10.256
%e Used to read and display real values in scientific notation. Example:
3.6e7
%E Used to read and display real values in scientific notation with capital
letter. Example: 3.6E7
%c Used to read and display characters
%lf Used to read and display long double values
%x Used to read and display hexadecimal values in lowercase.
%X Used to read and display hexadecimal values in uppercase.
%0x Used to read and display octal values
%u Used to print the addresses of a variable.
Type Casting
Converting one type of data into another type is known as type casting. There are two
types of type conversions:
1. Implicit type casting: This casting is also known as automatic type casting i.e.
type casting done by compiler automatically, when the lower data type is assigned
to higher data type.
Example:
int x=20;
float y;
y=x;
printf(“%d”=”f”, x,y); // here, there is no loss of data
2. Explicit type casting: This casting is also known as type casting. Explicit type
casting uses unary type cast operator. This is useful when higher data type value is
trying assigned to lower data type value, because there may be a loss of data. So,
the compiler will also show an error like “possible loss of data”.
Example:
float x=20;
int y,z;
y=(int)(x+20); // here float value is converted to int type
z=(int) (x+50);
Global variables: Variables whose existence is known to the both main() as well as other
functions are called global variables. Global variables are declared outside the main() and other
functions.
The following Program illustrates the concept of both local as well as global variables.
Example:
#include<stdio.h>
int x=50; // global variable declaration
int y=25; // global variable declaration
int add(); // function prototyping
void main(){
int x=10; // local variable declaration
int y=20; // local variable declaration
printf(“sum of two numbers=%d\n”,x+y);
sum=add();
printf(“sum of two numbers=%d\n”,sum);
}
int add(){
return x+y;
}
Output:
Storage Classes
Every variable in C programming has two properties: type and storage class. Type refers to the
data type of variable whether it is character or integer or floating-point value etc. And storage
class determines how long it stays in existence.
The storage class determines two properties of a variable:
1. Scope of a variable: Which specifies the part of the program over which a variable
name is visible, i.e. the variable is accessible by name.
2. Life time (or) extent of a variable: Which specifies the part of memory where
storage is allocated for a variable and how long the storage allocation continues to
exist.
Features:
auto storage class variables are stored in main memory i.e. RAM.
Scope of variables is within a block or function.
Lifetime of variables should exist as long as control remains in the block.
Default initial value stored in variables is garbage value.
Example:
#include<stdio.h>
void main()
{
auto int a=10;
{
auto int a=100;
printf(“internal block value=%d\n”, a);
}
printf(“external block value=%d\n”, a);
}
Output:
NOTE: The example above defines two variables within the same storage class. “auto” can only
be used within functions, i.e., as a local variables.
Features:
Example:
#include<stdio.h>
void main()
{
int a=100, b=100;
register int sum;
sum=a+b;
printf(“Addition=%d\n”, sum);
}
Output:
Addition=200
3. External (extern) or global storage class
Features:
Example:
#include<stdio.h>
int a=150; // global variable declaration
void display(); //function prototyping
void main()
{
extern int a; //explicit declaration
printf(“value in main block=%d\n”, a);
display();
}
void display(){
extern int a;
printf(“value in display block=%d\n”, a);
}
Output:
NOTE
Declaration within the function indicates that the function uses external
variable.
Functions belonging to same source code do not require declaration (no
need to write extern).
If variable is defined outside the source code, then declaration using extern
keyword is required.
Features:
Example:
#include<stdio.h>
void display(); //function prototyping
void main()
{
display();
display();
display();
}
void display(){
static int a=0; //declaration and only once executed
printf(“changing value=%d\n”, a);
a=a+10;
}
Output:
changing value=0
changing value=10
changing value=20
Summary of storage classes
C Operators
Operator is a symbol that is used to perform mathematical or logical manipulations in the
program. C language has the following operators:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Ternary (or) conditional operator
7. Increment or decrement operators
8. Special operators
3. Logical operators: These operators are used to compare two or more relational
expressions.
NOTE
Left shifting one time means, it is equal to multiplying the value by 2 one time.
Right shifting one time means, it is equal to dividing the value by 2 one time.
5. Assignment operators: This operator is used to assign the values for the variables in
the programs.
If the condition is true then expression1 gets evaluated otherwise (i.e. if condition false)
expression2 gets evaluated.
Associativity is used when two or more operators of same precedence operators appeared in
an expression. Associativity can be either left to right or right to left. For example, 100/10*10 is
calculated as (100/10)*10 not as 100/ (10*10), due having the same precedence of operators
(/, *).
Operator precedence & Associativity are listed in the following table and this table is
summarized in decreasing Order of priority i.e. topmost operator has highest priority and
bottommost operator has Lowest Priority.
Precedence Operator Associativity
1 ( ) ,[ ], . ,->, operand++ ,operand -- Left to right
2 ++operand, -- operand, Unary+, unary-, Right to left
!,~,
(type),*,&,sizeof()
3 *, /, %
4 +, -
5 << , >>
6 < , <=, >, >=
7 ==, != Left to right
8 &
9 ^
10 |
11 &&
12 ||
13 ?: Right to left
14 =, +=, -=, *=, /=, %=,>>=, <<=, &=, Right to left
^=, |=
15 , Left to right
Example: x = 3 * 2 / 2 + 3 / 2 + 2 – 2 + 3 * 2
= (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)
= (3 + 1 + 2) – 2 + 6
= (6 – 2) + 6
=4+6
= 10
Important definitions
Unary operator: A unary operation is an operation with only one operand, i.e. an operation with
a single operand. For example, post / pre increment operators.
Binary Operator: A Binary operator is one which has two operands. For example, addition, subtraction.
1. if statement
The if stamen is powerful decision making stamen and is used to control the flow of
execution of statements.
Syntax:
if(condition)
{
Statement-1;
……………..
……………..
Statement-n;
}
statements;
If the condition is true, the statements block will be executed otherwise the
statements block will be ignored or skipped. And the execution will jumped to the
remaining statements of the program.
Example:
#include<stdio.h>
void main()
{
int i;
printf(“Enter any value:”);
scanf(“%d”,&i);
if(i<0)
{
printf(”Negative number”);
}
}
Output:
Syntax:
if(condition)
{
true block statments;
}
else{
false block statements;
}
statements;
If the expression is true, then the true block statements are executed; if the
condition is false, then false block statements are executed.
#include<stdio.h>
void main()
{
int marks=50;
if(marks>=35)
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}
Syntax:
if(condition1)
{
statements1;
}
else if(condition2)
{
statements2;
}
else if(condition3)
{
statements3;
}
else {
default statements;
}
#include<stdio.h>
void main ( )
{
int num;
printf(“Enter a number:”);
scanf(“%d”,&num);
if( num > 0 )
printf("\n Number is Positive");
else if( num < 0 )
printf("\n Number is Negative");
else
printf("\n Number is Zero");
}
Explanation: In the above program first condition is tested i.e. number is checked
with zero. If it is greater than zero then only first if statement will be executed and
after the execution of if statement control will be outside the complete if-else
statement i.e. program termination.
Suppose in first if condition is false then the second condition will be tested i.e. if
number is not positive then and then only it is tested for the negative. And if number
is neither positive nor negative then it will be considered as zero.
When series of decisions are involved, we may have to use more than one if
statement in nested form.
if(condition1)
{
if(condition2)
{
if(condition3)
{
Statements1;
}
else{
statements2;
}
}
}
statements;
#include<stdio.h>
void main()
{
int i;
printf(“Enter any value:”);
scanf(“%d”,&i);
if(i>=0)
{
if(i<=10)
{
printf(”u have entered b/w 0 and 10”);
}
}
else{
printf(“entered other than 0 and 10”);
}
}
Output:
Switch Statement
The switch statement is a multi way branch statement. In the program there is a possibility to
make a choice from number of options, then this structured statement is useful.
Syntax:
switch(expression)
{
case value1: statements1;
break;
case value2: statements2;
break;
…
…
When the switch is evaluated, the value of expression is compared against the value1,
value2,…,valuen. If a value matches with any case, then the block of statements are executed.
The break statement at end of each block signal the end of particular case and causes an exit
from the switch statement and transfers control to the remaining statements of the program.
The default case is executed when value of expression does not match with any of the case
values in switch statement.
Example:
#include<stdio.h>
void main()
{
int marks=35,i=1;
switch(i)
{
case 1: if(i >= 35)
printf(“pass”);
else
printf(“failed”);
break;
}
}
Output:
pass
Loop Statements
Loop is defined as a block of statements, which are repeatedly executed for certain number of
times.
The condition is tested after executing the statements of the loop, i.e. the
statements are executed unconditionally at least once before testing of
condition.
When the execution reaches to condition; it tested and if the condition true then
again and again executes the statements of the loop repeatedly until the
condition is satisfied.
while loop is an entry controlled loop statement i.e. the condition is tested before start
of the loop statements execution, if the condition is not satisfied then statements of the
loop will not be executed.
Syntax:
while(condition)
{
statement1;
…………………..
…………………..
statementn;
}
statements;
Example:
#include<stdio.h>
void main()
{
int i=0;
while(i<=10)
{
printf(“%d\t”,i++);
}
}
Output:
0 1 2 3 4 5 6 7 8 9 10
2. do.. while loop statement
do.. while loop statement is an exit controlled loop statement, i.e. the condition tested
after executing the statements of the loop, it happens repeatedly until the condition is
satisfied.
Syntax:
do
{
statement1;
…………………..
…………………..
statementn;
}while(condition);
statements;
Example:
#include<stdio.h>
void main()
{
int i=0;
do
{
i=i+1;
printf(“%d\t”,i);
}while(i<=10);
}
Output:
1 2 3 4 5 6 7 8 9 10 11
for loop statement is an entry controlled loop, i.e. the condition is tested before start of
the loop statements execution. If condition is not satisfied then the statements of loop
will not be executed.
Syntax:
1) The variable initialization sets loop to an initial value and this statement is
executed only once.
2) The condition is a relational expression on the variable initialization; it
determines number of iterations to be performed on the statements of the loop
i.e. the statements of the loop is executed until the condition is satisfied.
3) When the statements of loop are executed, the control is transferred back to last
statement in for loop and performs increment or decrement on a variable. And
the new value of a variable is again tested with the condition; if condition is
satisfied then again executes the statements of the loop. This happens
repeatedly again and again until the condition is satisfied.
Example:
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
printf(“%d\t”,i);
}
}
Output:
0 1 2 3 4 5 6 7 8 9 10
1. break statement
2. continue statement
3. goto statement
1. break statement:
By using this jump statement, we can terminate the further execution of the program and
transfer the control to the end of the loop.
This statement always used with the control statements like switch case, while, do..
while, for loop etc.
Syntax: break;
Example:
#include<stdio.h>
void main()
{
int i=0;
while(i<=100)
{
if(i==10)
break;
i++;
printf(“%d\t”,i);
}
Printf(“Bye”);
}
Explanation: In the above program while is used to print values from 0 to 100, but in
this program break statement is used so, we get the output as 1 2 3 …. 10 Bye. Here, each time
‘i’ value is compared with 10, if condition is true then break statement is executed and the
control comes out of while loop and prints bye.
2. continue statement:
The continue statement is exactly opposite to break statement. It is used for continuing
next iteration of the loop statements. When continue statement occurs in the loop, it does not
terminate but it skips the statements after continue statement.
Syntax: continue;
Example:
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
if((i==2) || (i==4) || (i==6))
continue;
else
printf(“%d\t”,i);
}
}
3. goto statement:
The goto statement provides a method of transfer control to a labeled point in the
program. The goto statement requires a destination label declared as label_ name:
1. Forward branching: if the label_name: is placed after the goto label then goto can
be referred as forward branching statement.
Syntax:
goto Label;
statements;
………………….
………………….
Label: statement;
2. Backward branching: if the label_name: is placed before the goto label then goto
can be referred as backward branching statement.
Syntax:
Label:
statements;
………………….
………………….
goto Label;
Advantage:
It gives the power to jump to any part of program.
Disadvantages:
It reduces the readability of the program.
It becomes difficult to trace the control flow of a program.
Difficult to understand program logic.
Using goto statement is considered as poor programming practice. So try to
avoid goto statement as possible as you can.