C Complete Notes1
C Complete Notes1
*****************************************************************************
UNIT – I
TYPES OF COMPUTERS
1
Microcomputers (Personal Computer)
• Data Storage
Hard disk & Floppy disk drivers are used
to enter and store data and programs
• Softcopy Output
–A visual display screen (monitor) and / or
a printer is used to get the output
•
PDAs
Personal Digital Assistants
Generally used to maintain an electronic appointment book,
address book, calculator, and notepad
Mainframe
• Mainframe computers can support hundreds or thousands
of users, handling massive amounts of input, output, and
storage.
• Mainframe computers are used in large organizations
where many users need access to shared data and programs.
• Mainframes are also used as e-commerce servers, handling
transactions over the Internet.
Workstation
•Personal computer=Workstation
•Workstations are more powerful and higher in
performance than desktop computers, especially with
respect to CPU and Graphics, memory capacity and
multitasking capability.
•Its Powerful desktop computer designed for
specialized tasks.
•Lot of processing speed.
•Can also be an ordinary personal computer attached to a LAN (local area network).
CHARACTERISTICS OF COMPUTERS
Speed
• A computer is very fast device.
• It can perform large amount of work in a few seconds.
• Where human being worked a particular work for whole day, computer
does the same in very short time.
• Today, computers can perform 100 million computations in one second.
• The speed of computers are measured in terms of microseconds,
• Nano seconds and even in Pico seconds.
Where 1 second =10-6micro second
=10-9nano second
=10-12Pico second
4
Accuracy
• The computer is 100% accurate.
• Capable to perform arithmetical calculation and logic operations with the
same accuracy.
• It can never make mistakes.
Diligence
• A computer can operate twenty four hours continuously without taking any
rest.
• It has no feelings or no emotions, if you work continuously for 3 hours.
High Memory
• Computer has made more memory or storage capacity than human beings.
• It can store millions of data and instructions, which can be retrieved and
recalled even after a number of years.
• This is not possible in case of human brain
5
OPERATING SYSTEM
Introduction
Functions of OS
Classification of OS
• Microsoft Windows
• Mainframe
• DOS
• OS/2
• Linux
• Mac OS
• AmigaOS
6
PROGRAMMING LANGUAGES
Machine language
There are three types of programming language:
▪ Machine language(Low-level language)
▪ Assembly language(Low-level language)
▪ High-level language
Machine Language
▪ Machine language is a collection of binary digits orbits that the computer read
sand interprets.
▪ Machine languages are the only languages understood by computers.
▪ While easily understood by computers, machine languages are
almost impossible for humans to use because they consist entirely of numbers
Machine Language
169 1 160 0 153 0 128 153 0 129 153 130 153 0 131 200 208 241 96
High level language
5 FOR I=1 TO 1000: PRINT "A";: NEXT I
Assembly Language
▪ Consists of a series of instructions mnemonics that correspond to a
stream of executable instructions, when translated by an assembler that
can be loaded into memory and executed.
▪ Assembly languages use keywords and symbols, much like English, to
form a programming language but at the same time introduce a new
problem.
Machine language
10110000 01100001
Assembly language :
mov a1, #061h
7
Meaning:
Move the hexadecimal value 61 (97 decimal) into the processor register named
"a1".
8
Basic structures of C program
1) Documentation Section:
Consists of a set of command lines giving the name of program.
2) Link Section:
Provides Instruction to compiler to link functions from the system library.
3) Definition Section:
Define Symbolic constants.
4) Global Declaration Section:
Declare the variable that is outside of all the functions.
5) Main () Function:
Every C program must have one main () function section. These section two
Parts, declaration part and executable part.
❖ Declaration Part: declare all the variables inside of main function.
❖ Executable Part: declare the variables outside of main function
❖ The program execution begins at the opening brace and end at the closing
brace. { }
❖ All statement in the declaration and executable parts end with a semicolon(;).
9
Character set
C Tokens
10
11
12
VARAIABLES
13
14
15
UNIT II
MANAGING INPUT OUTPUT OPERATION
As we all know the three essential functions of a computer are reading, processing and
writing data.
Majority of the programs take data as input, and then after processing the processed data
is being displayed which is called information.
In C programming you can use scanf() and printf() predefined function to read and print
data.
#include<stdio.h>
void main()
int a,b,c;
c = a + b;
Output:
In this above program scanf() is used to take input from the user, and respectively printf() is
used to display output result on the screen.
16
MANAGING INPUT/OUTPUT
I/O operations are useful for a program to interact with users. stdlib is the standard C
library for input-output operations.
While dealing with input-output operations in C, two important streams play their role.
These are:
Standard input or stdin is used for taking input from devices such as the keyboard as a data
stream.
Standard output or stdout is used for giving output to a device such as a monitor. For using I/O
functionality, programmers must include stdio header-file within the program.
The easiest and simplest of all I/O operations are taking a character as input by reading that character
from standard input (keyboard).
Syntax:
var_name = getchar();
Example:
#include<stdio.h>
void main()
char title;
title = getchar();
17
There is another function to do that task for files: getc which is used to accept a character from standard
input.
Syntax:
Writing Character In C
Similar to getchar() there is another function which is used to write characters, but one at a time.
Syntax:
putchar(var_name);
Example:
#include<stdio.h>
void main()
putchar(result);
putchar('\n');
Similarly, there is another function putc which is used for sending a single character to the standard
output.
Syntax:
18
Formatted Input
It refers to an input data which has been arranged in a specific format. This is possible in C using scanf().
We have already encountered this and familiar with this function.
Syntax:
%w sd
Here the % sign denotes the conversion specification; w signifies the integer number that defines the
field width of the number to be read. d defines the number to be read in integer format.
Example:
#include<stdio.h>
void main()
Input data items should have to be separated by spaces, tabs or new-line and the punctuation
marks are not counted as separators.
19
There are two popular library functions gets() and puts() provides to deal with strings in C.
gets: The char *gets(char *str) reads a line from stdin and keeps the string pointed to by the str and
is terminated when the new line is read or EOF is reached.
Syntax:
puts: The function - int puts(const char *str) is used to write a string to stdout, but it does not
include null characters. A new line character needs to be appended to the output. The declaration is:
Syntax:
C FORMAT SPECIFIERS
Format specifiers can be defined as the operators which are used in association with
printf() function for printing the data that is referred by any object or any variable.
When a value is stored in a particular variable, then you cannot print the value stored in
the variable straightforwardly without using the format specifiers.
You can retrieve the data that are stored in the variables and can print them onto the
console screen by implementing these format specifiers in a printf() function.
Format specifiers start with a percentage % operator and followed by a special character
for identifying the type of data.
There are mostly six types of format specifiers that are available in C.
20
Format Specifier Description
The %d format specifier is implemented for representing integer values. This is used with
printf() function for printing the integer value stored in the variable.
Syntax:
printf("%d",<variable name>);
Whenever you need to print any fractional or floating data, you have to use %f format
specifier.
Syntax:
21
Charter Format Specifier %c
The %c format specifier is implemented for representing characters. This is used with
printf() function for printing the character stored in a variable.
When you want to print a character data, you should incorporate the %c format specifier.
Syntax:
printf("%c",<variable name>);
The %s format specifier is implemented for representing strings. This is used in printf()
function for printing a string stored in the character array variable.
When you have to print a string, you should implement the %s format specifier.
Syntax:
printf("%s",<variable name>);
The %u format specifier is implemented for fetching values from the address of a
variable having unsigned decimal integer stored in the memory.
This is used within printf() function for printing the unsigned integer variable.
Syntax:
printf("%u",<variable name>);
The %ld format specifier is implemented for representing long integer values. This is
implemented with printf() function for printing the long integer value stored in the variable.
Syntax:
22
printf("%ld",<variable name>);
C operators are symbols that are used to perform mathematical or logical manipulations.
The C programming language is rich with built-in operators.
Operators take part in a program for manipulating data and variables and form a part of
the mathematical or logical expressions.
C programming language offers various types of operators having different functioning
capabilities.
TYPES OF OPERATOR IN C
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
6. Conditional Operator
7. Bitwise Operators
8. Special Operators
1. ARITHMETIC OPERATORS
Arithmetic Operators are used to performing mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/) and modulus (%).
Operator Description
+ Addition
- Subtraction
23
* Multiplication
/ Division
% Modulus
#include <stdio.h>
void main()
Program Output:
Increment and Decrement Operators are useful operators generally used to minimize the
calculation, i.e. ++x and x++ means x=x+1 or -x and x−−means x=x-1. But there is a slight
difference between ++ or −− written before or after the operand. Applying the pre-increment first
add one to the operand and then the result is assigned to the variable on the left whereas post-
increment first assigns the value to the variable on the left and then increment the operand.
24
Operator Description
++ Increment
−− Decrement
#include <stdio.h>
void main()
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
Program Output:
25
54
43
32
21
10
2. RELATIONAL OPERATORS
Operator Description
== Is equal to
!= Is not equal to
3. LOGICAL OPERATORS
C provides three logical operators when we test more than one condition to make
decisions. These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning
logical NOT).
Operator Description
26
&& And operator. It performs logical conjunction of two
expressions. (if both expressions evaluate to True, result is
True. If either expression evaluates to False, the result is False)
4. BITWISE OPERATORS
C provides a special operator for bit operation between two variables.
Operator Description
| Binary OR Operator
5. ASSIGNMENT OPERATORS
Assignment operators applied to assign the result of an expression to a variable. C has a
collection of shorthand assignment operators.
Operator Description
27
= Assign
6. CONDITIONAL OPERATOR
C offers a ternary operator which is the conditional operator (?: in combination) to construct
conditional expressions.
Operator Description
?: Conditional Expression
7. SPECIAL OPERATORS
28
C supports some special operators
Operator Description
* Pointer to a variable.
#include <stdio.h>
void main()
int i=10; /* Variables Defining and Assign values */ printf("integer: %d\n", sizeof(i));
Program Output:
ARITHMATIC EXPRESSIONS
An arithmetic expression contains only arithmetic operators and operands. We know that
the arithmetic operators in C language include unary operators (+ - ++ -- ), multiplicative
operators (* / %) and additive operators (+ - ).
29
The arithmetic operands include integral operands (various int and char types) and
floating-type operands (float, double and long double).
a) Several valid arithmetic expressions are given below. Assume that variables a and b are of
type int.
Observe that the operators are used correctly. The unary operators in expressions -1.23,
a++ and -a + b /5 correctly operate on a single operand.
The unary minus (-) is used as a prefix operator whereas the increment operator (++) is
used in the postfix form.
All other operators (multiplicative and additive) are used as infix operators and they
operate on two operands. Also, the modulo-arithmetic(s) operator operates on integer operands
as required.
The expression 'A' + 2 is valid and its value is equal to 67, as the ASCII value of
character 'A' is 65. Note that the operands and operators need not be separated by spaces.
For example, the last two expressions in the first row can also be written as -a+b/5 and 3
.142*a*b. However, the spaces are often used to improve readability.
We use the operator precedence and associativity rules to determine the meaning and
value of an expression in an unambiguous manner.
30
Recall that the operators in an expression are bound to their operands in the order of their
precedence. If the expression contains more than one operator at the same precedence level, they
are associated with their operands using the associativity rules.
If the given expression is simple, we can often directly convert it to its mathematical form
and evaluate it. However, if the given expression is complex, i. e., it contains several operators at
different precedence levels, we need a systematic approach to convert it to a mathematical
equation and evaluate it.
The steps to convert a given valid C expression to its mathematical form (if possible) and
to evaluate it are as follows:
1. First determine the order in which the operators are bound to their operands by applying the
precedence and associativity rules. Note that after an operator is bound to its operand(s), that
sub-expression is considered as a single operand for the adjacent operators.
2. Obtain the equivalent mathematical equation for given C expression (if possible) by following
the operator binding sequence (obtained in step 1).
3. Determine the value of the given expression by evaluating operators in the binding sequence.
The steps to determine operator binding in an arithmetic expression are explained below
with the help of the expression -a+ b * c - d I e + f.
1. The unary operators (unary +, unary - , ++ and - -) have the highest precedence and right-to-
left associativity. Thus, the given expression is first scanned from right to left and unary
operators, if any, are bound to their operands. The order is indicated below the expression as
follows:
2. The multiplicative operators (*, I and %) have the next highest precedence and left to- right
associativity. Thus, the expression is scanned from left-to-right and the multiplicative operators,
if any, are bound to their operands as shown below. (Observe that after completion of the above
step, sub-expressions -a, b * c and d I e will be operands for the remaining operator bindings.)
3. The additive operators (+ and -) have the next highest precedence and left-to-right
associativity. Hence, the expression is scanned from left-to-tight and the additive operators, if
any, are bound to their operands as shown below. Observe that the operands for the first +
31
operator are the sub-expressions -a and b * c. Similarly, the operands for the - operator are -a+ b
* c and d /e.
Now we can write the mathematical equation for the given C expression by following the
operator binding sequence as shown below:
Now the given expression can be evaluated, again by following the operator binding sequence, as
shown below. Assume that the variables a, b, c, ct, e and f are of type float and are initialized
with values as a= 1. 5, b = 2. 0, c = 3. 5, ct= 5.0, e = 2. 5 and f = 1. 25.
Remember that except for some operators (& & || ? : and the comma operator), the C
language does not specify the order of evaluation of sub-expressions. Thus, the sub expressions
32
at the same level can be evaluated in any order. For example, the sub expressions -a, b * c and
ct I e in the above expression can be evaluated in any order.
The procedure explained above can also be used to check the validity of an expression.
The given expression is valid if we arrive at a single operand (or value) after all the operators in
the given expression are considered.
Consider a more complex arithmetic expression: -a--+ -b++ * --c. This expression
appears to be invalid due to the excessive use of operators. It contains three operands a, b and c
and seven operators, five of which are unary (-, ++ and --) and the other two are binary operators
(+ and *). However, using the operator binding steps, we can easily verify that it is a valid
expression:
C conditional statements allow you to make a decision, based upon the result of a
condition. These statements are called Decision Making Statements or Conditional
Statements.
So far, we have seen that all set of statements in a C program gets executed sequentially
in the order in which they are written and appear.
This occurs when there is no jump based statements or repetitions of certain calculations.
But some situations may arise where we may have to change the order of execution of statements
depending on some specific conditions.
33
This involves a kind of decision making from a set of calculations. It is to be noted that C
language assumes any non-zero or non-null value as true and if zero or null, treated as false.
This type of structure requires that the programmers indicate several conditions for
evaluation within a program.
The statement(s) will get executed only if the condition becomes true and optionally,
alternative statement or set of statements will get executed if the condition becomes false.
C languages have such decision-making capabilities within its program by the use of following
the decision making statements:
Conditional Statements in C
• If statement
o if statement
o if-else statement
o else if-statement
• goto statement
• switch statement
• Conditional Operator
34
IF STATEMENT
If statements in C is used to control the program flow based on some condition, it's used
to execute some statement code block if the expression is evaluated to true.
Otherwise, it will get skipped. This is the simplest way to modify the control flow of the
program.
• Simple if Statement
• if-else Statement
• else-if Ladder
Syntax:
if(test_expression)
statement 1;
statement 2;
...
'Statement n' can be a statement or a set of statements, and if the test expression is
evaluated to true, the statement block will get executed, or it will get skipped.
35
Example of a C Program to Demonstrate if Statement
Example:
#include<stdio.h>
main()
if (b & gt; a) {
printf("b is greater");
Program Output:
36
Example:
#include<stdio.h>
main()
int number;
number = -number;
grtch();
Program Output:
IF ELSE STATEMENTS
37
If else statement in C is also used to control the program flow based on some condition,
only the difference is: it's used to execute some statement code block if the expression is
evaluated to true, otherwise executes else statement code block.
Syntax:
if(test_expression)
else
38
Example of a C Program to Demonstrate if-else Statement
Example:
#include<stdio.h>
main()
int a, b;
if (a & gt; b) {
printf("\n a is greater");
} else {
printf("\n b is greater");
Program Output:
39
Example:
#include<stdio.h>
main() {
int num;
scanf("%d", num);
else
Program Output:
NESTED IF ELSE
Nested if else statements play an important role in C programming, it means you can use
conditional statements inside another conditional statement.
40
The basic format of Nested if else statement is:
Syntax:
if(test_expression one)
if(test_expression two) {
//Statement block Executes when the boolean test expression two is true.
else
#include<stdio.h>
main()
int x=20,y=30;
if(x==20)
if(y==30)
41
}
Output:
ELSE-IF STATEMENTS
OUTPUT:
GOTO STATEMENTS
So far we have discussed the if statements and how it is used in C to control statement
execution based on some decisions or conditions.
42
The flow of execution also depends on other statements which are not based on
conditions that can control the flow.
C supports a unique form of a statement that is the goto Statement which is used to
branch unconditionally within a program from one point to another.
Although it is not a good habit to use the goto statement in C, there may be some
situations where the use of the goto statement might be desirable.
Syntax:
goto label;
A label is an identifier required for goto statement to a place where the branch is to be
made.
A label is a valid variable name which is followed by a colon and is put immediately
before the statement where the control needs to be jumped/transferred unconditionally.
Syntax:
goto label;
- - -- - -
--------
label:
statement - X;
or
label:
- - -- - -
--------
43
goto label;
#include<stdio.h>
void main()
int age;
scanf("%d", &age);
if(age>=18)
else
getch();
SWITCH STATEMENT
C switch statement is used when you have multiple possibilities for the if
statement. Switch case will allow you to choose from multiple options.
44
The basic format of the switch statement is:
Syntax:
switch(variable)
case 1:
break;
case n:
break;
default:
break;
BREAK STATEMENT
After the end of each block it is necessary to insert a break statement because if the
programmers do not use the break statement, all consecutive blocks of codes will get executed
from every case onwards after matching the case block.
#include<stdio.h>
main()
int a;
45
scanf("%d",&a);
switch(a)
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default :
break;
Program Output:
46
47
UNIT-III
DECISION MAKING AND LOOPING
INTRODUCTION:
➢ Sometimes it is necessary for the program to execute the statement several times,
and C loops execute a block of commands a specified number of times until a
condition is met.
➢ In this chapter, you will learn about all the looping statements of C programming
along with their use.
WHAT IS LOOPING?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do
a task tens of thousands of times.
Every programming language has the feature to instruct to do such repetitive tasks with
the help of certain form of statements.
The statements get executed many numbers of times based on the condition.
But if the condition is given in such logic that the repetition continues any number of
times with no fixed condition to stop looping those statements, then this type of looping is
called Infinite Looping.
➢ while loops
➢ do while loops
➢ for loops
• All are slightly different and provides loops for different situations.
48
•
• Loop control statements are used to change the normal sequence of execution of the loop.
C BREAK STATEMENT
C break statement terminates any type of loop e.g., while loop, do while loop or for loop.
The breakstatement terminates the loop body immediately and passes control to the next
statement after the loop.
The break statement is only meaningful when you put it inside a loop body, and also in
the switch case statement.
We often use the break statement with the if statement, which specifies the condition to
terminate the loop.
49
The following example illustrates how to use the break statement:
#include <stdio.h>
int main() {
char key;
printf("Press any key or E to exit:\n");
while(1) {
scanf("%c", &key);
// if E or e, exit
if (key == 'E' || key == 'e')
break;
}
printf("Goodbye!\n");
}
The program asked users to enter any character. If the user enters E or e,
the break statement terminates the loop and control is passed to the statement after the loop that
displays the Goodbyemessage.
Besides using the break statement to terminate a loop, we also use the break statement
to terminate the processing of a case branch in the switch case statement.
C CONTINUE STATEMENT
C continue statement skips the rest of the current iteration in a loop and returns to the
top of the loop.
The continue statement works like a shortcut to the end of the loop body.
The following example illustrates the continue statement:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int haystack[SIZE] = {1, 3, 2, 4, 7, 6, 9, 5, 8, 0};
int needle;
printf("Enter a number (0-9) to see its position:");
scanf("%d",&needle);
int i;
for (i = 0; i < SIZE; i++)
{
if (needle != haystack[i])
50
{
printf("Finding at position %d: %d\n", i, haystack[i]);
continue;
}
printf("Number %d found at position %d\n", needle,i);
break;
}
return 0;
}
GOTO STSTEMENT:
C supports a unique form of a statement that is the goto Statement which is used to
branch unconditionally within a program from one point to another.
Although it is not a good habit to use the goto statement in C, there may be some
situations where the use of the goto statement might be desirable.
The goto statement is used by programmers to change the sequence of execution of a C
program by shifting the control to a different part of the same program.
Syntax:
goto label;
A label is an identifier required for goto statement to a place where the branch is to be
made. A label is a valid variable name which is followed by a colon and is put immediately
before the statement where the control needs to be jumped/transferred unconditionally.
Syntax:
goto label;
- - -- - -
--------
label:
statement - X;
/* This the forward jump of goto statement */
or
51
label:
- - -- - -
--------
goto label;
/*This is the backward jump of goto statement */
g: //label name
printf("you are Eligible\n");
s: //label name
printf("you are not Eligible");
C WHILE LOOPS
C while loops statement allows to repeatedly run the same block of code until a condition
is met.
WHILE LOOP is a most basic loop in C programming. while loop has one control
condition, and executes as long the condition is true.
The condition of the loop is tested before the body of the loop is executed, hence it is
called an entry-controlled loop.
52
The basic format of while loop statement is:
Syntax:
While (condition)
{
statement(s);
Incrementation;
}
example
#include<stdio.h>
int main ()
{
/* local variable Initialization */ int n = 1,times=5;
return 0;
}
Program Output:
53
DO WHILE LOOPS
C do while loops are very similar to the while loops, but it always executes the code
block at least once and furthermore as long as the condition remains true. This is an exit-
controlled loop.
Syntax:
do
{
statement(s);
}while( condition );
Example:
#include<stdio.h>
int main ()
{
54
/* local variable Initialization */ int n = 1,times=5;
/* do loops execution */ do
{
printf("C do while loops: %d\n", n);
n = n + 1;
}while( n <= times );
return 0;
}
Program Output:
C FOR LOOPS
C for loops is very similar to a while loops in that it continues to process a block of code
until a statement becomes false, and everything is defined in a single line. The for loop is
also ENTRY-CONTROLLED loop.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
55
Example of a C Program to Demonstrate for loop
Example:
#include<stdio.h>
int main ()
{
/* local variable Initialization */ int n,times=5;;
return 0;
Program Output:
SWITH STATEMENT
56
C switch statement is used when you have multiple possibilities for the if statement.
Switch case will allow you to choose from multiple options.
When we compare it to a general electric switchboard, you will have many switches in
the switchboard but you will only select the required switch, similarly, the switch case allows
you to set the necessary statements for the user.
Syntax:
switch(variable)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;
default:
//execute your code
break;
}
After the end of each block it is necessary to insert a break statement because if the
programmers do not use the break statement, all consecutive blocks of codes will get executed
from every case onwards after matching the case block.
#include<stdio.h>
main()
{
int a;
printf("Please enter a no between 1 and 5: ");
scanf("%d",&a);
switch(a)
{
case 1:
printf("You chose One");
57
break;
case 2:
printf("You chose Two");
break;
case 3:
printf("You chose Three");
break;
case 4:
printf("You chose Four");
break;
case 5:
printf("You chose Five.");
break;
default :
printf("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
Program Output:
C ARRAYS
➢ The array is a data structure in C programming, which can store a fixed-size sequential
collection of elements of the same data type.
➢ For example, if you want to store ten numbers then instead of defining ten variables, it's
easy to define an array of 10 lengths.
➢ One-Dimensional,
➢ Two-Dimensional and
➢ Multidimensional.
58
ONE DIMENSIONAL ARRAY:
Define an Array in C
Syntax:
This is called a one-dimensional array. An array type can be any valid C data types, and array
size must be an integer constant greater than zero.
Example:
double amount[5];
int age[5]={22,25,30,32,35};
int myArray[5];
int n = 0;
Example:
59
int myArray[5];
int n = 0;
1. Single or One Dimensional array is used to represent and store data in a linear form.
Syntax :
1. Array having more than one subscript variable is called Multi-Dimensional array.
Syntax :
60
Example : Two Dimensional Array
in C programming, you can create array of an array known as multidimensional array. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You
can think the array as table with 3 row and each row has 4 column.
float y[2][4][3];
You can think this example as: Each 2 elements have 4 elements, which makes 8 elements and
each 8 elements can have 3 elements. Hence, the total number of elements is 24.
C STRINGS
61
In C programming, the one-dimensional array of characters are called strings, which is
terminated by a null character '\0'.
Example:
char name[6];
Through pointers.
char *name;
Strings Initialization in C
Example:
'};
or
Example:
62
#include<stdio.h>
int main ()
{
char name[6] = {'C', 'l', 'o', 'u', 'd', '
#include<stdio.h>
int main ()
{
char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};
printf("Tutorials%s\n", name );
return 0;
}
'};
printf("Tutorials%s\n", name );
return 0;
}
Program Output:
TutorialsCloud
C STRING FUNCTIONS:
• String.h header file supports all the string functions in C language. All the string
functions are given below.
• Click on each string function name below for detail description and example programs.
String
functions Description
63
Same as strcmp() function. But, this function negotiates case.
strcmpi ( ) “A” and “a” are treated as same.
Syntax:
Example of strlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
64
Output:
Length of string str1: 13
Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of strncmp:
65
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of strcat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
66
char *strncat(char *str1, char *str2, int n)
It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will always be
appended at the end of the concatenated string.
Example of strncat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:
Example of strcpy:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
67
char *strncpy( char *str1, char *str2, size_t n)
size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1 and appends several
terminator chars(‘\0’) to accumulate the length of str1 to make it n.
Example of strncpy:
#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:
Example of strstr:
#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return 0;
}
Output:
68
UNIT IV
C POINTERS
INTRODUCTION
Pointers in C language is a variable that stores/points the address of another variable.
A Pointer in C is used to allocate memory dynamically i.e. at run time.
69
The pointer variable might be belonging to any of the data type such as int, float, char,
double, short etc.
A pointer is a variable in C, and pointers value is the address of a memory location.
Syntax:
type *variable_name;
Example:
int *width;
char *letter;
Example program:
• #include<stdio.h>
•
• int main ()
• {
• int n = 20, *pntr; /* actual and pointer variable declaration */
• pntr = &n; /* store address of n in pointer variable*/
• printf("Address of n variable: %x\n", &n );
•
• /* address stored in pointer variable */ printf("Address stored in pntr variable: %x\n",
pntr );
•
• /* access the value using the pointer */ printf("Value of *pntr variable: %d\n", *pntr );
• return 0;
• }
• Address of n variable: 2cb60f04
70
• Value of *pntr variable: 20
UNDERSTANDING POINTER
The actual locations of a variable in the memory are system dependent and therefore, the address
of a variable is not known to us immediately.
Example: p=&quantity
➢ &125(pointing at constsnts)
➢ Int x[10]
➢ &x (pointing at array names)
➢ &(x+y) (pointing at expressions)
Example program:
void main()
x=10;
ptr=&x;
y = *ptr;
printf(“Value of x is %d\n\n”,x);
71
printf(“%d is stored at address %u\n”, *&x, &x);
*ptr=25;
Output:
Value of X is 10
Now x = 25
72
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable
If you are not sure about which variable's address to assign to a pointer variable while
declaration, it is recommended to assign a NULL value to your pointer variable. A pointer
which is assigned a NULLvalue is called a NULL pointer.
#include <stdio.h>
int main()
{
int *ptr = NULL;
return 0;
}
73
Steps:
main()
{
int x, y;
int *ptr;
x = 10;
ptr = &x;
y = *ptr;
printf("Value of x is %d\n\n",x);
printf("%d is stored at addr %u\n", x, &x);
printf("%d is stored at addr %u\n", *&x, &x);
printf("%d is stored at addr %u\n", *ptr, ptr);
printf("%d is stored at addr %u\n", y, &*ptr);
printf("%d is stored at addr %u\n", ptr, &ptr);
printf("%d is stored at addr %u\n", y, &y);
*ptr = 25;
printf("\nNow x = %d\n",x);
}
Output
Value of x is 10
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
10 is stored at addr 4104
4104 is stored at addr 4106
10 is stored at addr 4108
Now x = 25
CHAIN OF POINTERS
74
Program
POINTER EXPRESSIONS
• Pointers expression :
void main()
{
int a,b,*p1,*p2, x, y, z ;
a =12; b = 4;
p1=&a; p2 = &b;
x = *p1 * *p2 – 6;
printf(“Address of a = %u\n”,p1);
printf(“Address of b=%u\n”,p2);
printf(“\n”);
printf(“a=%d, b=%d\n”,a , b);
printf(“x=%d \n”,x);
75
*p2 = *p2 + 3 ;
*p1 = *p2 – 5 ;
y = *p1 + *p2;
z= *p1 * *p2 – 6 ;
printf(\n a = %d , b = %d “, a ,b);
printf(“z = %d\n”, z);
}
Out put :-
Address of a = 4020
Address of b =4016
a = 12 b=4
x=42 y=9
a=2 b=7 z=8
➢ p1++ will cause the pointer p1 points to the next value of its type.
➢ Ex :- if p1 is an integer pointer with the initial value say 2800,then after the operations
p1=p1+1,the value of p1 will be 2802,not 2801
➢ when we increment pointer its value is increased by the length of the data type that it
points to. This length is called scale factor.
tptr = sptr;
76
tptr = NULL;
6. When two Pointer points to same array then one Pointer variable can be Subtracted from
another
7. Two Pointers pointing to objects of same data type then they can be compared using the
Relational Operator
77
Here variable arr will give the base address, which is a constant pointer pointing to the
first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In
short, arr has two purpose - it is the name of the array and it acts as a pointer pointing towards
the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one element to
another.
POINTER TO ARRAY
As studied above, we can use a pointer to point to an array, and then we can use that
pointer to access the array elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
78
In the above program, the pointer *p will print all the values stored in the array one by
one. We can also use the Base address (a in above case) to act as a pointer and print all the
values.
79
POINTER AND CHARACTER STRINGS
Pointer can also be used to create strings. Pointer variables of char type are treated as
string.
char *str = "Hello";
The above code creates a string and stores its address in the pointer variable str. The
pointer strnow points to the first character of the string "Hello". Another important thing to note
here is that the string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //this is Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not
need to use indirection operator *.
ARRAY OF POINTERS
We can also have array of pointers. Pointers are very helpful in handling character array
with rows of varying length.
char *name[3] = {
"Adam",
"chris",
"Deniel"
};
//Now lets see same array without using pointer
char name[3][20] = {
"Adam",
"chris",
"Deniel"
};
80
In the second approach memory wastage is more, hence it is preferred
to use pointer in such cases.
When we say memory wastage, it doesn't means that the strings will start occupying less
space, no, characters will take the same space, but when we define array of characters, a
contiguous memory space is located equal to the maximum size of the array, which is a wastage,
which can be avoided if we use pointers instead.
81
UNIT V
USER DEFINED FUNCTIONS
➢ A function is a block of code that performs a specific task.
➢ C allows you to define functions according to your need. These functions are known as
user-defined functions. For example:
➢ Suppose, you need to create a circle and color it depending upon the radius and color.
You can create two functions to solve this problem:
• create Circle() function
• color() function
Example: User-defined function
1. #include <stdio.h>
2.
3. int addNumbers(int a, int b); // function prototype
4.
5. int main()
6. {
7. int n1,n2,sum;
8.
9. printf("Enters two numbers: ");
10. scanf("%d %d",&n1,&n2);
11.
12. sum = addNumbers(n1, n2); // function call
13.
14. printf("sum = %d",sum);
15.
16. return 0;
17. }
18.
19. int addNumbers(int a,int b) // function definition
20. {
21. int result;
22. result = a+b;
23. return result; // return statement
24. }
82
ELEMENTS OF USER-DEFINED FUNCTION IN C PROGRAMMING
There are multiple parts of user defined function that must be established in order to
make use of such function.
FUNCTION CALL
Here, int before function name indicates that this function returns integer value to the
caller while intinside parentheses indicates that this function will recieve an integer value from
caller.
FUNCTION DEFINITION
Function definition provides the actual body of the function.
83
// body of the function
}
It consists of a function header and a function body. The function_name is an identifier.
The return_value_type is the data type of value which will be returned to a caller.
Some functions perform the desired task without returning a value which is indicated by void as
a return_value_type. All definitions and statements are written inside the body of the function.
RETURN STATEMENT
Return statement returns the value and transfer control to the caller.
FUNCTION HEADER:
It consists of three parts: return type, function name and argument list.
FUNCTION BODY:
It consists of three parts: local variable declaration part, executable part and return statement.
All the required variables are declared at the local variable declaration part.
Executable part contains all the executable statements that performs actual task.
Return Statement should be the last statement inside the function body. It is optional.
If return type of function is void then it can be omitted but function having return type other
than void must include return statement.
85
{
For example,
return a;
return (a+b);
FUNCTIONS CALL
86
There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference
1. CALL BY VALUE:
• In call by value method, the value of the variable is passed to the function as parameter.
• The value of the actual parameter can not be modified by formal parameter.
• Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:
• Actual parameter – This is the argument which is used in function call.
• Formal parameter – This is the argument which is used in function definition
1 #include<stdio.h>
5 int main()
6 {
87
8 // calling swap function by value
10 swap(m, n);
11 }
12
14 {
15 int tmp;
16 tmp = a;
17 a = b;
18 b = tmp;
20 }
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22
2. CALL BY REFERENCE:
• In call by reference method, the address of the variable is passed to the function as parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only address is used by both
parameters.
88
1 #include<stdio.h>
5 int main()
6 {
10 swap(&m, &n);
11 }
12
14 {
15 int tmp;
16 tmp = *a;
17 *a = *b;
18 *b = tmp;
20 }
89
OUTPUT:
values before swap m = 22
and n = 44
values after swap a = 44
and b = 22
CATEGORY OF FUNCTIONS:
All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Now, we will see simple example
C programs for each one of the below.
function declaration:
int function ( int );function call: function ( a );
function definition:
int function( int a )
{
1. With arguments and with statements;
return values return a;
}
function declaration:
void function ( int );function call: function( a );
function definition:
void function( int a )
2. With arguments and without {
return values statements;
}
90
return values void function();function call: function();
function definition:
void function()
{
statements;
}
function declaration:
int function ( );function call: function ( );
function definition:
int function( )
{
4. Without arguments and with statements;
return values return a;
}
NOTE:
• If the return data type of a function is “void”, then, it can’t return any values to the calling
function.
• If the return data type of the function is other than void such as “int, float, double etc”, then, it
can return values to the calling function.
91
17. scanf("%d",&n);
18.
19. for(i=2; i <= n/2; ++i)
20. {
21. if(n%i == 0)
22. {
23. flag = 1;
24. }
25. }
26. if (flag == 1)
27. printf("%d is not a prime number.", n);
28. else
29. printf("%d is a prime number.", n);
30. }
The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not and displays it on the screen.
The empty parentheses in checkPrimeNumber(); statement inside the main() function
indicates that no argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.
92
23. {
24. if(n%i == 0){
25. flag = 1;
26. break;
27. }
28. }
29. if(flag == 1)
30. printf("%d is not a prime number.",n);
31. else
32. printf("%d is a prime number.", n);
33. }
The integer value entered by the user is passed to checkPrimeAndDisplay() function.
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a prime
number or not and displays the appropriate message.
93
28. for(i=2; i <= n/2; ++i)
29. {
30. if(n%i == 0)
31. return 1;
32. }
33.
34. return 0;
35. }
The input from the user is passed to checkPrimeNumber() function.
The checkPrimeNumber() function checks whether the passed argument is prime or not. If
the passed argument is a prime number, the function returns 0. If the passed argument is a non-
prime number, the function returns 1.
The return value is assigned to the flag variable.Depending on whether flag is 0 or 1,
appropriate message is printed from the main()function.
94
28. int n;
29.
30. printf("Enter a positive integer: ");
31. scanf("%d",&n);
32.
33. return n;
34. }
The empty parentheses in n = getInteger(); statement indicates that no argument is
passed to the function. And, the value returned from the function is assigned to n.
NESTING OF FUNCTIONS
#include <stdio.h>
main(void) {
auto int my_fun();
my_fun();
printf("Main Function\n");
int my_fun() {
printf("my_fun function\n");
}
printf("Done"); }
Output
my_fun function
Main Function
Done
C RECURSION
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
95
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
Output
96
ADVANTAGES AND DISADVANTAGES OF RECURSION
Recursion makes program elegant and more readable. However, if performance is vital
then, use loops instead as recursion is usually much slower.
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope, visibility and
lifetime of a variable.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Local Variable
1. The variables declared inside the function are automatic or local variables.
2. The local variables exist only inside the function in which it is declared. When the
function exits, the local variables are destroyed.
int main() {
int n; // n is a local variable to main() function
... .. ...
}
void func() {
int n1; // n1 is local to func() function
}
In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed
when main() exits.
Global Variable
1. Variables that are declared outside of all functions are known as external or global
variables. They are accessible from any function inside the program.
97
5.
6. int main()
7. {
8. ++n; // variable n is not declared in the main() function
9. display();
10. return 0;
11. }
12.
13. void display()
14. {
15. ++n; // variable n is not declared in the display() function
16. printf("n = %d", n);
17. }
Output
n=7
suppose, a global variable is declared in file1. If you try to use that variable in a
different file file2, the compiler will complain. To solve this problem, keyword extern is used
in file2 to indicate that the external variable is declared in another file
.
Register Variable
1. The register keyword is used to declare register variables. Register variables were
supposed to be faster than local variables.
2. However, modern compilers are very good at code optimization and there is a rare chance
that using register variables will make your program faster.
3. Unless you are working on embedded systems where you know how to optimize code for
the given application, there is no use of register variables.
Static Variable
A static variable is declared by using keyword static. For example;
static int i;
The value of a static variable persists until the end of the program.
98
3.
4. int main()
5. {
6. display();
7. display();
8. }
9. void display()
10. {
11. static int c = 0;
12. printf("%d ",c);
13. c += 5;
14. }
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is increased by 5.
During the second function call, variable c is not initialized to 0 again. It's because c is a static
variable. So, 5 is displayed on the screen.
FILE INPUT/OUTPUT IN C
A file represents a sequence of bytes on the disk where a group of related data is stored.
File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function description
99
putc() writes a character to a file
100
a opens a text file in append mode
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.
101
INPUT/OUTPUT OPERATION ON FILE
In the above table we have discussed about various file I/O functions to perform reading
and writing on file. getc() and putc() are the simplest functions which can be used to read and
write individual characters to a file.
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
return 0;
}
struct emp
{
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age:");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
102
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
In this program, we have created two FILE pointers and both are refering to the same file
but in different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file,
which can then be printed on the console using standard printf() function.
fread() is also used in the same way, with the same arguments like fwrite() function.
Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");
if (bfp)
{
fwrite(mytext, sizeof(char), strlen(mytext), bfp);
fclose(bfp);
}
103
fseek(), ftell() and rewind() functions
• fseek(): It is used to move the reading control to different positions using fseek function.
• ftell(): It tells the byte location of current position of cursor in file pointer.
• rewind(): It moves the control to beginning of the file.
ERROR HANDLING IN C
C language does not provide any direct support for error handling. However a few
methods and variables defined in error.h header file can be used to point out error using the
return statement in a function.
In C language, a function returns -1 or NULL value in case of any error and a global
variable errno is set with the error code. So the return value can be used to check error while
programming.
WHAT IS ERRNO?
Whenever a function call is made in C language, a variable named errno is associated
with it. It is a global variable, which can be used to identify which type of error was encountered
while function execution, based on its value. Below we have the list of Error numbers and what
does they mean.
3 No such process
5 I/O error
104
7 Argument list too long
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
C language uses the following functions to represent error messages associated with errno:
• perror(): returns the string passed to it along with the textual represention of the current errno
value.
• strerror() is defined in string.h library. This method returns a pointer to the string
representation of the current errno value.
int main ()
{
FILE *fp;
fp = fopen("IWillReturnError.txt", "r");
105
return 0;
}
Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory
void main()
{
char *ptr = malloc( 1000000000UL); //requesting to allocate 1gb memory space
if (ptr == NULL) //if memory not available, it will return null
{
puts("malloc failed");
puts(strerror(errno));
exit(EXIT_FAILURE); //exit status failure
}
else
{
free( ptr);
exit(EXIT_SUCCESS); //exit status Success
}
}
Here exit function is used to indicate exit status. Its always a good practice to exit a
program with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to
show exit status.
In case of program coming out after a successful operation EXIT_SUCCESS is used to
show successful exit. It is defined as 0. EXIT_Failure is used in case of any failure in the
program. It is defined as -1.
106
DIVISION BY ZERO
There are some situation where nothing can be done to handle the error. In C language
one such situation is division by zero.
All you can do is avoid doing this, becasue if you do so, C language is not able to
understand what happened, and gives a runtime error.
Best way to avoid this is, to check the value of the divisor before using it in the division
operations. You can use if condition, and if it is found to be zero, just display a message and
return from the function.
107