0% found this document useful (0 votes)
6 views43 pages

Programming in C Unit Vise Lecture Notes

The document provides an overview of the basics of C programming, including programming paradigms, data types, storage classes, constants, keywords, and operators. It explains the structure of a C program, the significance of the main() function, and various types of data and storage classes such as auto, register, static, and extern. Additionally, it covers operators' precedence and associativity, expressions, and the classification of operators in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views43 pages

Programming in C Unit Vise Lecture Notes

The document provides an overview of the basics of C programming, including programming paradigms, data types, storage classes, constants, keywords, and operators. It explains the structure of a C program, the significance of the main() function, and various types of data and storage classes such as auto, register, static, and extern. Additionally, it covers operators' precedence and associativity, expressions, and the classification of operators in C.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 43

lOMoARcPSD|28529566

UNIT I 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 to programming paradigms

The programming language „C‟ was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. Although C was initially developed for writing system software, today it has become
such a popular language that a variety of software programs are written using this language. The
greatest advantage of using C for programming is that it can be easily used on different types of
computers. Many other programming languages such as C++ and Java are also based on C which
means that you will be able to learn them easily in the future. Today, C is widely used with the
UNIX operating system.
Programming Languages

Computer programming languages are developed with the primary objectives of facilitating a large
number of people to use computer without the need to know the details of internal structure of the
computer.
Structure of C program
A C program contains one or more functions, where a function is defined as a group of statements
that perform a well-defined task. Figure 1.1 shows the structure of a C program.
The statements in a function are written in a logical sequence to perform a specific task. The main()
function is the most important function and is a part of every C program.
lOMoARcPSD|28529566

Rather, the execution of a C program begins with this function. From the structure given in Fig. 1.1, we can
conclude that a C program can have any number of functions depending on the tasks that have to be
performed, and each function can have any number of statements arranged according to specific
meaningful sequence.
Note that programmers can choose any name for functions. It is not mandatory to write Function1,

Function2, etc., with an exception that every program must contain one function that has its name
as main().
Fig 1.1 Structure of C program
lOMoARcPSD|28529566

C Programming : Data Types


Data type determines the set of values that a data item can take and the operations that can
beperformed on the item. C language provides four basic data types. Table 1.2 lists the data types,
their size, range, and usage for a C programmer.

Basic Data Types in C

Basic data types and their variants

Storage classes
Storage classes of a variable determine:
1. Storage area of the variable
2. Initial value of variable if not initialized
3. Lifetime of the variable
lOMoARcPSD|28529566

4. Linkage of a function or variable

C language provides 4 storage class specifiers:


1. auto
2. register
3. static
4. extern
Syntax:
storageclassspecifier datatype variable name;

1. The auto storage class


 Automatic variables are also called as auto variables, which are defined inside a function.
 Auto variables are stored in main memory.
 Variables has automatic (local) lifetime.
 Auto variables are not implicitly initialized.
 Auto variables have no linkage.
 It is a default storage class if the variable is declared inside the block.
Example:
#include<stdio.h>
void main()
{
auto int a=10;
printf(“a=%d”,a);

{
int b=20;
printf(“b=%d”,b);
}
printf(“Here b is not visible\n”);
printf(“a=%d”,a);
lOMoARcPSD|28529566

Output a=10

b=20
Here b is not
visible a=10
2. The register storage class
 Register variables can be accessed faster than others
 Variables are stored in CPU.
 Variables have automatic (local) lifetime.
 Register variables are not implicitly initialized.
 Register variables have no linkage.
 Register variables are used for loop counter to improve the performance of a program.
Example:
# include<stdio.h>
void main()
{
register int a=200;
printf(“a=%d”,a);
}
Output:
a=200

3. The static storage class


 Static variables have static (global) lifetime.
 Static variables are stored in the main memory.
 Static variables can be declared in local scope as well as in the global scope.
 Static variables are implicitly initialized.
 The value of static variables persists between the function calls. Last change
made in the value of static variable remains throughout the program execution.
 Static variables will have internal linkage.

Ex:
# include<stdio.h>
void fun(int); void
main()
{
int i=0;
for(i=0;i<5;i++)
{
fun(i);
}
}
void fun(int i)
{
static int a=10; a+
+;
printf(“%d”,a);
}

Output:
11 12 13 14 15
4. The extern storage class
 Variables that are available to all functions are called external or global variables.
 External variables are stored in main memory.
 External variables have static (global) lifetime.
 External variables have external linkage.
 External variables are implicitly initialized to 0.
Example: extern
int v=10; void
call1()
void main()
{
call1();
printf(“In main v=%d”,v);
}
void call1()
{
printf(“In call1() v=%d”,v);
}

Output:
In main v=10 In call1( )
v=10
Since v is a external variable it is visible and accessed in all functions.

The typedef storage class


typedef is used for creating an alias or synonym for a known type.
Syntax:

typedef knowntype synonym name;

Eg:
typedef char* cp;
cp c; // is same as char * c;
cp and (char *) can be used interchangeably.

Summary of storage classes

S.No Storage Storage Initial Lifetime Linkage


class value
1 auto Memory Garbage Automatic NO
2 register CPU register Garbage Automatic NO
3 static Memory 0 Static Internal
4 extern Memory 0 Static External
Constants
A constant is an entity whose value can‟t be changed during the execution of a program.
Constants are classified as:
1. Literal constants
2. Qualified constants
3. Symbolic constants

Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating point
number, character or a string.
Literal constants are of the following types.
1. Integer Literal constant
2. Floating point Literal constant
3. Character Literal constant
4. String Literal constant

Integer Literal constant


Integer Literal constants are integer values like -1, 2, 8 etc. The rules for writing integer literal
constant are:
 An Integer Literal constant must have at least one digit
 It should not have any decimal point
 It can be either positive or negative.
 No special characters and blank spaces are allowed.
 A number without a sign is assumed as positive.
 Octal constants start with 0.
 Hexadecimal constant start with 0x or 0X
Floating point Literal constant
Floating point Literal constants are values like -23.1, 12.8, 4e8 etc.. It can be written in a
fractional form or in an exponential form.
The rules for writing Floating point Literal constants in a fractional form:
 A fractional floating point Literal constant must have at least one digit.
 It should have a decimal point.
 It can be either positive or negative.
 No special characters and blank spaces are allowed.
The rules for writing Floating point Literal constants in an exponential form:
 A Floating point Literal constants in an exponential form has two parts: the
mantissa part and the exponent part. Both are separated by e or E.
 The mantissa part can be either positive or negative. The default sign is positive.
 The mantissa part should have at least one digit.
 The mantissa part can have a decimal point.
 The exponent part should have at least one digit
 The exponent part cannot have a decimal point.
 No special characters and blank spaces are allowed.
Character Literal constant
A Character Literal constant can have one or at most two characters enclosed within single
quotes. E.g, „A‟ , „a‟ , „ n „.
It is classified into:
 Printable character literal constant
 Non-Printable character literal constant.
Printable character literal constant
All characters except quotation mark, backslash and new line characters enclosed within single
quotes form a Printable character literal constant. Ex: „A‟ , „#‟
Non-Printable character literal constant.
Non-Printable character literal constants are represented with the help of escape sequences. An
escape sequence consists of a backward slash (i.e. \) followed by a character and both enclosed
within single quotes.

String Literal constant


A String Literal constant consist of a sequence of characters enclosed within double quotes. Each
string literal constant is implicitly terminated by a null character.
E.g. “ABC”

Qualified constants:
Qualified constants are created by using const qualifier.
E.g. const char a = „A‟
The usage of const qualifier places a lock on the variable after placing the value in it. So we can‟t
change the value of the variable a

Symbolic constants
Symbolic constants are created with the help of the define preprocessor directive. For ex #define
PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each symbolic constant is replaced
by its actual value during the pre-processing stage.
Keywords
Keyword is a reserved word that has a particular meaning in the programming language. The
meaning of a keyword is predefined. It can‟t be used as an identifier.
Operators: Precedence and Associativity
Operands
An operand specifies an entity on which an operation is to be performed. It can be a variable
name, a constant, a function call.
E.g: a=2+3 Here a, 2 & 3 are operands
Operator
An operator is a symbol that is used to perform specific mathematical or logical manipulations.
For e.g, a=2+3 Here = & + are the operators
Precedence of operators
 The precedence rule is used to determine the order of application of
operators in evaluating sub expressions.
 Each operator in C has a precedence associated with it.
 The operator with the highest precedence is operated first.
Associativity of operators
The associativity rule is applied when two or more operators are having same precedence in the
sub expression.
An operator can be left-to-right associative or right-to-left associative.

Category Operators Associativity Precedence


Unary +, -, !, ~, ++, - -, &, sizeof Right to left Level-1
Multiplicative *, /, % Left to right Level-2
Additive +, - Left to right Level-3

Shift << , >> Left to right Level-4

Relational <, <=, >, >= Left to right Level-5

Rules for evaluation of expression


• First parenthesized sub expressions are evaluated first.
• If parentheses are nested, the evaluation begins with the innermost sub expression.
• The precedence rule is applied to determine the order of application of operators in
evaluating sub expressions.
• The associability rule is applied when two or more operators are having same precedence in the

sub expression.

Expressions
An expression is a sequence of operators and operands that specifies computation of a value.
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
Simple Expressions & Compound Expressions
An expression that has only one operator is known as a simple expression.
E.g: a+2
An expression that involves more than one operator is called a compound expression.
E.g: b=2+3*5
Classification of Operators
The operators in C are classified on the basis of
1) The number of operands on which an operator operates
2) The role of an operator

Classification based on Number of Operands


Types:
1. Unary Operator: A unary operator operates on only one operand. Some of the
unary operators are,
Operator Meaning
- Minus
++ Increment
-- Decrement
& Address- of operator
sizeof sizeof operator

2. Binary Operator: A binary operator operates on two operands. Some of the


binary operators are,

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
Division
&& Logical AND
3. Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is the ternary operator.
Classification based on role of operands
Based upon their role, operators are classified as,
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Miscellaneous Operators
1. Arithmetic Operators
They are used to perform arithmetic operations like addition, subtraction, multiplication, division
etc.
A=10 & B=20

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200

/ The division operator is used to find the quotient. B / A will give 2


% Modulus operator is used to find the remainder B%A will give 0
+,- Unary plus & minus is used to indicate the algebraic +A, -A
sign of a value.

Increment operator
The operator ++ adds one to its operand.
 ++a or a++ is equivalent to a=a+1
 Prefix increment (++a) operator will increment the variable BEFORE
the expression is evaluated.
 Postfix increment operator (a++) will increment AFTER the
expression evaluation.
 E.g.
1. c=++a. Assume a=2 so c=3 because the value of a is incremented
and then it is assigned to c.
2. d=b++ Assume b=2 so d=2 because the value of b is assigned to d
before it is incremented.
Decrement operator
The operator – subtracts one from its operand.
 --a or a-- is equivalent to a=a+1
 Prefix decrement (--a) operator will decrement the variable BEFORE
the expression is evaluated.
 Postfix decrement operator (a--) will decrement AFTER the
expression evaluation.
 E.g.
1. c=--a. Assume a=2 so c=1 because the value of a is decremented
and then it is assigned to c.
2. d=b-- Assume b=2 so d=2 because the value of b is assigned to d
before it is decremented.
2. Relational Operators
 Relational operators are used to compare two operands. There are 6
relational operators in C, they are

Operator Meaning of Operator Example


== Equal to 5==3 returns false (0)
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)

 If the relation is true, it returns value 1 and if the relation is false, it


returns value 0.
 An expression that involves a relational operator is called as a condition.
For e.g a<b is a condition.
3. Logical Operators
 Logical operators are used to logically relate the sub-expressions.
There are 3 logical operators in C, they are
 If the relation is true, it returns value 1 and if the relation is false, it
returns value 0.
Operator Meaning of Example
Operator Description
&& Logial AND If c=5 and d=2 then,((c==5) && (d>5)) It returns true when
returns false. both conditions are
true
|| Logical OR If c=5 and d=2 then, ((c==5) || It returns true when
(d>5)) returns true. at-least one of the
condition is true
! Logical NOT If c=5 then, !(c==5) returns false. It reverses the state
of the operand

Truth tables of logical operations

condition 1condition 2 NOT X X AND Y X OR Y


(e.g., X) (e.g., Y) (~X) ( X && Y ) ( X || Y )
False false true false false
False true true false true
true false false false true
true true false true true

4. Bitwise Operators
C language provides 6 operators for bit manipulation. Bitwise operator operates on the
individual bits of the operands. They are used for bit manipulation.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right

Truth tables

p Q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
E.g.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001

00001000 = 8 (In decimal) Bitwise


OR Operation of 12 and 25
00001100
| 00011001

00011101 = 29 (In decimal)

3 << 2 (Shift Left)


0011
1100=12

3 >> 1 (Shift Right)


0011
0001=1

5. Assignment Operators
To assign a value to the variable assignment operator is used.

Operators Example Explanation


Simple assignment operator = sum=10 10 is assigned to variable sum
+= sum+=10 This is same as sum=sum+10
-= sum-=10 sum = sum-10
*= sum*=10 sum = sum*10
Compound assignment operators/+ sum/=10 sum = sum/10
Or %= sum%=10 sum = sum%10
Shorthand assignment operators
&= sum&=10 sum = sum&10
^= sum^=10 sum = sum^10
E.g.
var=5 //5 is assigned to var
a=c; //value of c is assigned to a

6. Miscellaneous Operators
Other operators available in C are
a. Function Call Operator(i.e. ( ) )
b. Array subscript Operator(i.e [ ])
c. Member Select Operator
i. Direct member access operator (i.e. . dot operator)
ii. Indirect member access operator (i.e. -> arrow operator)
d. Conditional operator (?:)
e. Comma operator (,)
f. sizeof operator
g. Address-of operator (&)
a) Comma operator
 It is used to join multiple expressions together.
 E.g.
int i , j; i=(j=10,j+20
In the above declaration, right hand side consists of two expressions separated by comma. The first
expression is j=10 and second is j+20. These expressions are evaluated from left to right. ie first
the value 10 is assigned to j and then expression j+20 is evaluated so the final value of i will be 30.
b) sizeof Operator
 The sizeof operator returns the size of its operand in bytes.
 Example : size of (char) will give us 1.
 sizeof(a), where a is integer, will return 2.

c) Conditional Operator
 It is the only ternary operator available in C.
 Conditional operator takes three operands and consists of two symbols ? and : .
 Conditional operators are used for decision making in C.
Syntax :
(Condition? true_value: false_value);
For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
d) Address-of Operator
It is used to find the address of a data object.
Syntax

&a will give address of a.

Input/Output statements
The I/O functions are classified into two types:
 Formatted Functions
 Unformatted functions

Input and Output functions

Formatted Functions Unformatted Functions

printf() getch()
getche()
getchar()
scanf()
gets()
putch()
putchar()
puts()
UNIT II - ARRAYS AND STRINGS

Introduction to Arrays: Declaration, Initialization – One dimensional array – Example Program: Computing
Mean, Median and Mode - Two dimensional arrays – Example Program: Matrix Operations (Addition,
Scaling, Determinant and Transpose) - String operations: length, compare, concatenate, copy – Selection
sort, linear and binary search

Introduction to Arrays

An Array is a collection of similar data elements. These data elements have the same data type. The elements
of the array are stored in consecutive memory locations and are referenced by an index (also known as
subscript). Subscript indicates an ordinal number of the elements counted from the beginning of the array.
Definition:

An array is a data structure that is used to store data of the same type. The position of an element is specified
with an integer value known as index or subscript.
E.g.

a(integer array)

b(float array ) [0] [1] [2] [3]

Characteristics:

i) All the elements of an array share a common name called as array name

ii) The individual elements of an array are referred based on their position.

iii) The array index in c starts with 0.


In general arrays are classified as:
1. Single dimensional array
2. Multi-dimensional array

Declarations of Arrays

Array has to be declared before using it in C Program. Declaring Array means specifying three things.
Data_type Data Type of Each Element of the array

Array_name Valid variable name


Size Dimensions of the Array Arrays are declared using the following syntax:
type name[size]

Here the type can be either int, float, double, char or any oher valid data type. The number within the
brackets indicates the size of the array, i.e., the maximum number of elements that can be stored in the array.
ex: int marks[10]

Initialization of arrays

Elements of the array can also be initialized at the time of declaration as in the case of every other variable.
When an array is initialized, we need to provide a value for every element in the array. Arrays are initialized
by writing,
type array_name[size] = { list of values};

The values are written with curly brackets and every value is separated by a comma. It is a compiler error to
specify more number of values than the number of elements in the array.
ex: int marks[5] = {90, 92, 78, 82, 58};

One dimensional Array


• It is also known as one-dimensional arrays or linear array or vectors
• It consists of fixed number of elements of same type
• Elements can be accessed by using a single subscript. eg) a[2]=9;
Eg)

1 3 5 2
a
[0] [1] [2] [3] subscripts or indices

Declaration of Single Dimensional Array Syntax:

E.g. int a[4]; // a is an array of 4 integers char b[6]; //b is an array of 6 characters

Initialization of single dimensional array


Elements of an array can also be initialized.

Rules
a) Elements of an array can be initialized by using an initialization list. An initialization list is a comma
separated list of initializers enclosed within braces.
Eg) int a[3]={1,3,4};
b) If the number of initializers in the list is less than array size, the leading array locations gets
initialized with the given values. The rest of the array locations gets initialized to
0 - for int array
0.0 - for float array
\0 - for character array Eg) int a[2]={1};
a char b[5]={‘A’.’r’,’r’};
b
Usage of single dimensional array
The elements of single dimensional array can be accessed by using a subscript operator([]) and a subscript.

Reading storing and accessing elements:


An iteration statement (i.e loop) is used for storing and reading elements.

Ex:1 Program to calculate the average marks of the class


#include <stdio.h> void main()
{

int m[5],i,sum=0,n; float avg;


printf(“enter number of students \n”); scanf(“%d”,&n);
printf(“enter marks of students \n”); for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}

for(i=0;i<n;i++) sum=sum+m[i]; avg=(float)sum/n; printf(“average=%f”,avg);


}

Output:
Enter number of students 5
Enter marks of students 55
60
78
85
90
Average=73.6
Example Programs
C Program to Find Mean, Median, and Mode of Given Numbers.
#define SIZE 100 #include"stdio.h"
float mean_function(float[],int); float median_function(float[],int); float mode_function(float[],int); int
main()
{
int i,n,choice;
float array[SIZE],mean,median,mode; printf("Enter No of Elements\n"); scanf("%d",&n);
printf("Enter Elements\n"); for(i=0;i scanf("%f",&array[i]);
do
{
printf("\n\tEnter Choice\n\t1.Mean\n\t2.Median\n\t3.Mode\n4.Exit"); scanf("%d",&choice);
switch(choice)
{
case 1: mean=mean_function(array,n); printf("\n\tMean = %f\n",mean); break;

case 2: median=median_function(array,n); printf("\n\tMedian = %f\n",median); break;


case 3: mode=mode_function(array,n); printf("\n\tMode = %f\n",mode); break;
case 4: break; default:printf("Wrong Option"); break;
}
}while(choice!=4);
}
float mean_function(float array[],int n)
{
int i;
float sum=0; for(i=0;i sum=sum+array[i]; return (sum/n);
}
float median_function(float a[],int n)
{
float temp; int i,j; for(i=0;i for(j=i+1;j
{
if(a[i]>a[j])
{
temp=a[j]; a[j]=a[i]; a[i]=temp;
}
} if(n%2==0)
return (a[n/2]+a[n/2-1])/2; else
return a[n/2];
}
float mode_function(float a[],int n)
{
return (3*median_function(a,n)-2*mean_function(a,n));
}
Output
Enter Elements 2
3
4
Enter Choice
1. Mean
2. Median
3. Mode
4. Exit

UNIT III FUNCTIONS AND POINTERS


Introduction to functions: Function prototype, function definition, function call, Built-in functions (string
functions, math functions) – Recursion – Example Program: Computation of Sine series, Scientific
calculator using built-in functions, Binary Search using recursive functions – Pointers – Pointer operators –
Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting of names –
Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of two numbers and
changing the value of a variable using pass by reference

Introduction to functions
A function is a subprogram of one or more statements that performs a specific task when called.
Advantages of Functions:
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
• Based on who develops the function
• Based on the number of arguments a function accepts
1. Based on who develops the function
There are two types.
1. Library functions
2. User-defined functions
1. Library functions [Built-in functions]
Library functions are predefined functions. These functions are already developed by someone and are
available to the user for use. Ex. printf( ), scanf( ).
2. User-defined functions
User-defined functions are defined by the user at the time of writing a program. Ex. sum( ), square( )

Using Functions
A function can be compared to a black box that takes in inputs, processes it, and then outputs the
result. Terminologies using functions are:
 A function f that uses another function g is known as the calling function,
and g is known as the called function.
 The inputs that a function takes are known as arguments.
 When a called function returns some result back to the calling function, it is said to return that result.
 The calling function may or may not pass parameters to the called function. If the called function
accepts arguments, the calling function will pass parameters, else not.
 Function declaration is a declaration statement that identifies a function’s
name, a list of arguments that it accepts, and the type of data it returns.
 Function definition consists of a function header that identifies the function, followed by the body of
the function containing the executable code for that function.

Function Prototype
Before using a function, the compiler must know the number of parameters and the type of parameters that
the function expects to receive and the data type of

value that it will return to the calling program. Placing the function declaration statement prior to its use
enables the compiler to make a check on the arguments used while calling that function.
Syntax:
return_data_type function_name(data_type variable1, data_type variable2,..); Here, function_name is a valid
name for the function. Naming a function follows the same rules that are followed while naming variables. A
function should
have a meaningful name that must specify the task that the function will perform.
return_data_type specifies the data type of the value that will be returned to the calling function as a result of
the processing performed by the called function.
(data_type variable1, data_type variable2, ...) is a list of variables of specified data types.
These variables are passed from the calling function to the called function. They are also known as
arguments or parameters that the called function accepts to perform its task.
Function definition
When a function is defined, space is allocated for that function in the memory. A function definition
comprises of two parts:
 Function header
 Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements

.............
return(variable);
}

While return_data_type function_name(data_type variable1, data_type variable2,...) is known as the function


header, the rest of the portion comprising of program statements within the curly brackets { } is the function
body which contains the code to perform the specific task.
Note that the function header is same as the function declaration. The only difference between the two is that
a function header is not followed by a semi- colon.

Function Call
The function call statement invokes the function. When a function is invoked, the compiler jumps to the
called function to execute the statements that are a part of that function. Once the called function is executed,
the program control passes back to the calling function.
Syntax:
function_name(variable1, variable2, ...);
The following points are to be noted while calling a function:
 Function name and the number and the type of arguments in the function call must be same as that
given in the function declaration and the function header of the function definition.
 Names (and not the types) of variables in function declaration, function call, and header of function
definition may vary.
 Arguments may be passed in the form of expressions to the called function. In such a case, arguments
are first evaluated and converted to the type of formal parameter and then the body of the function gets
executed.

If the return type of the function is not void, then the value returned by the called function may be
assigned to some variable as given below. variable_name = function_name(variable1, variable2, ...);

Working of a function
void main()
{
int x,y,z;
int abc(int, int, int) // Function declaration
…..
…..
abc(x,y,z) // Function Call

… Actual arguments

}

int abc(int i, int j, int k) // Function definition


{ Formal arguments
…….
….
return (value);
}

Calling function – The function that calls a function is known as a calling function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual arguments.
Formal arguments – The arguments of called function are called as formal arguments.
Steps for function Execution:
1. After the execution of the function call statement, the program control is transferred to the called
function.
2. The execution of the calling function is suspended and the called function starts execution.
3. After the execution of the called function, the program control returns to the calling function
and the calling function resumes its execution.

Built-in functions (string functions, math functions)


The standard library functions are built-in functions in C programming to handle tasks such as mathematical
computations, I/O processing, string handling etc. These functions are defined in the header file.
The printf() is a standard library function to send formatted output to the screen (display output on the
screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such as scanf(), fprintf(), getchar() etc.
Once you include "stdio.h" in your program, all these functions are available for use.

Library of Mathematical functions.


These are defined in math.h header file.
Example:

1 double cos(double x)- Returns the cosine of a radian angle x

2 double sin(double x)- Returns the sine of a radian angle x.


3 double exp(double x)- Returns the value of e raised to the xth power

4 double log(double x)
Returns the natural logarithm (base-e logarithm) of x.
5 double sqrt(double x) Returns the square root of x.
6 double pow(double x, double y) Returns x raised to the power of y.

Library of standard input & output functions


Header file: stdio.h Example:
1 printf() This function is used to print the character, string, float, integer,
octal and hexadecimal values onto the output screen
2 scanf() This function is used to read a character, string, and numeric data
from keyboard.
3 getc() It reads character from file
4 gets() It reads line from keyboard

Library of String functions:


Header file: string.h Example:
Functions Descriptions
strlen() Determines the length of a String
strcpy() Copies a String from source to destination
strcmp() Compares two strings

strlwr() Converts uppercase characters to lowercase


strupr() Converts lowercase characters to uppercase
Example: strlen function
#include <stdio.h> int main() {
char string1[20]; char string2[20];
strcpy(string1, "Hello"); strcpy(string2, "Hellooo");
printf("Length of string1 : %d\n", strlen( string1 )); printf("Length of string2 : %d\n", strlen( string2 ));
return 0;
}
Output:
Length of string1 : 5 Length of string2 : 7
Example: strcpy function
#include <stdio.h> int main() {
char input_str[20]; char *output_str;
strcpy(input_str, "Hello"); printf("input_str: %s\n", input_str); output_str = strcpy(input_str, "World");

printf("input_str: %s\n", input_str); printf("output_str: %s\n", output_str); return 0;


}
Output:
input_str: Hello input_str: World output_str: World

UNIT IV STRUCTURES

Structure - Nested structures – Pointer and Structures – Array of structures – Example Program using
structures and pointers – Self referential structures – Dynamic memory allocation - Singly linked list -
typedef

Introduction
Using C language we can create new data types. These data types are known as User Defined data types &
can be created by using Structures, Unions & Enumerations.
Need for Structure
Arrays can store data of same data type. They can’t be used to store data of different data types. For this
Structures are used.
Structures
A structure is a collection of variables of different types under a single name. It is used for storing different
types of data.
3 aspects:
1. Defining a structure type
2. Declaring variables
3. Using & performing operations.
Structure Definition
The structure can be defined with the keyword struct followed by the name of structure and opening brace
with data elements of different type then closing brace with semicolon.
General Form
struct [structure tag name]
{
type membername1; type membername2;
……
}[variable name];
E.g.
struct book
{
char title[25]; int pages;

float price;
};
• Structure definition does not reserve any space in the memory.
• It is not possible to initialize the structure members during the structure definition.
• A structure definition must always be terminated with a semicolon.
Rules for Structure members
1. A structure can have data of different types
2. A structure can’t contain an instance of itself.

E.g.
struct box
{
struct box a; // not possible
};
3. A structure can contain members of other complete types.
E.g.

struct name
{
char firstname[20]; char lastname[20];
};
struct person
{
struct name personname; float salary;
}

4. A structure can contain a pointer to itself;


Declaration

Variables of structure type can be declared either at the time of structure definition or after the structure
definition.
General Form
struct structurename variablename[=initialization list]; E.g.
struct book b1,b2;
struct book b3={“CP”,500,385.00};
Accessing Members of Structure
There are two types of operators used for accessing members of a structure.
1. Direct member access operator (dot operator) (.)
2. Indirect member access operator (arrow operator) (->)
Using Dot operator General form:
structure variable name.member variable name E.g.
Suppose, we want to access title of structure variable b1, then, it can be accessed as:
b1.title
We can also directly assign values to members.
b1.title= “CP”;
Structures within a Structure (Nested Structures)
A structure can be nested within another structure. Structure within structure is known as nested structure
i.e.) one structure can be declared inside other.

Example program: #include<stdio.h> struct name


{
char fname[20],lastname[20];
};
struct student
{
int sno,m1,m2,m3;
int tot;
float avg;
struct name sname;
};
void main()
{
struct student s[10]; float,avg;
int n,i;
printf(“Enter the number of students \n”); scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter student details \n”); scanf(“%d”,&s[i].sno); scanf((“%d%d%d”,&s[i].m1, &s[i].m2, &s[i].m3);
scanf(“%s”, s[i].sname.fname);
scanf((“%s”,s[i].sname.lastname);
s[i].tot=s[i].m1+s[i].m2+s[i].m3; s[i].avg=s[i].tot/6.0;
}
printf(“Student Mark lists\n”); for(i=0;i<n;i++)
printf(“%s\t%s\t%f”,s[i].sname.fname, s[i].sname.lastname,s[i].avg);
}
Output:
Enter the number of students 2
Enter student details

1 70 58 68 AjithKesav
2 90 86 95 RishikKesav

Student Mark lists AjithKesav 70.000


RishikKesav 90.000
Accessing members in nested structure
E.g) s[i].sname.lastname

nested structure
Pointer and Structures

It is possible to create a pointer to a structure. A Structure containing a member that is a pointer to the same
structure type is called self referential structure. A pointer variable for the structure can be declared by
placing an asterisk(*) in front of the structure pointer variable.
Syntax:
struct namedstructuretype
*identifiername;
Example:
struct struct_name
{

data_type member_name1; data_type member_name2;


.....................................
}*ptr;
OR
struct struct_name *ptr;
Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to access the
data using pointer variable.
UNIT V FILE PROCESSING

Files – Types of file processing: Sequential access, Random access – Sequential access file - Example
Program: Finding average of numbers stored in sequential access file - Random access file -Example
Program: Transaction processing using random access files – Command line arguments

Introduction
A file is a semi-permanent, named collection of data. A File is usually stored on magnetic media, such as a
hard disk or magnetic tape. Semi-permanent means that data saved in files stays safe until it is deleted or
modified.
Named means that a particular collection of data on a disk has a name, like mydata.dat and access to the
collection is done by using its name.
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 readymade structure.
Types of Files
1. Text files
2. Binary files
1. Text Files
A text file consists of consecutive characters, which are interpreted by the library functions used to access
them and by format specifiers used in functions.
Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
They take minimum effort to maintain, are easily readable, and provide least security and takes bigger
storage space.
2. Binary files
A binary file consists of bytes of data arranged in continuous block. A separate set of library functions is
there to process such data files.
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store it in the
binary form (0's and 1's). They can hold higher amount of data, are not readable easily and provides a better
security than text files.
File Operations
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
Function description
fopen() - create a new file or open a existing file fclose() - closes a file
getc() - reads a character from a file putc() - writes a character to a file fscanf() - reads a set of data from a
file fprintf() - writes a set of data to a file getw() - reads a integer from a file putw() - writes a integer to a file
fseek() - set the position to desire point ftell() - gives current position in the file
rewind() - sets the position to the beginning point
1. Opening a File or Creating a File
Opening a file means creating a new file with specified file name and with accessing mode.
The fopen() function is used to create a new file or to open an existing file.
Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
filename is the name of the file to be opened and mode specifies the purpose of opening the file.
Mode can be of following types:
Mode Description
Mode Purpose
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
2. Closing a File
A file must be closed after all the operation of the file have been completed. The fclose() function is used to
close an already opened file.
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.

3. Reading and writing to a text file


i. Read a character from a file: fgetc function
The ‘fgetc’ function is used to read a character from a file which is opened in read mode.
Syntax:
c=fgetc(p1);
where p1 is the file pointer.
ii. Read a data from a file: fscanf function
The fscanf function is used to read data from a file. It is similar to the scanf function except that fscanf() is
used to read data from the disk.
Syntax:
fscanf(fb “format string”, &v1, &v2…&vn);
where fb refers to the file pointer. v1, v2, … vn refers variables whose values are read from the disk “format
string” refers the control string which represents the conversion specification.
iii. Write a character to a file:fputc function
The function ‘fputc’ is used to write a character variable x to the file opened in write mode.
Syntax:
fputc(x,fp1);
where fp1 is the file pointer.
iv. Writing data to a file : fprintf()
fprintf() function is used to write data to a file. It is similar to the printf() function except that fprintf() is
used to write data to the disk.
Syntax:
fprintf(fp, “format string”, v1,v2… vn); where fp refers to the file pointer.
Types of file processing
There are two main ways a file can be organized:
1. Sequential Access — In this type of file, the data are kept sequentially. To read last record of the file,
it is expected to read all the records before that particular record. It takes more time for accessing the
records.
2. Random Access — In this type of file, the data can be read and modified randomly. If it is desired to
read the last record of a file, directly the same record can be read. Due to random access of data, it takes less
access time as compared to the sequential file.
Sequential Access File
A Sequential file is characterized by the fact that individual data items are arranged serially in a sequence,
one after another. They can only be processed in serial order from the beginning. In other words, the records
can be accessed in the same manner in which they have been stored. It is not possible to start reading or
writing a sequential file from anywhere except at the beginning.
Random Access File
The second and better method of arranging records of a file is called direct access or random access. In this
arrangement one can have access to any record which is situated at the middle of the file without reading or
passing through other records in the file.
Reading Sequential Access file
Data is stored in files so that the data can be retrieved for processing when needed
Example:
clients.dat file contents
100 Jones 9023.00
200 Frank 234.00
300 Mano 29023.00
400 Bala 2344.00
Program:
// Reading and printing a sequential file #include <stdio.h>
#include <stdlib.h> int main(void) {
unsigned int account; // account number char name[30]; // account name double balance; // account
balance
FILE *cfPtr; // cfPtr = clients.dat file pointer
// fopen opens file; exits program if file cannot be opened if ((cfPtr = fopen("clients.dat", "r")) == NULL)
{ puts("File could not be opened");
exit(0);
}
printf("%-10s%-13s%s\n", "Account", "Name", "Balance"); fscanf(cfPtr, "%d%29s%lf", &account, name,
&balance);
// while not end of file while (!feof(cfPtr)) {
printf("%-10d%-13s%7.2f\n", account, name, balance); fscanf(cfPtr, "%d%29s%lf", &account, name,
&balance);
} // end while

fclose(cfPtr); // fclose closes the file


} // end main
Output:
Account Name Balance
100 Jones 9023.00
200 Frank 234.00
300 Mano 29023.00
400 Bala 2344.00
Read numbers from file and calculate Average
/* Program to read from the num.dat file and find the average of the numbers */
#include <stdio.h> #include <stdlib.h>
#define DATAFILE "prog15.dat" int main() {
FILE* fp;
int n[50], i = 0; float sum = 0;
if ((fp = fopen(DATAFILE, "r")) == NULL) {
printf("Unable to open %s. \n", DATAFILE); exit(0);
}
puts("Reading numbers from num.dat"); while (!feof(fp)) {
fscanf(fp, "%d ", &n[i]);
printf("%d %d\n", i, n[i]); sum += n[i];
i++;
}
fclose(fp);
// if no data is available in the file if (i == 0)
printf("No data available in %s", DATAFILE);
float average = sum / i;

printf("The average is %.3f for %d numbers\n", average, i); return 0;


}

You might also like