Basic Concepts of C Language
Basic Concepts of C Language
PROGRAMMING IN C
UNIT - 1
BASICS OF C PROGRAMMING
Introduction to programming paradigms - Structure of C
program - C programming: Data Types – Storage classes
- Constants – Enumeration Constants - Keywords –
Operators: Precedence and Associativity - Expressions –
Input / Output statements, Assignment statements –
Decision making statements - Switch statement -
Looping statements – Pre-processor directives -
Compilation process
INTRODUCTION
• C is a
• General-purpose
• Block-structured
• Procedural
• Case-sensitive
• High level programming language
• Developed by Dennis Ritchie
History
• 1960 : -
• ALGOL was found by International group of computer users.
• COBOL was found for commercial application usage.
• FORTRAN was found for scientific applications.
• In 1967: -
• Basic Combined Programming Language (BCPL)
• developed by Martin Richards at Cambridge University.
• a single language which can program all possible applications,
• In 1970: -
• a language called B was developed by Ken Thompson at
AT & T’s Bell Labs.
History
• In 1972: -
• Dennis Ritchie at Bell Labs developed a language with some
additional features of BCPL and B called C.
• In 1978: -
• Publication of The C Programming Language by Kernighan & Ritchie
caused a revolution in the computing world.
• In 1983: -
• the American National Standards Institute (ANSI) established a
committee to provide a modern, comprehensive definition of C. The
resulting definition, the ANSI standard, or "ANSI C", was completed
late 1988.
Programming languages
• Various programming languages
• Machine language
• Assembly language
• High-level language
• Machine language
• Natural language of a particular computer
• Consists of strings of numbers(1s, 0s)
• Instruct computer to perform elementary
operations one at a time
• Machine dependent
Programming languages
• Assembly Language
• E.g. add overtime to base pay and store result in gross pay
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY
Programming languages
• High-level languages
• To speed up the programming process
• Single statements for accomplishing substantial tasks
• Compilers - convert high-level programs into machine
language
• E.g. add overtime to base pay and store result in gross pay
grossPay = basePay + overtimePay
Basics of C Environment
• Development environment has 6 phases
Edit - Writing the source code by using some IDE or editor
Pre-processor - Already available routines
Phase 5 Loader
Puts program
in memory
Primary memory
Takes each
Phase 6 CPU instruction
and executes it,
storing
new data values
Executing a C Program
Steps involved in execution are
• Linking the program with functions that are needed from the C
library
Source
Code
Compile
Object
Code
Link section
Definition section
Subprogram section
(user defined function)
Simple C Program
/* A first C Program*/
#include <stdio.h>
void main()
{
printf("Hello World \n");
}
C Character Set
• Characters are the basic building blocks in C program,
equivalent to ‘letters’ in English language
• Characters can be used to form words, numbers and
expressions
• Characters in C are grouped into following categories
• Letters ex:a…z,A…Z
• Digits ex:0…9
• Special characters ex:,,&,@,_,+,-,…..
• White spaces ex:blank space
horizontal tab
new line…….
C Tokens
• In a passage of text, individual words and punctuation marks are
called tokens
• In a C source program, the basic element recognized by the
compiler is the "token."
• C Tokens are
Keywords - int, float, while
Identifiers - sum, main
Constants - 100, -55.5
Strings - “ABC”, “Hello”
Operators - +, -, *, /, ++
Special symbols - {, },[, ]
Keywords
• Keyword is a reserved word that has a particular meaning in
the programming language.
• Have special meaning to the compiler, cannot be used as
identifiers in our program.
• Keywords serve as basic building blocks for program statement
• Keywords must be written in lowercase
• There are 32 keywords available in C
Some Keywords
Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers
• Refer to the names of variables, functions and arrays
• User defined names and consist of a letters and digits,
with a letter as a first character
Rules for Identifiers
• First character must be an alphabet
• Must consist of only letters, digits and underscore
• Maximum number of characters is compiler
dependent
• Cannot use a keyword
• Must not contain white space
• Case sensitive
Identifiers
Examples of legal identifier:
Example
sum, avg_wt, item
VARIABLE DECLARATION
• Declaration of variables should be done in the declaration part of
the program
• Variables must be declared before they are used in the program
• Declaration provides two things:
• Compiler obtains variable name
• Tells the compiler about the data type of the variable being declared
and helps in allocating the memory
VARIABLE DECLARATION
Syntax:
data_type variable_name
Example:
int age;
char ch;
float avg;
int a,b,c;
VARIABLE DECLARATION
Initializing Variables
• Variables declared can be assigned or initialized using an
assignment operator ‘=‘
Syntax:
variable_name = constant;
or
data_type variable_name = constant;
Example:
int age; char ch=‘A’;
age=10; float avg=10.5;
Constants
• Constants refers to fixed values that do not change during the execution a program
• It cannot be placed on the left side of the assignment operator
• Types
• Literal constants
• Integer
• Floating point
• Character
• String
• Qualified constants
• Symbolic constants
Types of Constants
Numeric Constants
Character Constants
Fractional Form
• Must have at least one digit
• Should have a decimal point
• Can be either positive or negative
• No special characters and blank spaces are allowed
• By default it is assumed to be of type double e.g. 23.45
Exponential Form
• Two parts : mantissa part and exponent part separated by e or E
• Mantissa part can be either +ve or –ve
• Mantissa part should have at least one digit
or –ve
• Exponent part cannot have a decimal point
• No special characters and blank spaces are allowed within the
mantissa and exponent part
Ex: -2.5E12, -2.5e-12, 2e10
Character Literal Constants
• A character literal constant can have one or at
most two characters enclosed within a single
quotes
• Example: ‘A’, ‘a’, ‘\n’
• Types:
• Printable character literal constant
• Non-Printable character literal constant
• Represented with help of escape sequence
• An escape sequence consists of a backward slash(\) followed
by a character and both enclosed by single quotes
• An escape sequence is treated as single character
Escape Sequences
Escape Name Meaning
Sequence
\a Alert Sounds a beep
\b Back space Backs up 1 character
\f Form feed Starts a new screen of page
\n New line Moves to beginning of next line
\r Carriage return Moves to beginning of current line
\t Horizontal tab Moves to next tab position
\v Vertical tab Moves down a fixed amount
\\ Back slash Prints a back slash
\’ Single quotation Prints a single quotation
\” Double quotation Prints a double quotation
\? Question mark Prints a question mark
\0 Null character Prints nothing
Backslash Character Example
Program
Output
deghi
#include<stdio.h>
void main()
Hai Hello
{
printf("\nabc");
printf("\rdef");
printf("\bghi\n");
printf("Hai\tHello");
}
Input and Output Functions
Formatted Unformatted
Functions Functions
getch()
scanf() getche()
printf() getchar()
gets()
putch()
putchar()
puts()
Formatted Functions
Formatted Input:
• Input data is arranged in a particular format
• I/P values are taken by using scanf function
• Syntax:
• scanf(“control string”,arg1,arg2…argn) ;
control string - includes format specifications and optional number
specifying field width and the conversion character %
arg1,arg2,… - address of locations where the data are stored
Example: scanf(“%3d%2d”,&a,&b);
Formatted Functions
Formatted Output:
• printf statement displays the information required to
user with specified format
• Syntax:
printf(“control string”,arg1,arg2…argn) ;
control string - field format which includes format
specifications and optional number specifying field width
and the conversion character %, blanks, tabs and newline.
arg1,arg2,… - name of the variables
Example: printf(“%d\t%f\n”,sum1,sum2);
An Example Program
# include<stdio.h>
void main()
{
int num1
float num2;
char ch;
printf (“Enter values:”) ;
scanf(“%d%f%c”, &num1, &num2,&ch);
printf (“\nThe Entered Values are:%d %.2f %c”, num1, num2,ch) ;
}
Output 1:
Enter values: 1342 24.2 a
The Entered Values are: 1342 24.20 a
Format for various output
Flag output justification
+ (right justification) - (left justification)
Width Specifier minimum field width for an output value
short unsigned %u
unsigned hexadecimal %X or %x
unsigned octal %o
Real float %f or %g
double %lf
Character character %c
string %s
Unformatted Functions
Unformatted Input
getch() & getche()
read a alphanumeric characters from the standard input
device such as the keyboard
The character entered is not displayed by getch() function
Example : getch() & getche()
# include<stdio.h>
#include<conio.h>
void main ( )
{
clrscr();
printf (“Enter two alphabets:”) ;
getche();
getch();
}
Output:Enter two alphabets:A
Unformatted Functions
getchar()
• read a character type data from the standard input
device such as the keyboard
• Reads one character at a time till user press the enter
key
Example : getchar()
# include<stdio.h>
#include<conio.h>
void main ( )
{
char c;
clrscr();
printf (“Enter a character:”) ;
c=getchar();
printf(“c=%c”,c);
getch();
}
Output:Enter a character :A
c=A
Unformatted Functions
gets()
• read a string from the standard input device such as the
keyboard until user press the enter key
Example : gets()
# include<stdio.h>
#include<conio.h>
void main ( )
{
char str[10];
clrscr();
printf (“Enter a string:”) ;
gets(str);
printf(“String=%s”,str);
getch();
}
Output:Enter a string :Hello
String=Hello
Unformatted Functions
putch() & putchar()
• Prints any alphanumeric character taken by the
standard input device such as the keyboard
Example:
char ch=‘X’;
putch(ch); or putchar(ch);
Output: X
Unformatted Functions
puts()
• prints the string or character array
Example : puts()
# include<stdio.h>
#include<conio.h>
void main ( )
{
char str[10];
clrscr();
printf (“Enter a string:”) ;
gets(str);
printf (“Entered string:”) ;
puts(str);
getch();
}
Output:Enter a string :Hello
Entered string:Hello
Operators
• An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations
Types of Operators
Arithmetic Operators +, -, *, /, %
Relational Operators <, <=, >, >=, ==, !=
Logical Operators &&, ||, !
Assignment Operators =
Increment and Decrement Operators ++,--
Conditional Operators ?=
Bitwise Operators &,|, ^, <<, >>
Special Operators ,, sizeof, &, * ., ->
Properties Of Operators
• Precedence
• Associativity
Precedence:
• Priority allotted to the operator
Ex: 8+9*2-10
=8+18-10
=26-10
=16
Associativity:
• Expression having operators with equal precedence
• associativity property decides which operation is performed first
Types:Left to Right Right to left
12*4/8%2 x=8+5%2
= 48/8%2 =8+1
= 6%2 =9
=0
Arithmetic Operators
C Operation Algebraic C
#include<stdio.h>
Enter 3 nos. x ,y,z: 40 20 30
#include<conio.h>
x is greatest
void main()
{
int x,y,z;
Enter 3 nos. x ,y,z: 10 40 30
clrscr();
y is greatest
printf(“Enter 3 nos. x ,y,z:”);
scanf(“%d%d%d”,&x,&y,&z);
if((x>y)&&(x>z))
Enter 3 nos. x ,y,z: 10 20 30
z isprintf(“x
greatestis greatest”);
if((y>x)&&(y>z))
printf(“y is greatest”);
if((z>x)&&(z>y))
printf(“z is greatest”);
}
Assignment operators
Operator Example Meaning
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a–b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Increment/Decrement
operators
Operator Example Meaning
condition?expression1:expression2;
Example:
int a, b, c;
...
c = a > b ? a : b; // if a>b "execute" a, else b and assign the result to c
Bitwise Operators
Operator Meaning
| Bitwise OR
^ Bitwise XOR
~ One’s Complement
A | B ( Bitwise OR )
A & B ( Bitwise AND )
0101 0110
0101 0110
0011 0010
0011 0010
---------------------
---------------------
0111 0110
0001 0010
---------------------
---------------------
~ A ( Complement )
A ^ B ( Bitwise XOR ) 0101 0110
0101 0110 ---------------------
0011 0010 1010 1001
--------------------- ---------------------
0 1 1 0 0 10 0
---------------------
Bitwise Operators Example
Let A=0x56
0 1 0 1 0 1 1 0 << 2 0 1 0 1 0 1 1 0 0 0 ( 0x158 )
0 1 0 1 0 1 1 0 >> 1 0 1 0 1 0 1 1 ( 0x2B)
NOTE:
For multiply given number by two, left shifted by one time, i.e., a<<1
For divide given number by two, right shifted by one time, i.e., a>>1
Bitwise Operators Example
Write a program to shift inputed data by three bits left and right
Program
void main()
{
int x,y;
clrscr();
printf(“Enter value of x:”);
scanf(“%d”,&x);
y=x<<3;
printf(“Left shifted data=%d”,y);
printf(“Right shifted data=%d”,x>>3);
}
Output: Enter value of x:16
Left shifted data=128
Right shifted data=2
Special Operators
• C supports some special operators such as comma operator, size of
operator, pointer operators (& and *) and member selection operators (.
and ->).
• The size of and the comma operators are discussed here. The remaining
operators will see in pointer chapter
Comma Operator
• The comma operator can be used to link related expressions together. A
comma-linked list of expressions are evaluated left to right and value of
right most expression is the value of the combined expression.
Example
value = (x = 10, y = 5, x + y);
for (n=1, m=10, n <=m; n++,m++)
t = x, x = y, y = t;
Special Operators
Sizeof Operator
• The operator sizeof gives the size of the data type or variable in
terms of bytes occupied in the memory. The operand may be a
variable, a constant or a data type qualifier.
• The size of operator is normally used to determine the lengths of
arrays and structures when their sizes are not known to the
programmer. It is also used to allocate memory space dynamically to
variables during the execution of the program.
Example
int sum;
m = sizeof(sum); 2
n = sizeof(long int); 4
k = sizeof(235L); 4
Expressions
Arithmetic Expressions
Algebraic
C Expression
Expression
axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
Example
x=a*b–c
y=b/c*a
z = a – b / c + d;
Decision Making - Branching
• Decision making statements are used to skip or to execute a group of
statements based on the result of some condition.
• The decision making statements are,
− simple if statement
− if…else statement
− nested if
− else … if ladder
− switch statement
− goto
• These statements are also called branching statements
Simple if statement
Syntax:
if(condition)
{
Statements;
}
False
if(condition)
True (Bypass)
Statements;
Simple if - Example
# include <stdio.h> Output
void main ()
{ Type a number -50
int number; The absolute value is 50
printf("Type a number:");
scanf("%d",&number);
if (number < 0)
number = -number;
printf ("The absolute value is %d",number);
}
if - else statement
Syntax:
if(condi False
tion)
if(condition)
{ True
True block statements;
} True Block False Block
Statement Statements
else
{
False block statements;
}
if – else Example
# include <stdio.h>
Output
void main ()
{
Type a number 50
The
int
number
num; is positive
printf ("Type a number:");
scanf ("%d", &num);
if (number < 0)
printf(“The number is negative”);
else
printf(“The number is positive”);
}
if – else Example
#include<stdio.h>
Output
void main()
{ Enter a number 125
Int num; The number is ODD
printf ("Enter a number:");
scanf ("%d",&num);
if (num%2==0)
printf ("The number is EVEN.\
n");
else
printf ("The number is ODD.\n");
}
Nested if Statement
• if statement may itself can contain another if statement is known as nested if
statement.
Syntax:
if(condition1)
{
if(condition2)
{
True block statement of condition1 & 2;
}
else
{
False block statement of condition2;
}
}
else
{
False block statements of condition1;
}
Nested if Statement
False
condition1
True
False
if(condition2) False Block Statements of
True condition 1;
True Block Statements of
condition 1 & 2; False Block Statements of
condition 2;
Nested if Example
Output
# include <stdio.h>
void main()
{ Enter 3 numbers:10 25 20
int n1,n2,n3,big; The largest number is: 25
printf (“Enter 3 numbers:");
scanf ("%d %d %d", &n1,&n2,&n3);
if (n1 > n2)
{
if(n1 > n3)
big = n1;
else
big = n3;
}
if(n2 > n3)
big = n2;
else
big = n3;
printf(“The largest number is: %d”,big);
}
Else - if Ladder Statement
Syntax
if (condition1)
statement block 1;
else if (condition2)
statement block 2;
else if (condition3)
statement block 3;
:
:
else if (condition)
statement block n;
else
default statement;
Else - if Ladder Statement
True
If(condition1)
False
True
Else if(condition2)
False Statements1;
True
Else if(condition3)
False Statements2;
Default Statements;
Statements3;
Else - if Ladder Example
#include <stdio.h>
voidOutput
main ()
{
int mark;
Enter mark: 75
printf ("Enter mark:");
Distinction
scanf ("%d", &mark);
if (mark <= 100 && mark >= 70)
printf ("\n Distinction");
else if (mark >= 60)
printf("\n First class");
else if (mark >= 50)
printf ("\n Second class");
else
printf ("Fail");
}
Switch Statement
Syntax
switch ( expression )
{
case value1: program statement;
......
break;
case value2: program statement;
.......
break;
…….
…….
case valuen: program statement;
.......
break;
default: program statement;
.......
break;
}
Switch Statement
Switch (Expression)
Case 1 Statements
Case 2 Statements
Case 3 Statements
Case 4 Statements
Switch Statement Example
#include <stdio.h> break;
void main () case '/':
{ if (num2 != 0)
int num1, num2, result; result = num1 / num2;
char operator; break;
printf ("Enter two numbers:"); default:
scanf ("%d %d", &num1, &num2); printf ("\n unknown operator");
printf ("Enter an operator:"); break;
scanf ("%c", &operator); }
switch (operator) printf (“Result=%d", result);
{ }
case '+':
result = num1 + num2; break; Output
case '-':
result = num1 - num2; Enter two numbers:10 20
break; Enter an operator:+
case '*': Result=30
result = num1 * num2;
Switch Statement Example
#include<stdio.h> case 'i': count++;
#include<conio.h> break;
#include<string.h> case 'o': count++;
void main() break;
{ case 'u': count++;
char st[100]; break;
int i,count=0; }
clrscr(); }
printf("Enter line of text:"); printf("\n Number of vowels: %d",count);
gets(st); getch();
for(i=0;st[i]!='\0';i++) }
{
switch(st[i]) Output
{
case 'a': count++; Enter line of text: Hello World
break; Number of vowels: 3
case 'e': count++;
break;
goto statement
•The goto statement used to transfer the program control unconditionally from
one statement to another statement.
•The general usage is as follows:
•The goto requires a label in order to identify the place where the branch is to
be made.
•A label is a valid variable name followed by a colon.
goto statement example
#include <stdio.h> Output
void main ()
{ Enter a number:5
int n, sum = 0, i = 0;
inc: i++;
sum += i;
if (i < n)
goto inc;
}
Looping statements
• The test may be either to determine whether the i has repeated the
specified number of times or to determine whether the particular
condition has been met.
• Type of Looping Statements are
• while statement
• do-while statement
• for statement
while statement
Syntax
While
False
(test
condition)
while (test condition)
{ True
True While
(test
condition)
False
do..while statement example
#include<stdio.h> Output
void main() Enter the number:275
{ Reversed number is 572
int num=0, rev_num=0;
printf(“Enter the number:”);
scanf(“%d”,&num);
do
{
ld=num%10;
rev_num=rev_num*10+ld;
num=num/10;
} while(num>0);
printf(“\nReversed number is %d”,rev_num);
}
while and do..while comparison
While Do…while
1) Syntax: 1) Syntax:
while(condition) do
{ {
Body of the loop Body of the loop
} }while(condition);
2) This is decision making and 2) This is also -decision making
looping statement and looping statement
3) This is the top tested loop 3) This is the bottom tested loop
4) Loop will be executed atleast
4)Loop will not be executed if the
once even though the condition is
condition is false in first check
false in first check
for statement
■ The for loop is most commonly and popularly used looping statement in C. The
for loop allows us to specify three things about the loop control variable i in a
single line. They are,
■ Initializing the value for the i
■ Condition in the i counter to determine whether the loop should continue or
not
■ Incrementing or decrementing the value of i counter each time the program
segment has been executed.
Syntax
for(initialization; test condition;increment/decrement)
{
body of the loop;
}
for statement
Initialization;
Increment/Decrement;
True
test condition
False
for statement example
// Number 1 to 10 divisible by 2 but not
Output
divisible by 3 and 5
#include<stdio.h>
2
void
4 main()
{8
int i;
for(i=1;i<=10;i++)
{
if(i%2==0&&i%3!=0&&i%5!=0)
printf("%d\n",i);
}
}
for statement example
//12+22+32+…. n2
Output
#include<stdio.h> //<math.h>
void main()
Enter the number:5
{
Sum of series=55
int n, i,sum=0;
printf(“Enter the number:”);
scanf(“%d”, &n);
for(i=1;i <= n;i++)
{
sum = sum + i*i; //pow(i,2)
}
printf(“Sum of series=%d”,sum);
}
break statement
■ Sometimes while executing a loop it becomes desirable to skip a part of
the loop or quit the loop as soon as certain condition occurs.
1) Syntax: 1) Syntax:
break; continue;
2) Takes the control to outside of 2) Takes the control to beginning
the loop of the loop
3) It is used in switch statement 3) It is not used in switch
statement
4) Example: 4) Example:
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
if(i==3) if(i==3)
break; continue;
} }
Preprocessor Directives
•The preprocessor is a program that processes the source program
before it is passed to the compiler.
•The preprocessor directives are always preferably initialised at the
beginning of the program before the main(). It is begins with a symbol
#(hash)
• #define directive
• #include directive
• #ifdef directive Conditional compilation
• #ifndef directive
•#undef directive directives
• #error directive
#define directive
The syntax of #define directive is as follows
#define identifier substitute
or
#define identifier(arg1…argN) substitute
Ex:
#define PI 3.14
void main()
OUTPUT
{
float r,area;
printf(“Enter radius:”); Enter radius:7
scanf(“%f”,&r); Area=153.86
area=PI*r*r;
printf(“Area=%.2f”,area);
}
#define directive example
#include<stdio.h>
#include<conio.h> OUTPUT
#define PI 3.14 Enter the radius of the circle:7
void main() The circumference of the circle is 43.96
{ The area of the circle is 153.86
int r;
float cir,area;
printf(“Enter the radius of the circle:");
scanf("%d",&r);
cir=2*PI*r;
area= PI *r*r;
printf("The circumference of the circle is %0.2f",cir);
printf(“The area of the circle is %0.2f",area);
getch();
}
#define directive example
#include<stdio.h>
#define SQR(x) (x*x) OUTPUT
void main() Enter the radius of the circle:7
{ The circumference of the circle is 43.96
int r; The area of the circle is 153.86
float cir,area;
printf(“Enter the radius of the circle:");
scanf("%d",&r);
cir=2*PI*r;
area= PI*SQR(r);
printf("The circumference of the circle is %0.2f",cir);
printf(“The area of the circle is %0.2f",area);
getch();
}
#undef directive
The syntax of #undef directive is as follows
#undef identifier_macro_template substitute
Ex:
#define PRINT printf(“Hello\n”)
void main()
{
int i;
PRINT; OUTPUT
#undef PRINT printf(“Hello\n”)
PRINT; Error
}
#include directive
• The #include directive loads the specified file in the current
program
The syntax of #include directive is as follows
#include “filename”
#include <filename>
• The area or block of the C program from where the variable can be
accessed is known as the scope of variable
• The lifetime of the variable retains a given value during the execution
of the program.
• The external declaration does not allocate storage space for the
variables.
void stat()
{
static int x;
x=x+1;
printf(“x=%d\n”,x);
}
Register variables Example
#include<stdio.h>
int main() Output:
{ 1
register int j; 2
for(j=1;j<=3;j++) 3
printf(“%d\n”,j);
return 0;
}