C Programming and Data Structures Unit-I Introduction To C Language Topics
C Programming and Data Structures Unit-I Introduction To C Language Topics
C Programming and Data Structures Unit-I Introduction To C Language Topics
UNIT-I
INTRODUCTION TO C LANGUAGE
Topics:-
1. C Language elements
2. Variable declarations and data types
3. Operators and expressions
4. Decision statements - If and switch statements
5. Loop control statements - while, for, do-while statements
6. Arrays
C Character Set:-
C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.Each and every smallest individual units in a C program are known as C
tokens. (or) The smallest individual unit in a C program is called token.
There are 6 tokens in C language.
1. Keywords
2. Identifiers
3. Constants
4. Operators
5. Strings
6. Special symbols
Keywords:- All predefined names or words which cannot be changed are called keywords.
There are a total of 32 keywords in 'C'. Keywords are written in lowercase letters.
auto double int struct
do if static while
1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants
Integer constants:- Integer constants are whole numbers without any fractional part . An
integer constant is a sequence of digits.It must not have a decimal point.It can either be
positive or negative.
Ex:- 19, -203, etc
There are three types of integer constants:
1. Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or +
sign.
Example of valid decimal integer constants
341, -341, 0, 8972
2. Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is
said to be octal integer constants.
Example of valid octal integer constants
010, 0424, 0, 0540
3. Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits preceded by
0x or 0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
Example Program 1
#include<stdio.h>
int main()
{
printf("%f\n%e",56.78E-2,45.786);
return 0;
}
Output:-
0.567800
4.578600e+001
Example Program 2
#include<stdio.h>
int main()
{
float x,y,z;
printf("Enter the first real number:");
scanf("%f",&x);
printf("Enter the second real number:");
scanf("%f",&y);
z=x+y;
printf("Sum in fractional: %f",z);
printf("\nSum in exponential: %e",z);
return 0;
}
Input & Output:-
Enter the first real number:12675.34
Enter the second real number:145.658E-2
Sum in fractional: 12676.796875
Sum in exponential: 1.267680e+004
Single character constants:- It simply contains a single character enclosed within ' and ' (a
pair of single quote). Character constants have a specific set of integer values known as
ASCII values (American Standard Code for Information Interchange).
Ex:- 'X', '5', ';'
String constants:- These are a sequence of characters enclosed in double quotes, and they
may include letters, digits, special characters, and blank spaces.
Ex:- “hello”, “8”, “123”, etc
Backslash Character Constants:-
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".
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
Operators:- An operator is a symbol (+, -, *, /) that directs the computer to perform certain
mathematical or logical manipulations. (or) An operator is a symbol which is used to
perform arithmetic or logical operation on given input data.
Ex:- addition(+), multiplication(*), subtraction(-), etc
String:- A string is an group of characters always enclosed with double quotes(“ “).
Ex:- “Hello”, “GIST”, “1234” , etc
Special symbols:- Symbols other than the Alphabets and Digits are called Special symbols.
Special symbols are of two types:-
Special charecters:- The following are special charecters used in C have some special
meaning and thus, cannot be used for some other purpose.
[ ] ( ) { } ; : # ‘ “ are some special charecters used in the C program.
Curly Braces{ }: These opening and ending curly braces marks the start and end of a block
of code containing more than one executable statement.
Paranthesis( ): These special symbols are used to indicate function calls and function
definitions.
Square Brackets[ ]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
White spaces or escape sequences or back slash character constants:- whitespace is
any character or series of characters that represent horizontal or vertical space.
Ex:- \t, \n, \0, \r, \?, \’, \” ,etc
C Tokens Example Program
main( )
{
int x, y, total;
x = 10, y = 20;
total = x + y;
printf ("Total = %d \n", total);
}
where,
{,}, (,),”,%,; – special charecters (or) delimiters
int – keyword
x, y, total – identifiers
+,=, and comma(,) – operators
10,20 – Integer constants
\n- backslash character constant
Output:-
Total = 30
---***---
Example:-
int i,j,k;
char c,ch;
float f,salary;
double d;
Intitialization of variables:- Assigning values or constants to a variables is called
Initialization. It can be done in 2 ways.
i) At the time of compilation
ii) At the time of execution
At the time of compilation:-If we initialise a variable at the time of declaration, It is
referred to as Compile time initialization.C variables declared can be initialized with the
help of assignment operator ‘=’.
Syntax:-variable_name=constant/expression;
At the time of execution:-If Initialization is done during execution of program , it is referred
to as run time initialization. Scanf( ) function is used to initialize variable at run time.
Example:-
Compile time:-
int i = 10;
Run time:-
scanf (“%d”, & i ); /* at execution time the value of i is assigned as the value we enter.*/
Note:- C variables must be declared before they are used in the c program.
Data types
Data type enables the user to specify what type of data to be entered as input for program
to do manipulation or operation. There are four data types in C language. They are:-
Data Types
Most of the time, for small programs, we use the basic fundamental data types in C – int,
char, float, and double.
For more complex and huge amounts of data, we use derived types – array, structure,
union, and pointer.
Integer DataType:-
Integer data type allows a variable to store Integer constants.
Signed Integer :-
Short Integer Long Integer
UnSigned Integer:-
Short Integer Long Integer
Long double data type:- long double data type allows a variable to store real constants.
Character data type:- character data type allows variable to store only one character.
charecter can be alphabet or digit or special symbol.
-----****-----
main()
{
int data = 10;
int result = 0;
result = data++;
printf("data = %d\n",data);
printf("result = %d\n",result);
}
Output:
data = 11
result = 10
Decrement:-Decrement operator decreases the value of operand by 1.
There are two types of decrement operators.
Sizeof :-The sizeof is a unary operator that returns the size of data (constants, variables,
array, structure, etc) in form of bytes.
#include<stdio.h>
main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
}
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Address(&):-Every variable is a memory location and every memory location has its
address defined which can be accessed using address (&) operator, which denotes an
address in memory.
#include<stdio.h>
main ()
{
int var1=10;
printf("Address of var1 variable: %u\n",&var1);
printf(“Value of var1 variable: %d”,var1);
}
Output:-
Address of var1 variable: bff5a400
Value of var1 variable: 10
+ addition
- subtraction
* multiplication
/ Division(quotient)
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
}
Output:-
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
Relational Operators:- Relational operators are used to compare values of two variables.
There are six relational operators. If the relation is true, then it will return value 1.
Otherwise, it returns value 0.
RELATIONAL
USAGE DESCRIPTION EXAMPLE
OPERATORS IN C
> a>b a is greater than b 7 > 3 returns true (1)
Logical Operators:- Logical operators are used to compare two expressions. If comparision
is true produces 1 as output otherwise 0 as output. There are 3 logical operators.
Operator Meaning Example
Output:-
Return value of above expression is 1
Return value of above expression is 0
Return value of above expression is 1
Bitwise Operators:- Bitwise Operators are used for manipulating data at the bit level.
Bitwise operators cannot be directly applied to primitive data types such as float, double,
etc. Always remember one thing that bitwise operators are mostly used with the integer
data type.
There are six bitwise operators.
Operator Meaning
| Bitwise OR operator(Binary)
Left Shift(<<) and Right shift(>>):- The bitwise shift operators move the bit values of a
binary object. The left operand specifies the value to be shifted. The right operand specifies
the number of positions that the bits in the value are to be shifted.
Operator Usage
<< Indicates the specified no. of bits are to be shifted to the
left.
>> Indicates the specified no. of bits are to be shifted to the
right.
Left shift:-
The << operator fills vacated bits with zeros.
For example, if variable x has the value 8, the bit pattern (in 16-bit format) of x is:
0000000000001000
The expression x << 3 produces:
0000000001000000 (decimal value=64)
Right Shift:-
For example, if variable y has the value 12, the bit pattern(in 16-bit format) of y is:
0000000000001100
The expression y >> 2 produces:
0000000000000011 (decimal value=3)
Example Program:-
#include<stdio.h>
main( )
{
int x=8,y=12,c,d;
c=x<<3;
printf("value of c is %d ",c);
d=y>>2;
printf("\nvalue of d is %d ",d);
}
Output:-
value of c is 64
value of d is 3
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise AND:-
00001100
& 00011001
________
Bitwise OR:-
12 = 00001100 (In Binary)
00001100
| 00011001
________
Bitwise XOR:-
00001100
^ 00011001
________
#include<stdio.h>
main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
printf("Output = %d", a|b);
printf("Output = %d", a^b);
}
Output:-
Output = 8
Output = 29
Output = 21
Comma Operator(,):- comma operator can be used as separator and also as operator.
1) Comma (,) as separator
While declaration multiple variables and providing multiple arguments in a function, comma
works as a separator.
Example:
int a,b,c;
In this statement, comma is a separator and tells to the compiler that these (a, b, and c) are
three different variables.
Sometimes we assign multiple values to a variable using comma, in that case comma is known
as operator.
Example:
a = 10,20,30;
b = (10,20,30);
In the first statement, value of a will be 10, because assignment operator (=) has more priority
more than comma (,), thus 10 will be assigned to the variable a.
In the second statement, value of b will be 30, because 10, 20, 30 are enclosed in braces, and
braces has more priority than assignment (=) operator. When multiple values are given with
comma operator within the braces, then right most value is considered as result of the
expression. Thus, 30 will be assigned to the variable b.
The first expression1 is evaluated, if it is true then the value of expression2 becomes the
result of the overall expression. On the other hand, if expression1 is false, then the value
of expression3 becomes the result of the overall expression.
#include<stdio.h>
main( )
{
int a, b, max;
printf("Enter a and b: ");
scanf("%d%d", &a, &b);
max = a > b ? a : b;
printf("Largest of the two numbers = %d\n", max);
}
Output:-
Enter a and b: 1993 1534
Largest of the two numbers = 1993
Expressions
Ex:-10 + 4 * 3 / 2
#include<stdio.h>
main()
{
float a,b,c,x,y,z;
a=9;
b=12;
c=3;
x= a-b/3+c*2-1;
y= a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
printf("x = %f\n",x);
printf("y = %f\n",y);
printf("z = %f\n",z);
}
Output:-
x = 10.000000
y = 7.000000
z = 4.000000
---***---
1. Sequence
2. Selection
3. Repetition
2. Selection:
It selects a statement to execute on the basis of condition. Statement is executed when the
condition is true and ignored when it is false.
Selection statements :- if, if else, nested if else, else if ladder, switch statements.
3. Repetition:
In this structure the statements are executed more than one time. It is also known as iteration
or loop
if statement :- When user need to execute a block of statements only when a given
condition is true then we use if statement.
Syntax:-
if(condition)
{
statement 1;
statement 2;
...
}
Example program:-
#include<stdio.h>
main( )
{
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is even number",number);
}
}
Output
Enter a number:4
4 is even number
if-else statement:- The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes the C else statement.
We can use the else statement with if statement to execute a block of code when
the condition is false.
Syntax:-
if(condition)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
Example Program 2:-
#include <stdio.h>
main( )
{
int age;
printf("Enter your age?");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote...");
}
else
{
printf("Sorry ... you can't vote");
}
}
Output 1
Enter your age?18
You are eligible to vote...
Output 2
Enter your age?13
Sorry ... you can't vote
else-if ladder statement:- The else..if statement is useful when user need to check
multiple conditions within the program.
Syntax:-
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
Example Program:-
#include<stdio.h>
#include<conio.h>
voidmain()
{
int a;
printf("Enter a Number: ");
scanf("%d",&a);
if(a >0)
{
printf("Given Number is Positive");
}
elseif(a == 0)
{
printf("Given Number is Zero");
}
elseif(a <0)
{
printf("Given Number is Negative");
}
getch();
}
Output:
Enter a Number: -5
Given Number is Negative
Nested if-else statement:- When an if else statement is present inside the body of another
“if” or “else” then this is called nested if else.
Syntax:-
if(expression)
{
if(expression1)
{
statement-block1;
}
else
{
statement-block2;
}
}
else
{
statement-block3;
}
Example Program:-
#include<stdio.h>
main( )
{
int a,b,c;
printf("Enter 3 number to compare: ");
scanf("%d%d%d",&a,&b,&c);
if(a > b)
{
if(a > c)
{
printf("a is greatest");
}
else
{
printf("c is greatest");
}
}
else
{
if(b > c)
{
printf("b is greatest");
}
else
{
printf("c is greatest");
}
}
}
Output:
Enter 3 Number to compare: 5
7
9
c is greatest
Switch statement:- The switch statement allows us to execute one code block
among many alternatives.
Syntax:-
switch( expression )
{
case constant-1:
Block-1;
Break;
case constant-2:
Block-2;
Break;
case constant-n:
Block-n;
Break;
default:
Block-1;
Break;
}
Statement-x;
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.
If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to constant2 ,
If we do not use break , all statements after the matching label are executed.
By the way, the default clause inside the switch statement is optional.
Example program:-
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
Output
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5- 12.4 = 20.1
---***---
Loops in programming come into use when we need to repeatedly execute a block of
statements. For example: Suppose we want to print “Hello World” 10 times. This can be
done in two ways as shown below:
#include <stdio.h>
main( )
{
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
return0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
return0;
}
Output:-
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
In computer programming, a loop is a sequence of instructions that is repeated until a
certain condition is reached. A loop consists of two parts, a body of a loop and a control
statement. The control statement is a combination of some conditions that direct the body
of the loop to execute until the specified condition becomes false.
Types of Loops in C
In an entry controlled loop, a condition is checked before executing the body of a loop. It
is also called as a pre-checking loop.
In an exit controlled loop, a condition is checked after executing the body of a loop. It is
also called as a post-checking loop.
for loop:-
syntax:-
Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
However, if the test expression is evaluated to true, statements inside the body of for loop
are executed, and the update expression is updated.
Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the
loop terminates.
Output
1 2 3 4 5 6 7 8 9 10
Explanation:-
1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body of for loop is
executed. This will print the 1 (value of i) on the screen.
3. The update statement ++i is executed. Now, the value of i will be 2. Again, the test
expression is evaluated to true, and the body of for loop is executed. This will print 2 (value
of i) on the screen.
4. Again, the update statement ++i is executed and the test expression i < 11 is evaluated. This
process goes on until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for loop terminates.
While loop:-
Syntax:-
initializationStatement;
while (testExpression)
{
// statements inside the body of the loop
updateStatement;
}
The while loop evaluates the test expression inside the parenthesis ().
If the test expression is true, statements inside the body of while loop are executed. Then,
the test expression is evaluated again.
The process goes on until the test expression is evaluated to false.
while (i <= 5)
{
printf("%d\n", i);
++i;
}
}
Output
1
2
3
4
5
initialization Statement;
do
{
// statements inside the body of the loop
updateStatement;
}
while (testExpression);
The body of do...while loop is executed once. Only then, the test expression is evaluated.
If the test expression is true, the body of the loop is executed again and the test expression
is evaluated.
Output
break statement:-
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
The break statement is almost always used with if...else statement inside the loop.
How break statement works?
#include <stdio.h>
main( )
{
int i;
double number, sum = 0.0;
for (i = 1; i <= 10; ++i)
{
printf("Enter a n%d: ", i);
scanf("%lf", &number);
// if the user enters a negative number, break the loop
if (number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf", sum);
}
Output
continue statement:-
The continue statement skips the current iteration of the loop and continues with the next
iteration. Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.
How continue statement works?
Example 2: continue statement
#include <stdio.h>
main( )
{
int i;
double number, sum = 0.0;
for (i = 1; i <= 10; ++i)
{
printf("Enter a n%d: ", i);
scanf("%lf", &number);
if (number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf", sum);
}
Output
goto statement:-
The goto statement allows us to transfer control of the program to the specified label.
Syntax of goto Statement:
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the goto statement is encountered, the control of the
program jumps to label: and starts executing the code.
#include <stdio.h>
main( )
{
const int maxInput = 100;
int i;
double number, average, sum = 0.0;
for (i = 1; i <= maxInput; ++i)
{
printf("%d. Enter a number: ", i);
scanf("%lf", &number);
// go to jump if the user enters a negative number
if (number < 0.0)
{
goto jump;
}
sum += number;
}
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
}
Output
1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53
---***---
Topic 6: Arrays
Consider following example:-
main( )
{
int a=4;
int a=9;
int a=12;
Printf(“a=%d”,a);
}
Output:-
a=12
Explanation:- ‘a’ is a variable which can store only one data at a time. First 4 is stored in
‘a’ then 9 and then 12 is stored in ‘a’. Therefore finally 12 is stored in memory. Values 4,9
are erased.
Why do we need arrays?
We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if
we want to store a large number of instances, it becomes difficult to manage them with
normal variables. The idea of an array is to represent many instances in one variable.
An array is collection of elements of same data type which are referred with single name.
Types of arrays:-
1. Single dimensional array (or) One dimensional(1D) array
2. Multi dimensional array
1D array:- single dimensional arrays are used to store list of values of same datatype. In
other words, single dimensional arrays are used to store a row of values.
Declaration of array:-
Syntax:-
datatype arrayname[size];
Example:- int a[5]; /*integer array*/
float b[3]; /* float array*/
char c[10]; /*character array*/
Initialization of array:- Assigning values to array is called initialization. It can be done in 2
ways.
1. At time of compilation
2. At time of execution
At time of compilation:- assignment (=) operator is used for initialization of array.
Example:-
int n[6] = {2, 3, 15, 8, 48, 13};
Example program
include<stdio.h>
main( )
{
int i;
int arr[3] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
Output:-
2 3 4
#include <stdio.h>
main( )
{
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i)
{
printf("%d\n", values[i]);
}
}
Output
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
Example:-
float x[3][4];
Example program:-
#include<stdio.h>
main( )
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
} //end of j
Printf(“\n”);
} //end of i
}
Output:-
1 2 3
2 3 4
3 4 5
4 5 6
At the time of execution:- scanf( ) is used for initialization.
Example program:-
#include<stdio.h>
main( )
{
int i,j;
int arr[4][3];
printf("enter 2d-array elements:");
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
}//end of j
}//end of i
Nested for loops:- Nested loop means a loop statement inside another loop
statement. That is why nested loops are also called as “loop inside loop“.
do
{
do
{
// statement of inside loop
}while(condition);
// statement of outer loop
}while(condition);
/*Program for reading and displaying matrix elements in an array*/
main( )
{
int i, j;
// Declare the matrix
int matrix[ROW][COL] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
printf("Given matrix is \n");
// Print the matrix using nested loops
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
Output:-
Given matrix is
123
456
789
-----***THE END***----