0% found this document useful (0 votes)
11 views297 pages

Introduction to C Programming Basics

The document provides an introduction to computer programming in C, covering fundamental concepts such as problem-solving techniques, algorithms, flowcharts, and the structure of a C program. It discusses the characteristics of computers, the difference between hardware and software, and various programming languages including low-level and high-level languages. Additionally, it outlines the steps involved in compiling and executing a C program, as well as the use of Integrated Development Environments (IDEs).

Uploaded by

divyacse4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views297 pages

Introduction to C Programming Basics

The document provides an introduction to computer programming in C, covering fundamental concepts such as problem-solving techniques, algorithms, flowcharts, and the structure of a C program. It discusses the characteristics of computers, the difference between hardware and software, and various programming languages including low-level and high-level languages. Additionally, it outlines the steps involved in compiling and executing a C program, as well as the use of Integrated Development Environments (IDEs).

Uploaded by

divyacse4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS25C01 Computer Programming: C

MODULE-1
Introduction to C: Problem Solving, Problem Analysis Chart, Developing an Algorithm,
Flowchart and Pseudocode, program structure, Compilation & Execution process, Interactive
and Script mode, Comments, Indentation, Error messages, Primitive data types, Constants,
Variables, Reserved words, Arithmetic, Relational, Logical, Bitwise, Assignment, Conditional
operators, Input/Output Functions, Built-in Functions.
Practical: Create Problem Analysis Charts, Flowcharts and Pseudocode for simple C programs
(Minimum three).

Define Computer:
Computer is a calculating machine, which accepts data through input device, processes it using
processing device and give the result through output device. Computer is an electro-
mechanical machine. It consists of electronic parts (IC‟S) electrical (motors, fan) and
Mechanical parts (Outer cover, keyboard).

Characteristics of Computer:
The following are the characteristics of a computer:
1. Speed: Computer can process the data at an extremely high speed.
2. Accuracy: Computer will produce accurate result.
3. Reliability: It is the measurement of performance of computer.
4. Versatile: Computer can be used for different purpose.
5. Storage capacity: computer can store large amount of data.

Block Diagram of a Computer:


Computer has five fundamental units:
1. Input unit: Through which data will be fed into the computer

Example: Keyboard, Mouse, Microphone, Joystick, Web camera


Keyboard is the standard input unit.
2. Storage unit: It is used to store the data/ Information.
Two types:
(i) Primary Storage Unit / Primary Memory
Example: Random Access Memory (RAM)
(ii) Secondary Storage Unit/ Secondary Memory
Example: Hard Disk Drive (HDD)/ Solid State Device (SSD)
3. Control Unit: Controls all other units.
4. Arithmetic and Logical Unit: Does the computation.
Note: Control Unit and Arithmetic and Logical unit put together called as
Central Processing Unit or CPU. A single chip CPU is called Microprocessor.
5. Output Unit: Through which result will be displayed to the external world
Example: Monitor, Speaker, Projector, Printer
Monitor is the standard output unit.
Output generated using printer is called Hardcopy output.

Hardware: All the physical parts of the computer is called hardware. You can touch and feel.
Example: Keyboard, Mouse, outer cover, IC‟s
Software:Programs written for the computer is called software. Ex: MS-Word, C program,
Windows 10 OS
Operating System:It is the interface between user of the computer and computer hardware.
Text Editor: It is an application program which allows user to type text and edit it.

Computer Languages:
Machine Level Language (MLL) : Binary language it use 1 and 0. It is the only language
understood by the computer.
Assembly Level Language (ALL) : It uses short notations like add, sub, mul and div etc.
It cannot be understood by the computer. Hence ALL needs to be converted into MLL
Assembler: is the program, which converts ALL to MLL and vice versa.
Example for ALL: ALL 8085, ALL 8086

High Level Language (HLL) : It is English like language. It is easy to understand by the
programmer.
It cannot be understood by the computer.
HLL needs to be converted into MLL.
Compiler or Interpreter will be used to convert HLL to MLL and vice versa.
Compiler: converts HLL to MLL in one step.
Interpreter: Converts HLL to MLL line by line.
Example: C,C++, Java

[Link] solving
Problem solving in computer programming is the iterative process of understanding a problem,
devising a detailed step-by-step solution (an algorithm), and translating that solution into a
computer program. Key stages include defining and analyzing the problem to determine inputs
and outputs, developing an algorithm using natural language or flowcharts, coding the
algorithm into a programming language, and testing and debugging the program to ensure it
works correctly. This core skill allows programmers to break down complex issues into
manageable steps for a computer to execute.

Steps in the Problem-Solving Process


1. Understand and Define the Problem:
Clearly understand what needs to be solved by identifying the problem's requirements, inputs,
and expected outputs.
2. Analyze the Problem:
Break down the problem into smaller, more manageable parts to identify its principal
components and core functionalities.
3. Develop a Solution (Algorithm):
Create a step-by-step plan for the computer to follow. This is often done in natural language
(like pseudocode) or through visual aids like flowcharts.
4. Code the Solution:
Translate the algorithm into a specific programming language that the computer can
understand and execute.
5. Test and Debug:
Rigorously test the coded solution with various inputs to find and fix errors (bugs) to ensure
the program functions as intended.
6. Review and Refine:
Evaluate the overall effectiveness of the solution and refine it for clarity, efficiency, and
completeness.

[Link] Analysis Charts


A Problem Analysis Chart (PAC) is a structured tool used to break down a problem into key
components. It helps to systematically understand the problem, identify necessary data, and
develop a structured approach to solve it. In the context of algorithms and flowcharts, PACs
serve as the initial step in problem-solving by organising information that will be used to
visualise and implement the solution.
The PAC breaks the problem into smaller parts. It helps us to bring a logical sequence to our
thought process and help us arrive at better solutions.

How PACs, Algorithms, and Flowcharts Interrelate


PACs, algorithms, and flowcharts are interconnected in problem-solving:

 PACs provide a structured approach to analyse the problem by identifying inputs,


outputs, processes, and alternative solutions.
 Flowcharts visually represent the steps and decision points outlined in the PAC,
making it easier to understand and communicate the solution process.
 Algorithms are step-by-step procedures derived from the PAC and visualised through
flowcharts. They provide a logical sequence of operations to solve the problem.

By integrating PACs, algorithms, and flowcharts, we can systematically analyse problems,


visualise the solution process, and implement efficient solutions. This structured approach
enhances our problem-solving skills and ensures that solutions are well-organized, efficient,
and easy to understand. The interactive activity demonstrates how a simple algorithm can be
visualised and implemented, reinforcing the concepts of PACs and flowcharts in a practical
context.

[Link]:It is the step-by-step procedure to solve a given problem. It will accept input,
processes and gives output. It is simple to represent and it is independent of programming
language.
Example:
I. Write an algorithm to exchange the contents of two variable.
1. [Start]

2. [Input two numbers]


Read(x,y)
3. [Process two swap two numbers]
t <- x
x <- y
y <- t
4. [Output – to print the swapped numbers]
Write (x,y)
5. [Stop]

II. Write an algorithm to find the area of a triangle given base and height.
1. [Start]
2. [Input – Base and height of the triangle]
Read(b,h)
3. [Process – to compute the area of the triangle]
a <- 0.5*b*h
4. [Output the area]
Write (a)
5. [Stop]

III. Write an algorithm to find the area of a triangle given its 3 sides.
1. [Start]
2. [Input – 3 sides of the triangle]
Read(a,b,c)
3. [Process – to compute half perimeter]
s<- (a+b+c)/2.0
4. [Process to compute the area ]
a <- sqrt( s * (s-a) * (s-b) * (s-c) )
5. [Output the area]
Write (a)
6. [Stop]

IV. Write an algorithm to compute the area of a circle


1. [Start]
2. [Input – radius of the circle]
Read(r)
3. [Initialize]
p <- 3.14
4. [Process – to compute the area of the circle]
a <- (p * r *r)
5. [Output the area]
Write (a)
6. [Stop]
V. Write an algorithm to check whether the given number is odd or even
1. [Start]
2. [Input a number]
Read(n)
3. [Compute the reminder]
r <- n modulo 2
4. [ process to check whether the given number is odd or even using reminder value]
If (r = 0)
Write (“Given number is Even”)
Else
Write (“Given number is Odd”)
5. [Stop]

VI. Write an algorithm to compute the sum of first ‘n’ natural numbers
1. [Start]
2. [Input a number]
Read(n)
3. [Initialize]
sum < - 0
4. [compute the sum of first „n‟ numbers ]
for i <- 1 to n step 1
sum <- sum + i
end for
5. [Display the sum]
Write(sum)
6. [Stop]
VII. Write an algorithm to compute the factorial of the given number

1. [Start]
2. [Input a number]
Read(n)
3. [Initialize]
fact < - 1
4. [compute the factorial of „n‟ ]
for i <- 1 to n step 1
fact <- fact* i
end for
5. [Display the sum]
6. [Stop]

4. Flow chart:
It is the pictorial representation of an algorithm. All the steps are drawn in the form of
different shapes. Commonly used symbols for flow chart are :

Write a flowchart to exchange contents of two variables:


Write a flowchart to compute the area of a triangle

5. Pseudocode
Pseudocode is an informal, high-level description of an algorithm or program logic. It uses a
mix of natural language (like English) and common programming constructs to outline the
steps involved in a process, without adhering to the strict syntax rules of any specific
programming language.

Key characteristics of pseudocode:

 Human-readable:
It is designed for human understanding, not for execution by a computer.
 Language-independent:
It can be understood by programmers regardless of their preferred programming language.
 Focus on logic:
It emphasizes the sequence of operations and decision-making within an algorithm.
 Informal syntax:
While it often uses keywords like IF, ELSE, FOR, WHILE, PRINT, etc., it does not require
precise punctuation or grammar like actual code.
 Indentation for structure:
Indentation is commonly used to show the hierarchical structure of control flow (e.g., within
loops or conditional statements).
Purpose of pseudocode:

 Algorithm design:
It helps in planning and structuring algorithms before writing actual code.
 Communication:
It facilitates communication and understanding of algorithms among developers, designers,
and project managers.
 Problem-solving:
It allows focusing on the logical steps to solve a problem without getting bogged down by
language-specific syntax.
 Documentation:
It can serve as a form of documentation for algorithms.

Example
START
DECLARE variable 'number'
GET input from user and STORE in 'number'

IF 'number' IS GREATER THAN 0 THEN


PRINT "The number is positive."
ELSE IF 'number' IS LESS THAN 0 THEN
PRINT "The number is negative."
ELSE
PRINT "The number is zero."
END IF
END

Difference between Flowchart and Pseudocode


Flowchart Pseudocode

A Pseudocode is a step-by-step
A Flowchart is pictorial representation of
description of an algorithm in code like
flow of an algorithm.
structure using plain English text.
Flowchart Pseudocode

A Flowchart uses standard symbols for input,


output decisions and start stop statements. Pseudocode uses reserved keywords like
Only uses different shapes like box, circle if-else, for, while, etc.
and arrow.

This is a way of visually representing data, These are fake codes as the word pseudo
these are nothing but the graphical means fake, using code like structure but
representation of the algorithm for a better plain English text instead of programming
understanding of the code language

Pseudocode is better suited for the


Flowcharts are good for documentation
purpose of understanding

6. Introduction to C
C is a programming language developed at AT & T‟s Bell Laboratories of USA in 1972. It
was designed and written by a man named Dennis Ritchie. In the late seventies C began to
replace the more familiar languages of that time like PL/I, ALGOL, etc.

A computer program is just a collection of the instructions necessary to solve a specific


problem. The basic operations of a computer system form what is known as the computer‟s
instruction set. And the approach or method that is used to solve the problem is known as an
algorithm.
So for as programming language concern these are of two types.
1) Low level language

2) High level language

Low level language:


Low level languages are machine level and assembly level language. In machine level
language computer only understand digital numbers i.e. in the form of 0 and 1. So, instruction
given to the computer is in the form binary digit, which is difficult to implement instruction in
binary code. This type of program is not portable, difficult to maintain and also error prone.
The assembly language is on other hand modified version of machine level language. Where
instructions are given in English like word as ADD, SUM, MOV etc. It is easy to write and
understand but not understand by the machine. So the translator used here is assembler to
translate into machine level.

High level language:


These languages are machine independent, means it is portable. The language in this
category is Pascal, Cobol, Fortran etc. High level languages are understood by the machine.
So it need to translate by the translator into machine level. A translator is software which is
used to translate high level language as well as low level language in to machine level
language. Three types of translator are there:
 Compiler

 Interpreter

 Assembler
Compiler and interpreter are used to convert the high level language into machine
level language. The program written in high level language is known as source program and
the corresponding machine level language program is called as object program. Both
compiler and interpreter perform the same task but there working is different. Compiler read
the program at-a-time and searches the error and lists them. If the program is error free then
it is converted into object program. When program size is large then compiler is preferred.
Whereas interpreter read only one line of the source code and convert it to object code. If it
check error, statement by statement and hence of take more time.

Integrated Development Environments (IDE)


The process of editing, compiling, running, and debugging programs is often managed by a
single integrated application known as an Integrated Development Environment, or IDE for
short. An IDE is a windows-based program that allows us to easily manage large software
programs, edit files in windows, and compile, link, run, and debug programs.

On Mac OS X, CodeWarrior and Xcode are two IDEs that are used by many programmers.
Under Windows, Microsoft Visual Studio is a good example of a popular IDE. Kylix is a
popular IDE for developing applications under Linux. Most IDEs also support program
development in several different programming languages in addition to C, such as C# and
C++.

6.1 BASIC STRUCTURE OF A C PROGRAM


The basic structure of a C program is divided into 6 parts which makes it easy to read,
modify, document, and understand in a particular format. C program must follow the below-
mentioned outline in order to successfully compile and execute. Debugging is easier in a
well-structured C program.
Sections of the C Program
There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

Example:

// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20

// Global Declaration
int sum(int y);

// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}

// Subprogram
int sum(int y)
{
return y + X;
}

[Link] involved in the Compilation and execution of a C program:


 Program Creation
 Compilation of the program
 Execution of the program
 The output of the program

 The compilation is the process of converting the source code of the C language into
machine code. As C is a mid-level language, it needs a compiler to convert it into an
executable code so that the program can be run on our machine.
 The C program goes through the following phases during compilation:
Working Process

7. Interactive and Script mode

 In the context of C programming, "interactive mode" and "script mode" refer to how
C programs are typically developed and executed, although the terminology is more
commonly associated with interpreted languages like Python.

Interactive Mode (for C):

 While C is a compiled language, elements of "interactive mode" can be experienced


during development through tools like debuggers or integrated development
environments (IDEs) with interactive features.

 In a C debugger, you can set breakpoints, step through code line by line, inspect
variable values, and even modify variables during runtime. This provides immediate
feedback on specific parts of your code.

 Debugging, testing small code snippets, understanding program flow, and exploring
variable states during execution.
Script Mode (for C):
:
 This is the standard way to develop and run C programs. You write your entire
program in source code files (e.g., .c files).

 The C source code is compiled into an executable binary file using a C compiler (like
GCC). This executable is then run as a complete program.

 Developing full-fledged applications, creating reusable libraries, and deploying


production-ready software.

8. Comments
Comments in C programming are non-executable statements within the source code that are
ignored by the compiler. Their primary purpose is to provide explanations, documentation,
and notes for human readers of the code, improving readability and maintainability.

C supports two types of comments:


 Single-line comments:
o Syntax: // Your comment here
o These comments begin with two forward slashes (//) and extend to the end of the current
line. They are suitable for brief explanations of individual lines or small sections of code.
C
int x = 10; // Initialize variable x with value 10

 Multi-line comments (Block comments):


o Syntax: /* Your multi-line comment here */
o These comments begin with /* and end with */. They can span multiple lines and are
typically used for longer explanations, function descriptions, or for temporarily commenting
out blocks of code during development or debugging.

9. Indentation in C

Indentation in C programming refers to the use of whitespace, typically spaces or tabs, at


the beginning of lines of code to visually indicate the structure and hierarchy of the
program. While C compilers do not strictly enforce indentation for code execution (unlike
languages like Python where it is syntactically mandatory), it is crucial for code readability
and maintainability.

[Link] Meassages
In C programming, "errors" refer to issues that prevent a program from compiling or
executing correctly. These errors can be categorized into several types:
 Syntax Errors:
Occur when the code violates the grammatical rules of the C language.
Examples include missing semicolons, unbalanced brackets, or misspelled keywords.
Detected by the compiler during the compilation phase, preventing the creation of an
executable.
 Linker Errors:
Arise during the linking phase, when the linker attempts to combine object files and
libraries to create a final executable.
Occur if the linker cannot find the definitions for functions or variables that have been
declared in the code but not defined (e.g., missing library files).
 Runtime Errors:
Happen while the program is executing.
Often caused by illegal operations, such as division by zero, accessing invalid memory
locations, or attempting to open a non-existent file.
Can lead to program crashes or unexpected behavior.
 Logical Errors:
The program compiles and runs without crashing, but it produces incorrect or
unexpected output.
Result from flaws in the program's algorithm or logic, where the code does not correctly
implement the intended functionality.
 Compiler Warnings:
Not strictly errors, but indications of potential issues in the code that might lead to
problems later.
Examples include uninitialized variables or non-standard coding practices.
While warnings do not prevent compilation, it is best practice to address them to avoid
future errors.
 Preprocessor Errors:
Occur during the preprocessor stage, before compilation.
Can be caused by issues with preprocessor directives, such as incorrect use
of #include or inability to locate a referenced header file.
 Memory Errors:
A specific type of runtime error related to memory management.
Examples include memory leaks (failure to free dynamically allocated memory) or
attempting to access memory that has already been freed.
11.C Tokens: Character set, Identifiers, Keywords, constants, Data types, type
qualifiers, Declaration and Initialization of variables.

Token: The smallest individual units in a program are called tokens. The „C‟

Tokens are classified as:

1. Character set
2. Keywords
3. Identifiers
4. Constants
5. Operators

Character set:

Character set consists of


i) alphabet from A-Z or a-z
ii) digits from 0-9
iii) Special characters like (,), {,}, [,], <, >, &, $, #, %, ^, !, ?, :, ;, ",', .
iv) White space character: blank space
v) Escape sequences:

\b backspace
\a audible bell
\v vertical tab
\t horizontal tab
\f form feed
\r carriage return
\” double quotes
\‟ single quotes
\\ back slash

\r is a carriage return character; it tells your terminal emulator to move the cursor at the
start of the line.
The cursor is the position where the next characters will be rendered.
So, printing a \r allows overriding the current line of the terminal emulator.

Example Program:

#include<stdio.h> main()
{

printf("Backspace Character\b");
printf(" Audible Bell\a\n");
printf("Vertical Tab\vDemonstration\n");
printf("Horizental Tab\tDefault 8 spaces\n");
printf("Form feed\fIt is only with Printer\n");
printf("Carriage Return\rmove the cursor at the start of the line\n");
printf("Single Quotes The \"Sun\" rises in the \'east\'\n");
printf("Backslash \\hai\n");
}

Output:

Backspace Characte Audible Bell Vertical Tab


Demonstration Horizental Tab
Default 8 spaces Form feed
It is only with Printer
move the cursor at the start of the line
Double quotes and Single Quotes The "Sun" rises in the 'east' Backslash \hai

12.1 Keywords:

Keywords are reserved words. All keywords have fixed meanings. Keywords serve as
basic building blocks for program statements. In „C‟, there are 32 keywords. All
keywords must be written in lower case.

These 32 keywords are classified into 3 types namely

1. Type related Keywords (16)


2. Storage related Keywords (4)
3. Control flow related Keywords (12)

Type related Keywords:

int short void enum


float long struct const
char signed union volatile
double unsigned typedef sizeof

Storage related keywords:

auto static register extern


Control flow related keywords:

if default goto for


else case continue while
switch break return do

12.2 Identifiers: Identifier refers to the names of the variables, functions and arrays.

Rules to name a particular identifier:

1. It must start with either alphabet or underscore.


2. Remaining letters may be alphabet, digit, underscore.
3. Identifier would not allow any special symbol except underscore.
4. An identifier can be of any length while most compilers of „C‟ language
recognize only the first 8 characters.
5. Do not use keywords as an identifier.

12.3 Constants:

Constants refer to fixed values that do not change during the execution of a program.

Constants are 2 types.


1. Numerical constants
2. Non-numerical constants

Numerical Constants are 2 types.


i. Integer constants
ii. Real constants

Non- Numerical Constants are 2 types.


i. Character constants
ii. String or multiple character constants

Integer constants:

An integer constant refers to a sequence of digits. There are three types of


integers, namely, decimal, octal and hexadecimal.

 Decimal integers consist of a set of digits, 0 through 9, preceded by an


optional – or + sign.
 Valid examples of decimal integer constants are: 321, -
789, 0, +77
 An octal integer constant consists of any combination of digits from the set
0 through 7, with leading 0.
 Some examples of octal integers are 047, 0,
0543, 0655

 Hexadecimal integer constant consists of a sequence of digits preceded by


0x or 0X.
 They may also include alphabets A through F or a through f. (0 – 9
and A – F or a – f)
 Examples of hexadecimal integer constants are: 0X49,
0x8D

Real constants:

 Some quantities vary continuously, such as distances, heights, temperatures,


prices and so on.
 These quantities are represented by numbers containing fractional parts.
Such numbers are called real or floating point constants.
 A real constant is a sequence of digits with a decimal point.
 Examples of real constants are: 0.00876,
-0.456, 543.78, +247.0
 A real number may also be expressed in exponential or scientific notation.
 Example is:
The value 289.45 may be written as 2.8945e2 in exponential notation.
General form is:
mantissa e exponent
 The mantissa is either a real number expressed in decimal notation or an
integer.
 The exponent is an integer number with an optional plus or minus sign.
 The letter e is either in lowercase or uppercase.

Single Character constants (Character constant):

 A single character constant contains a single character (alphabet, digit,


special symbol, white space) enclosed within a pair of single quote marks.
 Examples are: '1', 'a', '
','@'

Note: Character constants have integer values known as ASCII values. Since each
character constant represent an integer value, so character arithmetic is possible.

Example Program:

#include<stdio.h> main()
{
char ch='a'; printf("ch=%c\n",ch);
printf("ASCII value of \'%c\'=%d\n",ch,ch);
}

Output:
ch=a
ASCII value of 'a'=97
//Character Arithmetic
#include<stdio.h> main()
{

char ch='a'; printf("ch=%c\n",ch);


ch=ch+2;
printf("ASCII value of %c=%d\n",ch,ch);
}

Output:
ch=a
ASCII value of c=99

String constants (Multiple characters):

 String is a sequence of characters enclosed in double quotes.


 The characters may be an alphabet, digit, special symbol and white space.
 Each and every string ends with null character '\0'.
 Examples are:
"ab", "ab5", "@an", "6*7"

12.4 variables in C:
In C programming, a variable is a named storage location in memory used to hold
data. Variables are fundamental for storing and manipulating information during
program execution.

Key aspects of variables in C:


Declaration: Before a variable can be used, it must be declared. This involves specifying
its data type and a unique name. The data type determines the kind of data the variable
can store (e.g., int for integers, float for floating-point numbers, char for characters) and
the amount of memory it will occupy.

int age; // Declares an integer variable named 'age'


float price; // Declares a float variable named 'price'
char initial; // Declares a character variable named 'initial'
Initialization: Variables can be assigned a value at the time of declaration or later in the
program.

int count = 10; // Declares and initializes 'count' to 10


float temperature;
temperature = 25.5; // Assigns a value to 'temperature' later

Naming Rules:
Variable names must follow specific rules:
They can contain letters (A-Z, a-z), digits (0-9), and underscores (\_).
They must begin with a letter or an underscore.
They are case-sensitive (e.g., myVar and myvar are different).
They cannot be C reserved keywords (e.g., int, float, if).
They cannot contain spaces or other special characters.
Scope and Lifetime:
Variables have a defined scope (where they are accessible in the code) and lifetime (how
long they exist in memory). Common types include:
Local variables: Declared inside a function, accessible only within that function,
and exist only while the function is executing.
Global variables: Declared outside any function, accessible throughout the entire
program, and exist for the program's entire execution.
Static variables: Retain their value between function calls.
Usage:
Once declared and potentially initialized, variables can be used in expressions,
assignments, function calls, and input/output operations.
Example:
int num1 = 5;
int num2 = 3;
int sum = num1 + num2; // Using variables in an expression
printf("Sum: %d\n", sum); // Displaying the variable's value
12.5 Data types:

Data type specifies which type of data that we are storing in a variable. There are 3 types
of data types.

1. Primary or primitive or fundamental data types


2. User defined data types
3. Derived data types
4. Empty data set
Primary data types:

There four fundamental data types.

i. Integer
ii. Floating point
iii. Character
iv. Double precision floating point

Integer:

'C' provides three different classes of integers.


They are
a) int
b) short int
c) long int
The difference between these 3 integers is the number of bytes to occupy the range of
values.

Typ Bytes Bits Range


e
signed short int or 2 16 -32768 to 32767
short int
signed int or int 2/4 16/32 -32768 to 32767 or -2147483648 to
2147483647
signed long int or 4 32 -2147483648 to 2147483647
long int
unsigned short int 2 16 0 to 65535
unsigned int 2/4 16/32 0 to 65535 or 0 to 4294967295
unsigned long int 4 32 0 to 4294967295
Integers are whole numbers with a range of values supported by a particular machine.
Integers occupy one word of storage, and since the word sizes of machines vary
(typically 16 or 32 bits).

The size of an integer that can be stored depends on the computer.

Signed integer uses one bit for sign and 15 bits for the magnitude of the number.

Formula to find number of bits occupied by data type when number of bytes is known:
-2n-1 to 2n-1 - 1
Floating point types:

Floating point or real numbers are stored in 32 bits (on all 16 bit and 32 bit machines)
with 6 bits precision.
3 classes of floating point types:
i. float
ii. double
iii. long double

Type Bytes Bits Range Precision


float 4 32 3.4E-38 to 3.4E+38 6 bits
double 8 64 1.7E-308 to 1.7E+308 14 bits
long double 12 96 3.4E-4932 to 1.1E+4932 19 bits

Character types:

A single character can be defined as a character type data.

Type Bytes Bits Range


signed char 1 8 -128 to 127
unsigned char 1 8 0 to 255

//Program to find number of bytes occupied by primary data types:

#include<stdio.h> main()
{

printf("signed char size=%d\n",sizeof(char)); printf("signed


short int size=%d\n",sizeof(short int)); printf("signed int
size=%d\n",sizeof(int)); printf("signed long int
size=%d\n",sizeof(long int));
printf("unsigned char size=%d\n",sizeof(unsigned char)); printf("unsigned
int size=%d\n",sizeof(unsigned int));
printf("unsigned short int size=%d\n",sizeof(unsigned short int)); printf("unsigned
long int size=%d\n",sizeof(unsigned long int)); printf("float
size=%d\n",sizeof(float));
printf("double size=%d\n",sizeof(double)); printf("long double
size=%d\n",sizeof(long double));
}
Output:

signed char size=1 signed short


int size=2 signed int size=4
signed long int size=4 unsigned
char size=1 unsigned int size=4
unsigned short int size=2 unsigned
long int size=4 float size=4
double size=8
long double size=12

User defined data types:

 'C' supports a feature known as “type definition” that allows users to define an
identifier that would represent an existing data type.
 The user defined data type identifier can later be used to declare variables.

General form:

typedef type identifier

where type is any existing data type, identifier is a new name given to the data
type.

Examples: typedef int


units;
typedef float marks; units
u1,u2;
marks m1, m2;
 The main advantage of typedef is that we can create meaningful data type
names for increasing the readability of the program.
 typedef is mainly used in the concepts of structure and union.

Example program:
#include<stdio.h> int main()
{

typedef int units; typedef


float marks; units a,b;
marks x,y;
printf("Enter 2 values\n");
scanf("%d%d",&a,&b); printf("Enter 2
values\n"); scanf("%f%f",&x,&y);
printf("a=%d\tb=%d\n",a,b);
printf("x=%f\ty=%f\n",x,y);
}

Output:
Enter 2 values
5
6
Enter 2 values
1.9
6.7
a=5 b=6
x=1.900000 y=6.700000

Enumerated data type provided by ANSI standard. It is defined as:

enum identifier {value1,value2,…,valuen};

 Where identifier is a user defined enumerated data type, which can be used to
declare variables which can have one of the values enclosed within the braces
(known as enumeration constants).
 After this definition, we can declare variables to be of this 'new' type.

enum identifier v1,v2,…,vn can only have one of the values value1, value2, …, valuen.
The assignments are:
v1=value3;
v5=value1;

Example:

enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};


enum day weekst, weekend;
weekst=Monday; weekend=Thursday;

Example program:
#include<stdio.h> main()
{
enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum day weekst,weekend;
weekst=Monday;
weekend=Thursday;
printf("weekst=%d\nweekend=%d\n",weekst,weekend);
}

Output:
weekst=0
weekend=3

 The compiler automatically assigns integer digits from 0 to all enumerated


constants.
0 for value1,
1 for value2,
2 for value3,
3 for value4,
4 for value5,
5 for value6,
6 for value7

 Automatic assignments can be overridden by using the following:

enum day {Monday, Tuesday=5, Wednesday, Thursday, Friday,


Saturday, Sunday};

Example program:
#include<stdio.h> main()
{

enum day {Monday, Tuesday=5, Wednesday, Thursday, Friday, Saturday,


Sunday};
enum day weekst,weekend;
weekst=Tuesday;
weekend=Thursday;
printf("weekst=%d\nweekend=%d\n",weekst,weekend);
}

Output:
weekst=5
weekend=7

 The definition and declaration can be combined in one statement as follows:

enum day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} weekst,


weekend;

#include<stdio.h> main()
{

enum day { Monday, Tuesday=5, Wednesday,Thursday, Friday, Saturday}


weekst,weekend;
weekst=Tuesday; weekend=Thursday;
printf("weekst=%d\nweekend=%d\n",weekst,weekend);
}

Type qualifiers:

We can change the properties of primitive or fundamental data type. There are
two type qualifiers:
i. const for constant
ii. volatile

const:

const is a new data type qualifier defined by ANSI standard

. Example: const int classsize=60;


This tells the compiler that the value of the int variable classsize must not be modified by
the program.

Example program:

1. #include<stdio.h>
2. main()
3. {
4. const int classsize=60;
5. printf("classsize=%d\n",classsize);
6. classsize=classsize*3;
7. printf("classsize=%d\n",classsize);
8. }
Note: The compiler gives an error at line number 6: assignment of read-onlyvariable 'a'.

volatile:

ANSI standard defines qualifier volatile that could be used tell explicitly the compiler that
a variable‟s value may be changed at any time by some external sources (from outside the
program).
Example:
volatile int a;
Example program:
#include<stdio.h>
main()
{
volatile int a=5;
printf("a=%d\n",a);
a=a*4;
printf("a=%d\n",a);
}
Output: a=5 a=20

13. Operator
This is a symbol use to perform some operation on variables, operands or with the
constant. Some operator required 2 operand to perform operation or Some required
single operation.

Several operators are there those are, arithmetic operator, assignment, increment ,
decrement, logical, conditional, comma, size of , bitwise and others.

1. Arithmetic Operator

This operator used for numeric calculation. These are of either Unary arithmetic
operator, Binary arithmetic operator. Where Unary arithmetic operator required
only one operand such as +,-, ++, --,!, tiled. And these operators are addition,
subtraction, multiplication, division. Binary arithmetic operator on other hand
required two operand and its operators are +(addition), -(subtraction),
*(multiplication), /(division), %(modulus). But modulus cannot applied with
floating point operand as well as there are no exponent operator in c.
Unary (+) and Unary (-) is different from addition and subtraction.

When both the operand are integer then it is called integer arithmetic and the result is
always integer. When both the operand are floating point then it is called floating
arithmetic and when operand is of integer and floating point then it is called mix type
or mixed mode arithmetic . And the result is in float type.

[Link] Operator

A value can be stored in a variable with the use of assignment operator. The
assignment operator(=) is used in assignment statement and assignment expression.
Operand on the left hand side should be variable and the operand on the right hand
side should be variable or constant or any expression. When variable on the left hand
side is occur on the right hand side then we can avoid by writing the compound
statement. For example,
int x= y;

int Sum=x+y+z;

[Link] and Decrement

The Unary operator ++, --, is used as increment and decrement which acts upon single
operand. Increment operator increases the value of variable by one
.Similarly decrement operator decrease the value of the variable by one. And these
operator can only used with the variable, but cann't use with expression and constant
as ++6 or ++(x+y+z)
It again categories into prefix post fix . In the prefix the value of the variable is
incremented 1st, then the new value is used, where as in postfix the operator is written
after the operand(such as m++,m--).
EXAMPLE
let y=12; z=

++y; y= y+1;

z= y;

Similarly in the postfix increment and decrement operator is used in the operation . And
then increment and decrement is perform.
EXAMPLE
let x= 5; y=

x++; y=x;

x= x+1;
[Link] Operator

It is use to compared value of two expressions depending on their relation. Expression


that contain relational operator is called relational expression.

Here the value is assign according to true or false value.


a.(a>=b) || (b>20)

b.(b>a) && (e>b)


c. (b!=7)

5. Conditional Operator

It sometimes called as ternary operator. Since it required three expressions as


operand and it is represented as (? , :).
SYNTAX

exp1 ? exp2 :exp3


Here exp1 is first evaluated. It is true then value return will be exp2 . If false then
exp3.
EXAMPLE

void main()
{
int a=10, b=2

int s= (a>b) ? a:b; printf(“value

is:%d”);

}
Output:
Value is:10
6. Comma Operator
Comma operator is use to permit different expression to be appear in a situation where
only one expression would be used. All the expression are separator by comma and are
evaluated from left to right.
EXAMPLE

int i, j, k, l;
for(i=1,j=2;i<=5;j<=10;i++;j++)
7. Sizeof Operator
Size of operator is a Unary operator, which gives size of operand in terms of byte
that occupied in the memory. An operand may be variable, constant or data type
qualifier.

Generally it is used make portable program(program that can be run on different


machine) . It determines the length of entities, arrays and structures when their size are
not known to the programmer. It is also use to allocate size of memory dynamically
during execution of the program.
EXAMPLE
main( )
{
int sum; float f;

printf( "%d%d" ,size of(f), size of (sum) );


printf("%d%d", size of(235 L), size of(A));
}
8. Bitwise Operator
Bitwise operator permit programmer to access and manipulate of data at bit level.
Various bitwise operator enlisted are
one's complement (~)
bitwise AND (&)
bitwise OR (|)
bitwise XOR (^)
left shift (<<)
right shift (>>)
These operator can operate on integer and character value but not on float and double.
In bitwise operator the function showbits( ) function is used to display the binary
representation of any integer or character value.

In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its
value would obtaining by 0 to 2 bits.
As the bitwise OR operator is used to set on a particular bit in a number. Bitwise
AND the logical AND.

It operate on 2operands and operands are compared on bit by bit basic. And hence both
the operands are of same type.

Logical or Boolean Operator

Operator used with one or more operand and return either value zero (for false) or one
(for true). The operand may be constant, variables or expressions. And the expression
that combines two r more expressions is termed as logical expression.
C has three logical operators :
Operator Meaning

&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary operator. Logical
AND gives result true if both the conditions are true, otherwise result is false. And
logial OR gives result false if both the condition false, otherwise result is true.

14. Operator precedence and associativity


Operator precedence and associativity are rules that decide the order in which parts of an
expression are calculated. Precedence tells us which operators should be evaluated first,
while associativity determines the direction (left to right or right to left) in which
operators with the same precedence are evaluated.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right


Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Within an expression, higher precedence operators will be evaluated first.

[Link]/Output Functions
C programming relies on a set of standard input/output (I/O) functions, primarily found in
the <stdio.h> header file, to interact with the user and external files. These functions facilitate
receiving data from input devices (like the keyboard) and displaying information to output
devices (like the monitor).

1. Console I/O Functions:


 printf(): This is a formatted output function used to display data on the console. It takes a
format string and a variable number of arguments, allowing for precise control over the
output's appearance using format specifiers (e.g., %d for integers, %f for floats, %s for
strings).

#include <stdio.h>
int main() {
int age = 30;
printf("Your age is: %d\n", age);
return 0;
}
 scanf(): This is a formatted input function used to read data from the console. It also uses a
format string to specify the expected data type and requires the address of the variable where
the input should be stored (using the & operator).

#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
 getchar(): Reads a single character from the standard input.
 putchar(): Writes a single character to the standard output.
 gets(): Reads a line of text (including spaces) from the standard input into a character
array. Note: gets() is considered unsafe due to potential buffer overflows and is generally
discouraged in favor of fgets().
 puts(): Writes a string to the standard output, followed by a newline character.

2. File I/O Functions:


These functions are used for reading from and writing to files.
 fopen(): Opens a file and returns a file pointer.
 fclose(): Closes an opened file.
 fprintf(): Writes formatted data to a file.
 fscanf(): Reads formatted data from a file.
 fgets(): Reads a line of text from a file.
 fputs(): Writes a string to a file.
 getc() / fgetc(): Reads a single character from a file.
 putc() / fputc(): Writes a single character to a file.

16. Built in functions in c


In C programming, the term "built-in functions" typically refers to the standard library
functions that are provided as part of the C language standard. These functions are not
inherently part of the core language syntax or keywords, but rather are pre-defined and pre-
compiled functions available for use by including specific header files.
Here is a list of some common Standard Library functions, categorized by their header file.
Input and output functions (<stdio.h>)
This library provides functions for handling input from the user and printing output to the
console.
 printf(): Prints formatted output to the console.
 scanf(): Reads formatted input from the console.
 getchar(): Reads a single character from the standard input.
 putchar(): Writes a single character to the standard output.
 fgets(): Reads a string from a specified stream, such as a file or the console.
 fopen(): Opens a file.
 fclose(): Closes an open file.
Mathematical functions (<math.h>)
For mathematical operations, you must include the <math.h> header.
 sqrt(): Calculates the square root of a number.
 pow(): Returns the result of a number raised to a power.
 abs(): Returns the absolute value of a number (for integers, <stdlib.h> also has abs()).
 ceil(): Rounds a number up to the nearest integer.
 floor(): Rounds a number down to the nearest integer.
 sin(), cos(), tan(): Trigonometric functions.
 log(): Calculates the natural logarithm of a number.
String manipulation functions (<string.h>)
This header file contains functions for manipulating null-terminated strings.
 strcpy(): Copies one string to another.
 strcat(): Joins two strings together.
 strlen(): Calculates the length of a string.
 strcmp(): Compares two strings.
 strchr(): Finds the first occurrence of a character in a string.
 strstr(): Finds the first occurrence of a substring within another string.
Standard utility functions (<stdlib.h>)
The standard library provides many general-purpose functions in <stdlib.h>.
 malloc(): Dynamically allocates a block of memory.
 free(): Deallocates a block of memory previously allocated by malloc().
 exit(): Terminates the program normally.
 atoi(): Converts a string to an integer.
Character handling functions (<ctype.h>)
This library provides functions for testing and converting individual characters.
 isalpha(): Checks if a character is an alphabet letter.
 isdigit(): Checks if a character is a decimal digit.
 isupper(): Checks if a character is an uppercase letter.
 islower(): Checks if a character is a lowercase letter.
 toupper(): Converts a character to uppercase.
 tolower(): Converts a character to lowercase.
Time and date functions (<time.h>)
For working with time and dates, include the <time.h> header.
 time(): Gets the current time.
 difftime(): Calculates the difference between two times.
 localtime(): Converts a time value into a structure for local time.

Practical: Create Problem Analysis Charts, Flowcharts and


Pseudocode for simple C programs (Minimum three).
Here are pseudocode examples for three simple C programs:
1. Program to Calculate the Sum of Two Numbers

START
DECLARE integer num1, num2, sum
DISPLAY "Enter first number: "
READ num1
DISPLAY "Enter second number: "
READ num2
CALCULATE sum = num1 + num2
DISPLAY "The sum is: ", sum
END
2. Program to Find the Larger of Two Numbers
START
DECLARE integer num1, num2
DISPLAY "Enter first number: "
READ num1
DISPLAY "Enter second number: "
READ num2
IF num1 > num2 THEN
DISPLAY num1, " is larger."
ELSE IF num2 > num1 THEN
DISPLAY num2, " is larger."
ELSE
DISPLAY "Both numbers are equal."
END IF
END

3. Program to Check if a Number is Even or Odd


START
DECLARE integer number
DISPLAY "Enter an integer: "
READ number
IF number MOD 2 EQUALS 0 THEN
DISPLAY number, " is an even number."
ELSE
DISPLAY number, " is an odd number."
END IF
END

*************************************************************************
UNIT-II CONTROL STRUCTURES AND FUNCTIONS

Contents
Control Structures- Conditional Statements, Looping Statements
Functions-Library Functions, User defined Functions, Function Prototype, Function Definitions,
Types of Functions, Functions with and without arguments, Functions with no return and with
Return Values - Nested Functions - Recursion.

CONTROL STRUCTURES
CONTROL STRUCTURE

Control Statements

Conditional Unconditional

[Link]

Decision Making Statement Loop Control Statement 2. continue

1. if Statement 1. for 3. break

2. if.. else statement 2. while

3. nested if statement 3. do-while

4. if..else ladder

5. switch statement

CONDITIONAL STATEMENT

Decision Making Statement


If Statement:
 The if statement is a decision making statement.
 It is used to control the flow of execution of the statement and also used to the
logically whether the condition is true or false
 It is always used in conjunction with condition.
False
Condition

True

Statements

Syntax:
If(condition)
{

True statements;
}
 If the condition is true, then the true statements are executed.
 If the condition is false then the true statements are not executed, instead the
program skips past them.
 The condition is given by relational operators like ==,<=,>=,!=,etc.

Example 1: //program to check whether the entered number is less than 25

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf(“Enter one value”);
scanf(“%d”,&i);
if(i<=25)
printf(“The entered no %d is < 25”,i);
getch();
}
Output:

Enter one value 5


The entered no 5 is < 25

Example 2: //program to calculate the sum and multiplication using if Statement

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,n;
clrscr();
printf(“Enter two values”);
n=scanf(“%d%d”,&a,&b);
if(n==2)
{
printf(“the sum of two numbers : %d”,a+b);
printf(“the product of two numbers:%d”,a*b);
}
getch();
}

Output:

Enter two value 5 10


the sum of two numbers : 15
the product of two numbers : 50

if.. else statement:

 It is basically two way decision making statement and always used in conjunction
with condition.
 It is used to control the flow of expression and also used to carry the logical test and
then pickup one of the two possible actions depending on the logical test.
 If the condition is true, then the true statements are executed otherwise false
statements are executed.
 The true and false statements may be single or group of statements.

Condition

True Statements False Statements


Syntax:
If (condition)

True statements;
else
False statements;

Example 1: //program to find the greatest of two number.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter two value”);
scanf(“%d%d”,&a,&b);
if(a>b)

printf(“The given no %d is greatest”,a);


else
printf(“The given no %d is greatest”,b);
}

Output:

Enter two value 5 10


The given no 10 is greatest

Nested if..else Statement:

When a series of if_else statements are needed in a program, we can write an entire
if_else statement inside another if and it can be further nested. This is called nesting if.

Syntax:
if(condition 1)
{
if(condition 2)
{
True statement 2;
else
False statement 2;
}
else
False statement 1;
}
Example 1: //program to find the greatest of three numbers.

#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 100;
int b = 200;

/* check the boolean condition */


if( a == 100 )
{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );

return 0;
}

Output:

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200
If_else Ladder:

 Nested if statements will become complex, if several conditions have to be checked.


 In such situations we can use the else if ladder .

Syntax:
if(condition 1)
{
if(condition 2)
{
True statement 2;
}
elseif(condition 3)
{
True statement 3;
else
False statement 3;
}
else
False statement 1;
}

Switch Statement
 The switch statement is used to execute a particular group of statements from
several available groups of statements.
 It allows us to make a decision from the number of choices.
 It is a multi-way decision statement.

Rules for writing switch () statement.


 The expression in switch statement must be an integer value or a character
constant.
 No real numbers are used in an expression.
 Each case block and default block must be terminated with break statement.
 The default is optional and can be placed anywhere, but usually placed at end.
 The ‘case’ keyword must terminate with colon(:).
 Cases should not be identical.
 The values of switch expression is compared with the case constant expression in
the order specified i.e., from top to bottom.
switch
( Expression)

case 1: statements
break;

case 2: statements
break;

default: statements
break;

Syntax:

switch(expression)
{
case 1:
state
ment;
break;
case 2:
state
ment;
break;
default: statement;
break;
}

// program to print the give number is odd / even using switch case statement.

#include<stdio.h>
#include<conio.h> void main()
{
int a,b,c;
printf(“Enter one value”); scanf(“%d”,&a);
switch(a%2)
{
case 0:
printf(“The given no %d is even”, a);
break;
default :
printf(“The given no %d is odd”, a);
break;
}
}

Output:

Enter one value 5


The given no 5 is odd

Unconditional statement
Break statement
 The break statement is used to terminate the loop.
 When the keyword break is used inside any loop, control automatically transferred to
the first statement after the loop.

Syntax:
break;

//program to print the number upto 5 using break statement

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break;
printf(“%d”,i);
}
}
Output:
1 2 3 4 5

While(condition) Do for(initialize;condition; incr/dec)


{ …….. { …….. { ……..
if(condition) if(condition) if(condition)
beak; break; break;
………. ………. ……….
} }while(condition); }

Continue Statement

 In some situation, we want to take the control to the beginning of the loop, bypassing
the statement inside the loop which have not been executed, for this purpose the
continue is used.
 When the statement continue is encountered inside any loop, control automatically
passes to the beginning of the loop.

Syntax:
continue;

While(condition)
{
……..
if(condition)
continue;
……….
}

While(condition) Do for(initialize;condition; incr/dec)


{ …….. { …….. { ……..
if(condition) if(condition) if(condition)
continue; continue; continue;
………. ………. ……….
} } while (condition); }
Difference between break and continue

Break Continue

Break statement takes the control to the Continue statement takes the control to be
outside of the loop beginning of the loop
It is also in switch statement This can be used only in loop statements

Always associated with if condition in loop This is also associated with if condition

Goto Statement:

 C provides the goto statement to transfer control unconditionally from one place to
another place in the program.
 A goto statement can change the program control to almost anywhere in the program
unconditionally.
 The goto statement require a label to identify the place to move the execution.
 The label is a valid variable name and must be ended with colon(:).

Syntax:

1. goto label; 2. label:


…… …..……
……. ………..
label: goto label;

/* program to print the given both number is equal or not*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%d%d”,&a,&b);
if(a==b)
goto equal;
else
{
printf(“%d and %d are not equal”,a,b);
exit(0);
}
equal: printf(“%d and %d are equal”,a,b);
}

Output:

Enter the numbers 4 5


4 and 5 are not equal

Enter the numbers 5 5


5 and 5 are equal

LOOPING STATEMENTS

A loop statement allows us to execute certain block of code repeatedly until test condition is
false.

There are 3 types of loops in C programming:

1. for loop
2. while loop
3. do...while loop

for loop:

The syntax for a for loop is

for ( variable initialization; condition; variable update )


{
Code to execute while the condition is true
}

The initialization statement is executed only once at the beginning of the for loop. Then the test
expression is checked by the program. If the test expression is false, for loop is terminated. But
if test expression is true then the code/s inside body of for loop is executed and then update
expression is updated. This process repeats until test expression is false.
for loop example

Write a program to find the sum of first n natural numbers where n is entered by user.
Note: 1,2,3... are called natural numbers.

#include <stdio.h>
void main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to
sum=sum+count */
}
printf("Sum=%d",sum);

Output

Enter the value of


n. 19
Sum=190
In this program, the user is asked to enter the value of n. Suppose you entered 19 then, count is
initialized to 1 at first. Then, the test expression in the for loop,i.e., (count<= n) becomes true.
So, the code in the body of for loop is executed which makes sum to 1. Then, the expression
++count is executed and again the test expression is checked, which becomes true. Again, the
body of for loop is executed which makes sum to 3 and this process continues. When count is
20, the test condition becomes false and the for loop is terminated.

/* C program to check whether a number is prime or not. */

#include <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}

Output

Enter a positive integer: 29


29 is a prime number.

This program takes a positive integer from user and stores it in variable n. Then, for loop is
executed which checks whether the number entered by user is perfectly divisible by i or not
starting with initial value of i equals to 2 and increasing the value of i in each iteration. If the
number entered by user is perfectly divisible by i then, flag is set to 1 and that number will not
be a prime number but, if the number is not perfectly divisible by i until test condition i<=n/2 is
true means, it is only divisible by 1 and that number itself and that number is a prime number.
Different Types of For Loop in C Programming

For loop can be implemented in different ways

1. Single Statement inside For Loop


2. Multiple Statements inside For Loop
3. No Statement inside For Loop
4. Semicolon at the end of For Loop
5. Multiple Initialization Statement inside For
6. Missing Initialization in For Loop
7. Missing Increment/Decrement Statement
8. Infinite For Loop
9. Condition with no Conditional Operator.

Single Statement inside For Loop:

for(i=0;i<5;i++)
printf("sathyabama");

1. Above code will print sathyabama word 5 times.


2. We have single statement inside for loop body.
3. No need to wrap printf inside opening and closing curly block.
4. Curly Block is Optional.

Multiple Statements inside For Loop

for(i=0;i<5;i++)
{
printf("Statement 1"); printf("Statement 2");
printf("Statement 3"); if(condition)
{
--------
--------
}
}
If we have block of code that is to be executed multiple times then we can use curly braces to
wrap multiple statement in for loop
No Statement inside For Loop

for(i=0;i<5;i++)
{

}
It is bodyless for loop. It is used to increment value of “i”.This are not used generally. At
the end ,for loop value of i will be 5.

Semicolon at the end of For Loop:

for(i=0;i<5;i++);

 We will not get compile error if semicolon is at the end of for loop.
 This is perfectly legal statement in C Programming.
 This statement is similar to bodyless for loop.

Multiple Initialization Statement inside For:

for(i=0,j=0;i<5;i++)
{
statement1;
statement2;
statement3;
}

Multiple initialization statements must be seperated by Comma .

Missing Increment/Decrement Statement:


for(i=0;i<5;)
{
statement1;
statement2;
statement3;
i++;
}

we have to explicitly alter the value i in the loop body.

Missing Initialization in For Loop:


i = 0;
for(;i<5;i++)
{
statement1;
statement2;
statement3;
}

we have to set value of ‘i’ before entering in the loop otherwise it will take garbage value of „i‟.
Infinite For Loop:
i = 0;
for( ; ; )
{
statement1;
statement2;
statement3;
if(breaking condition)
break;
i++;
}

Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.
While Loop

while loop repeatedly executes a target statement as long as a given


condition is true.

Initialization;
while(condition)
{
----------
---------
----------
------
Increment/decrement;
}

 For Single Line of Code – Opening and Closing braces are not needed. while(1) is used
for Infinite Loop
 Initialization, Increment/Decrement and Condition steps are on different Line.
 While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then
and then only code is executed ]
Examples:
#include <stdio.h>

int main()
{
int y = 0;/* Don't forget to declare variables*/
while ( y < 10 ) {/* While y is less than 10 */
printf( "%d\n", y );
y++; /* Update y so the condition can be met
eventually */
}
getchar();
}

C Program to Find Number of Digits in a Number


#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
n/=10; /* n=n/10 */
++count;
}
printf("Number of digits: %d",count);
}
Output:
Enter an integer: 34523 Number of digits: 5
Types of infinite while loop

Semicolon at the end of while loop

#include<stdio.h>
void main()
{
int num=300;
while(num>255); //Note it Carefully
printf("Hello");
}
Output :
Will not print anything
1. In the above program , Condition is specified in the While Loop
2. Semicolon at the end of while indicated while without body.
3. In the program variable num doesn‟t get incremented , condition remains true forever.
4. As Above program does not have Loop body , It won‟t print anything

Non-Zero Number as a Parameter

#include<stdio.h>
void main()
{
while(1)
printf("Hello");
}
Output :

Infinite Time "Hello" word

1. We can specify any non-zero positive number inside while loop


2. Non zero number is specified in the while loop which means that while loop will remains
true forever.

Subscript variable remains the same

#include<stdio.h>
void main()
{
int num=20;
while(num>10) {
printf("Hello");
}
}

Output :

Infinite Time "Hello C" word


Explanation :

1. Condition is specified in while Loop, but terminating condition is not specified and even
we haven‟t modified the condition variable.
2. In this case our subscript variable (Variable used to Repeat action) is not either
incremented or decremented
3. so while remains true forever.
Character as a Parameter in While Loop

#include<stdio.h>
void main()
{
while('A')
printf("Hello");
}

Output :
Infinite Time "Hello" word

Explanation :

1. Character is Represented in integer in the form of ASCII internally.


2. Any Character is Converted into Non-zero Integer ASCII value
3. Any Non-zero ASCII value is TRUE condition , that is why Loop executes forever

DO..WHILE

DO..WHILE loops executes the body of the loop atleast once.

The structure is

initialization;
do
{
--------------
--------------
incrementation;
}while(condition);

The condition is tested at the end of the block instead of the beginning, so the block will be
executed at least once. If the condition is true, it go back to the beginning of the block and
execute it again. A do..while loop is almost same as a while loop except that the loop body is
guaranteed to execute at least once.

 It is Exit Controlled Loop.


 Initialization , Incrementation and Condition steps are on different Line.
 It is also called Bottom Tested.
 Semicolon must be added after the while
Example:

#include <stdio.h>

int main()
{
int z;

z = 0; do {
/* " sathyabama is printed at least one time even though the
condition is false */
printf( "sathyabama\n" ); } while ( z != 0 );
getchar();

C Program to print first 5 Natural Numbers

Using For Loop

#include<stdio.h>

void main() { int i = 1;

for (i = 1; i <= 5; i++) { printf("%d", i);


}
}
1
2
3
4
5

Using While Loop

#include<stdio.h>

void main() { int i = 1;


while (i <= 5) {
printf("%d", i); i++;
}
}

Using Do-While Loop

#include<stdio.h>

void main() {
int i = 1;

do {
printf("%d", i);
i++;
} while (i <= 5);

}
FUNCTIONS

LIBRARY FUNCTIONS

Definition

C Library functions are inbuilt functions in C language which are clustered in a group and
stored in a common place called Library. Each and every library functions in C executes explicit
functions. In order to get the pre- defined output instead of writing our own code, these library
functions will be used. Header file consists of these library functions like Function prototype and
data definitions.

 Every input and output operations (e.g., writing to the terminal) and all mathematical
operations (e.g., evaluation of sines and cosines) are put into operation by library
functions.
 The C library functions are declared in header files (.h) and it is represented as
[file_name].h
 The Syntax of using C library functions in the header file is declared as
“#include<file_name.h>”. Using this syntax we can make use of those library functions.
 #include<filename.h>” command defines that in C program all the codes are included in
the header files followed by execution using compiler.
 It is required to call the suitable header file at the beginning of the program in terminal in
order to use a library function. A header file is called by means of the pre-processor
statement given below,

#include<filename.h>

Whereas the filename represents the header file name and #include is a pre- processor directive.
To access a library function the function name must be denoted, followed by a list of
arguments, which denotes the information being passed to the function.

Example

In case if you want to make use of printf() function, the header file <stdio.h> should be included at
the beginning of the C program.

#include <stdio.h>
int main()
{
/* NOTE: Error occurs if printf() statement is written without using
the header file */

printf(" Hello World");


}
The „main() function‟ is also a library function which is called at the initial of the program.

Example
To find the square root of a number we use our own part of code to find them but this may
not be most efficient process which is time consuming too. Hence in C programming by declaring
the square root function sqrt() under the library function “math.h” will be used to find them rapidly
and less time consuming too. Square root program using the library functions is given below:
Finding Square root Using Library Function
#include <stdio.h>
#include <math.h>
int main(){
float num,root;
printf("Enter a number to find square root.");
scanf("%f",&num);
root=sqrt(num); /* Computes the square root of num and stores in
root. */
printf("Square root of %.2f=%.2f",num,root);
return 0;
}

List of Standard Library Functions in C Programming

C Header Files

ctype.h stdio.h conio.h string .h m ath.h stdlib.h tim e.h

Adding User Defined functions in C library:

 In C Programming we can declare our own functions in C library which is called as user-
defined functions.
 It is possible to include, remove, change and access our own user defined function to or
from C library functions.
 Once the defined function is added to the library it is merely available for all C programs
which are more beneficial of including user defined function in C library function
 Once it is declared it can be used anywhere in the C program just like using other C library
functions.
 By using these library functions in GCC compilers (latest version), compilation time can be
consumed since these functions are accessible in C library in the compiled form.
 Commonly the header files in C program are saved as ”file_name.h” in which all library
functions are obtainable. These header files include source code and this source code is
further added in main C program file where we include this header file via “#include
<file_name.h>” command.

Steps for adding user defined functions in C library:

Step 1:

For instance, hereby given below is a test function that is going to be included in the C
library function. Write and save the below function in a file as “addition.c”

addition(int a, int b)
{
int sum;
total =a + b;
return sum;
}

Step 2:

Compile “addition.c” file by using Alt + F9 keys (in turbo C).


step 3:

A compiled form of “addition.c” file would be created as “[Link]”.


Step 4:

To add this function to library, use the command given below (in turbo C).
c:\> tlib [Link] + c:\ [Link]
+ represents including c:\[Link] file in the math library.
We can delete this file using – (minus).

Step 5:
Create a file “addition.h” and declare sample of addition() function like below.
int addition (int a, int b);
Now “addition.h” file has the prototype of function “addition”.

Note : Since directory name changes for each and every IDE, Kindly create, compile and
add files in the particular directory.
Step 6:

Here is an example to see how to use our newly added library function in a C program.

# include <stdio.h>
// User defined function is included here.
# include “c:\\addition.h”
int main ( )
{
int total;
// calling function from library
total = addition (10, 20);
printf ("Total = %d \n", total);
}

Output:
Total = 30

 Source code checking for all header files can be checked inside “include” directory
following C compiler that is installed in system.
 For instance, if you install DevC++ compiler in C directory in our system, “C:\Dev-
Cpp\include” is the path where all header files will be readily available.

Mostly used header files in C:


C library functions and header files in which they are declared in conio.h is listed below:
[Link] Header file Description
1 stdio.h A standard input/output header file where Input/ Output functions are
declared
2 conio.h Console input/output header file
3 string.h String functions are defined in this header file
4 stdlib.h The general functions used in the C program is defined in this header file.
5 math.h Mathematical related functions are defined in this header file.
6 time.h Time and clock allied functions are defined in this header file.
7 ctype.h Every character managing functions are declared in this header file
8 errno.h This header file contains Error handling functions.
9 assert.h Diagnostics functions are declared in this header file.

C – conio.h library functions

The entire C programming inbuilt functions that are declared in conio.h header file are given
below. The source code for conio.h header file is also given below for your reference.
List of inbuilt conio.h file C functions:

[Link] Function Description


1 clrscr() This function is used to clear the output screen.
2 getch() It reads character from keyboard
3 getche() It reads character from keyboard and echoes to o/p screen
4 textcolor() This function is used to change the text colour
5 textbackground() This function is used to change text background

C – stdio.h library functions


Inbuilt functions of C declared in stdio.h header file are given below.
[Link] Function Description
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, numeric data from keyboard.
3 getc() It reads character from file
4 gets() It reads line from keyboard
5 getchar() It reads character from keyboard
6 puts() It writes line to o/p screen
7 putchar() It writes a character to screen
8 clearerr( ) Clears the error indicators
9 f open() All file handling functions are defined in this header file.
10 f close() closes an opened file
11 getw() reads an integer from file
12 putw() writes an integer to file
13 f getc() reads a character from file
14 putc() writes a character to file
15 f putc() writes a character to file
16 f gets() reads string from a file, per line at a time
17 f puts() writes string to a file
18 f eof() finds end of file
19 f getchar reads a character from keyboard
20 f getc() reads a character from file
21 f printf() writes formatted data to a file
22 f scanf() reads formatted data from a file
23 f getchar reads a character from keyboard
24 f putchar writes a character from keyboard
25 f seek() moves file pointer position to given location
26 SEEK_SET moves file pointer position to the beginning of the file
27 SEEK_CUR moves file pointer position to given location
28 SEEK_END moves file pointer position to the end of file.
29 f tell() gives current position of file pointer
30 rewind() moves file pointer position to the beginning of the file
31 putc() writes a character to file
32 sprint() writes formatted output to string
33 sscanf() Reads formatted input from a string
34 remove() deletes a file
35 fflush() flushes a file
Functions

 A function is a group of statement that is used to perform a specified task which


repeatedly occurs in the main program. By using function, we can divide the complex
problem into a manageable problem.
 A function can help to avoid redundancy.
 Function can be of two types, there are
1. Built-in Function (or) Predefined Function (or) Library
Function
2. User defined Function

Functions

Predefined Function User-defined Function

Difference between Predefined and User-defined Functions

Predefined Function User-defined function

Predefined function is a function which is User- Defined function is a function which is


already defined in the header file (Example: created by the user as per requirement of its
math.h, string.h, etc) owner

Predefined Function is a part of a header file, User- Defined function are part of the program
which are called at runtime which are compiled at runtime

The Predefined function name is given by the User- Defined function name created by the
developer user

Predefined Function name cannot be changed User defined Function name can be changed
User Defined Functions

 The function defined by the users according to their context (or) requirements is
known as a user defined function.
 The User defined function is written by the programmer to perform specific task (or)
operation, which is repeatedly used in the main program.
 These functions are helpful to break down the large program into a number of the
smaller function.
 The user can modify the function in order to meet their requirements.
 Every user define function has three parts namely
Function Declaration
Function Calling
Function Definition

Need for user-defined function

 While it is possible to write any complex program under the function, and it leads to a
number of problems, such as
 The problem becomes too large and complex.
 The user can‟t go through at a glance
 The task of debugging, testing and maintenance become difficult.
 If a problem is divided into a number of parts, then each part may be independently
coded and later it combined into a single program. These subprograms are called
functions, it is much easier to understand, debug and test the program.

Merits of User-Defined Function


 The length of the source program can be reduced by dividing it into smaller functions
 It provides modularity to the program
 It is easy to identify and debug an error
 Once created a user defined function, can be reused in other programs
 Function facilitates top-down programming approach
 The Function enables a programmer to build a customized library of repeatedly used
routines
 Function helps to avoid coding of repeated programming of the similar instruction

Elements of User-Defined Function


1. Function Declaration
2. Function Call
3. Function Definition

Function Declaration
 Like normal variable in a program, the function can also be declared before they
defined and invoked
 Function declaration must end with semicolon (;)
 A function declaration must declare after the header file
 The list of parameters must be separated by comma.
 The name of the parameter is optional, but the data type is a must.
  If the function does not return any value, then the return type void is must.
 If there are no parameters, simply place void in braces.
 The data type of actual and formal parameter must match.

Syntax:
Return_type function_name (datatype parameter1, datatype parameter2,…);
Description:

Return type : type of function


Function_name : name of the function
Parameter list or argument list : list of parameters that the function
can convey.

Example:
int add(int x,int y,int z);

Function Call
The function call be called by simply specifying the name of the function, return
value and parameters if presence.

Syntax: function_name();
function_name(parameter);
return_value =function_name (parameter);

Description:
function_name : Name of the function
Parameter : Actual value passed to the calling function

Example
fun();
fun(a,b);
fun(10,20);
c=fun(a,b);
e=fun(2.3,40);

Function Definition

 It is the process of specifying and establishing the user defined function by specifying
all of its element and characteristics.
Syntax:
Return_type function_name (datatype parameter1, datatype parameter2)
Example 1
#include<stdio.h>
#include<conio.h>
void add(); //Function Declaration void sub();//Function Declaration
void main()
{
clrscr();
add(); //Function call
sub(); //Function call
getch();
}
void add() //Function Definition
{
int a,b,c;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b); c=a+b;
printf(‚add=%d‛,c);
}
void sub() //Function Definition
{
int a,b,c;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
c=a-b;
printf(“sub=%d”,c);
}
Example 2 :
//Program to check whether the given number is odd or even
#include<stdio.h>
#include<conio.h>
void oddoreven()
{
printf("Enter One value");
scanf("%d",&oe);
if(oe%2==0)
printf("The Given Number%d is even");
else
printf("The Given Number %d is odd");
}
void main()
{
clrscr();
oddoreven();
getch();
}

Function Parameter

 The Parameter provides the data communication between the calling function and called
function.
 There are two types of parameters.

o Actual parameter: passing the parameters from the calling function to the
called function i.e the parameter, return in function is called actual parameter
o Formal parameter: the parameter which is defined in the called function i.e. The
parameter, return in the function definition is called formal parameter

Example:
main()
{
………..
Where
………..
Fun(a,b);
a,b are the actual
……….. parameters
………..
} x,y are formal parameter
Fun(int x,int y)
{
…………
…………
}
Example Program

#include<stdio.h>
#include<conio.h>
void add(int,int); //Function Declaration Output:
void sub(float,int);//Function Declaration
void main() add=7
{ sub=-2.500000
clrscr();
add(3,4); //Function call
sub(2.5,5); //Function call
getch();
}
void add(int a,int b)//Function Definition
{
int c;
c=a+b;
printf(“add=%d”,c);
}
void sub(float a, int b) //Function Definition
{
float c;
c=a-b;
printf(“sub=%f”,c);
}
Example 2:
//program for factorial of given
number #include<stdio.h>
#include<conio.h> void main()
{
int fact(int); Output:
int f; Enter one value 5
clrscr(); The Factorial of given
printf("Enter one value"); number 5 is 120
scanf("%d",&f);
printf("The Factorial of given number %d is %d",f,fact(f));
getch();
}
int fact(int f)
{
if(f==1) return 1;
else
return(f*fact(f-1));
}
Function Prototype (or) Function Interface

 The functions are classified into four types depends on whether the arguments
are present or not, whether a value is returned or not. These are called
function prototype.
 In ‘C’ while defining user defined function, it is must to declare its prototype.
 A prototype states the compiler to check the return type and arguments type of
the function.
 A function prototype declaration consists of the function’s return type, name
and argument. It always ends with semicolon. The following are the function
prototypes
o Function with no argument and no return value.
o Function with argument and no return value.
o Function with argument and with return value.
o Function with no argument with return value.

Function with no argument and no return value

 In this prototype, no data transfer takes place between the calling function and
the called function. i.e., the called program does not receive any data from the
calling program and does not send back any value to the calling program.

Syntax:-
main() void Fun()
{ {
The dotted lines indicates that,
………..
there is only transfer of control,
………..
……….. but no data transfer.
………..
Fun();
……….. }
………..
}
Example program 1
#include<stdio.h> Output:
#include<conio.h> Enter two values 6 4
mul=24
void mul();
void main()
{
clrscr();
mul();
getch();
}
void mul()
{
int a,b,c;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
c=a*b;
printf(“mul=%d”,c);
}
Example program 2
//Program for finding the area of a circle using Function with no argument
and no return value
I#include<stdio.h>
#include<conio.h>
void circle();
Output:
void main()
Enter radius 5
{ The area of circle 78.500000
circle();
}
void circle()
{
int r;
float cir;
printf("Enter radius");
scanf("%d",&r);
cir=3.14*r*r;
printf("The area of circle is %f",cir);
}
Function with argument and no return value
 In this prototype, data is transferred from the calling function to called
function. i.e., the called function receives some data from the calling function
and does not send back any values to calling function
 It is one way data communication.
Syntax:-
main() void Fun(x,y) The solid lines indicate data
{ { transfer and dotted line indicates
……….. ……….. a transfer of control.
……….. ………..
Fun(a,b);
a and b are the actual
……….. }
……….. parameters
}
Example program 1: x and y are formal parameters
#include<stdio.h>
#include<conio.h>
void add(int,int);
void main() Output:
{ Enter two values 6 4
clrscr(); add=10

int a,b;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
add(a,b);
getch();
}
void add(int x,int y)
{
int c;
c=x+y;
printf(“add=%d”,c);
}
Example program 2:
//Program to find the area of a circle using Function with argument and no return value
#include<stdio.h>
#include<conio.h>
void circle(int);
Output:
void main()
Enter radius 5
{ The area of circle 78.500000
int r;
clrscr();
printf("Enter radius");
scanf("%d",&r);
circle(r);
}
void circle(int r)
{
float cir;
cir=3.14*r*r;
printf("The area of circle is %f",cir);
getch();
}

Function with argument and with return value.


 In this prototype, the data is transferred between the calling function and
called function. i.e., the called function receives some data from the calling
function and sends back returned value to the calling function.
 It is two way data communication
Syntax:- The solid lines indicates data transfer
main() int Fun(x,y) takes place in between thecalling
{ { program and called program
……….. ………..
……….. ……….. a,b are the actual parameter
c=Fun(a,b); return(z);
……….. } x,y are formal parameter
}
Example program 1:
#include<stdio.h>
#include<conio.h> Output:
void add(int,int); Enter two values 6 4
Add=10
void main()
{
clrscr();
int a,b,c;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“Add=%d”,c);
getch();
}
void add(int x,int y)
{
int m;
m=x+y;
return m;
}
Example Program 2
// Program to find the area of a circle using Function with argument
and with return value
#include<stdio.h>
#include<conio.h>
float circle(int);
void main()
{
int r;
clrscr(); Output:
printf("Enter radius"); Enter radius 5
the area of circle 78.500000
scanf("%d",&r);
printf("the area of circle is %f",circle(r));
getch();
}
float circle(int r)
{
float cir;
cir=3.14*r*r;
return cir;
}
Function with no argument with return value
 In this prototype, the calling function cannot pass any arguments to the called
function, but the called program may send some return value to the calling function.
 It is one way data communication
Syntax:-
main() int Fun() The dotted line indicates a
{ { control transfer to the called
………..
……….. program and the solid line
……….. indicates data return to the
………..
Fun(); calling program
return(z);
……….. }
………..
}
Example program 1
#include<stdio.h>
#include<conio.h>
int add();
void main()
Output:
{
Enter two values 6 4
clrscr(); Add=10
int z;
z=add();
printf(“Add=%d”,z);
getch();
}
int add()
{
int a,b,c;
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
c=a+b;
return c;
}
Example Program 2
// Program to the area of a circle using no argument with a return
value
#include<stdio.h>
#include<conio.h>
float circle();
Output:
void main()
Enter radius 5
{ the area of circle 78.500000
clrscr();
printf("the area of circle is %f",circle());
getch();
}
float circle()
{
float cir;
int r;
printf("Enter radious");
scanf("%d",&r);
cir=3.14*r*r;
return cir;
}
Parameter Passing Methods (or) Passing Arguments to Function

 Function is a good programming style in which we can write reusable code that
can be called whenever required.
 Whenever we call a function, the sequence of executable statements gets
executed. We can pass some of the information (or) data to the function for
processing is called a parameter.
 In ‘C’ Language there are two ways a parameter can be passed to a function.
They are

o Call by value
o Call by reference

Call by Value:
 This method copies the value of the actual parameter to the formal parameter of the
function.
 Here, the changes of the formal parameters cannot affect the actual parameters,
because formal parameter are photocopies of the actual parameter.
 The changes made in formal arguments are local to the block of the called function.
Once control returns back to the calling function the changes made disappears.

Example Program
#include<stdio.h>
#include<conio.h>
void cube(int);
int cube1(int);
void main() Output:

{ Enter one values 3


Value of cube function is 3
int a; Value of cube1 function is 27
clrscr();
printf(“Enter one values”);
scanf(“%d”,&a);
printf(“Value of cube function is=%d”, cube(a));
printf(“Value of cube1 function is =%d”, cube1(a ));
getch();
}
void cube(int x)
{
x=x*x*x;
return x;
}
int cube1(int x)
{
x=x*x*x;
return x;
}

Call by reference
 Call by reference is another way of passing parameter to the function.
 Here the address of the argument is copied into the parameter inside the function, the
address is used to access arguments used in the call.
 Hence, changes made in the arguments are permanent.
 Here pointer is passed to function, just like any other arguments.
Example Program
#include<stdio.h>
#include<conio.h>
void swap(int,int);
Output:
void main() Before swapping a=5 b=10
After swapping a=10 b=5
{
int a=5,b=10;
clrscr();
printf(“Before swapping a=%d b=%d”,a,b);
swap(&a,&b);
printf(“After swapping a=%d b=%d”,a,b);
getch();
}
void swap(int *x,int *y)
{
int *t;
t=*x;
*x=*y;
*y=t;
}

Nesting of function call in c programming

If we are calling any function inside another function call, then it is known as Nesting
function call. In other words, a function calling different functions inside is termed as Nesting
Functions.

Example:
// C program to find the factorial of a number.

#include <stdio.h>

//Nesting of functions
//calling function inside another function
//calling fact inside print_fact_table
function

void print_fact_table(int); // function declaration

int fact(int); // function declaration

void main() // main function


{
print_fact_table(5); // function call
}

void print_fact_table(int n) // function definition


{
int i;
for (i=1;i<=n;i++)
printf("%d factorial is %d\n",i,fact(i)); //fact(i)-- function call
}

int fact(int n) // function definition


{
if (n == 1)
return 1;
else
return n * fact(n-1);
}

Output:
1 factorial is 1
2 factorial is 2
3 factorial is 6
4 factorial is 24
5 factorial is 120

Recursion

A function calling same function inside itself is called as recursion.

Example: // C program to find the factorial of a number.

#include <stdio.h>
int fact(int); // function declaration
void main() // main function
{
printf("Factorial =%d",fact(5)); // fact(5) is the function call
}
int fact(int n) // function definition
{
if (n==1) return 1; else
return n * fact(n-1); // fact(n-1) is the recursive function call
}

Output:
Factorial = 120

Discussion:
For 1! , the functions returns 1, for other values, it executes like the one below:
When the value is 5, it comes to else part and calculates like this,
= 5 * fact (5-1) = 5 * fact (4)

= 5* 4* fact (4-1) = 5 * 4* fact (3)

= 5* 4* 3* fact (3-1) = 5 * 4* 3* fact (2)

= 5* 4* 3* 2* fact (2-1) = 5 * 4* 3* 2* fact (1)

= 5* 4* 3* 2* 1 (if (n==1) then return 1, hence we get 1)

=120

Example :

// A program that contains both nested functions and recursion in it.


// Find the maximum number among five different integers using nested function call
and recursion.

int max(int x,int y) // function defintion


{
return x>y ? x:y; // condition operator is used (exp1?exp2:exp3)
}

void main() // main function


{
int m;
m=max(max(4,max(11,6)),max(10,5)); //nested, recursive call
of function max
printf("%d",m);
getch();
}

Output: 11
QUESTIONS FOR PRACTICE
1. What would be the output of the following programs:

(a) main( )
{
int a = 300, b, c ; if ( a >= 400 )
b = 300 ; c = 200 ;
printf ( "\n%d %d", b, c ) ;
}

(b) main( )
{
int a = 500, b, c ; if ( a >= 400 )
b = 300 ; c = 200 ;
printf ( "\n%d %d", b, c ) ;
}

(c) main( )
{
int x = 10, y = 20 ; if ( x == y ) ;
printf ( "\n%d %d", x, y ) ;
}

(d) main( )
{
int x = 3, y = 5 ;
if ( x == 3 )
printf ( "\n%d", x ) ;
else
printf ( "\n%d", y ) ;
}

(e) main( )

{
int x = 3 ; float y = 3.0 ;
if ( x == y )
printf ( "\nx and y are equal" ) ;
else
printf ( "\nx and y are not equal" ) ;
}

(f) main( )
{
int x = 3, y, z ; y = x = 10 ;
z = x < 10 ;
printf ( "\nx = %d y = %d z = %d", x, y, z ) ;
}

(g) main( )
{
int k = 35 ;
printf ( "\n%d %d %d", k == 35, k = 50, k > 40 ) ;
}

(h) main( )
{
int i = 65 ; char j = ‘A’ ;
if ( i == j )
printf ( “C is WOW” ) ;
else
printf( "C is a headache" ) ;
}

(i) main( )
{
int a = 5, b, c ; b = a = 15 ;
c = a < 15 ;
printf ( "\na = %d b = %d c = %d", a, b, c ) ;
}

(j) main( )
{

int x = 15 ;
printf ( "\n%d %d %d", x != 15, x = 20, x < 30 ) ;
}

2. What is the output of this C code (when 1 is entered)?

#include <stdio.h> void main()


{
double ch;
printf("enter a value btw 1 to 2:");
scanf("%lf", &ch);
switch (ch)
{
case 1: printf("1"); break;
case 2: printf("2"); break;
}
}
a) Compile time error
b) 1
c) 2
d) Varies

3. What is the output of this C code (When 1 is entered)?

#include <stdio.h> void main()


{
int ch;
printf("enter a value btw 1 to 2:");
scanf("%d", &ch);
switch (ch, ch + 1)
{
case 1: printf("1\n"); break;
case 2: printf("2"); break;
}
}
a) 1
b) 2
c) 3
d) Run time error

4. Find the output for the following Program


main()
{
int a,b , c =
1000; a = 100;
b = 20;
go to lab;
c = -1000;
printf(“\n Dummy”);
lab: print(“\n C value is %d”,c);
}

5. C program to display all prime numbers between Two interval entered by user.
6. C program to reverse a given number.
7. Program to Check Whether Given Number is Perfect Or Not.
8. Program Even Number Pyramid in C

2 4
2 4 6
2 4 6 8

9. Print prime number Pyramid in C

3 5
7 11 13
17 19 23 29
31 37 41 43 47

10. Write a C program to find the summation of the following series :

a) 1+ 2 + 3 +......+ n.
2 2 2 2
b) 1 + 2 + 3 +.... + n .
11. The keyword used to transfer control from a function back to the calling
function is
a) Switch b) Return c) Goto
12. Write a program to Calculate the Power of a Number Using Recursion
13. How many times the program will print "Sathyabama University" ?
#include<stdio.h>
int main()
{
printf("\nSathyabma University");
main();
return 0;
}
a) Infinite times b) 32767 times c) Till stack overflows
14. What will be the output of the program?
#include<stdio.h>
int f1(int);
int main()
{
int k=35;
k = f1(k=f1(k=f1(k)));
printf("k=%d\n", k);
return 0;
}
int f1(int k)
{
k++;
return k;
}
15. Which of the following function declaration is illegal?
a) int 11bhk(int); b) int 11bh2k(int a);
c) int 22bhk2(int*, int []); d) All of the mentioned

16. Which function is not called in the following program?


#include <stdio.h>
void one()
{
printf("first");
}
void two()
{
one();
}
void three()
{
two();
}
void main()
{
void (*ptr)();
ptr = three;
ptr();
}
a) Function first b) Function second
c) Function third d) None of the mentioned
17. What will be the output of the program?
#include<stdio.h>
void fun(int*, int*);
int main()
{
int i=5, j=2;
fun(&i, &j);
printf("%d, %d", i, j);
return 0;
}
void fun(int *a, int *b)
{
*a = *a**b;
*b = *a**b;
}
Scope and Lifetime of Variables

Types of Variable Scope

1. Local Scope: Variables declared inside a function or block.


2. Global Scope: Variables declared outside all functions.
3. Block Scope: Variables declared within a specific block, such as inside loops or conditionals.
4. File Scope: Variables declared at the file level (outside functions) and limited to the file when marked
as static.

Lifetime of Variables

 The lifetime refers to how long the variable retains its value in memory.
 Variables can have automatic, static, or dynamic lifetimes depending on where and how they’re declared

Example 1: Local Scope and Automatic Lifetime

Local variables declared within a function have local scope and automatic lifetime. This means they are
created when the function is called and destroyed when the function exits.

#include <stdio.h>

void exampleFunction() {

int localVar = 10; // Local to exampleFunction

printf("Local variable: %d\n", localVar);

int main() {

exampleFunction();

// printf("%d", localVar); // Error: localVar not accessible here

return 0;

In this example, localVar exists only within example Function. When example Function is
called, localVar is created, and when the function exits, it is destroyed.

Example 2: Global Scope and Lifetime

Global variables are declared outside of any function and have global scope. They are accessible from any
function in the same file and have a static lifetime, meaning they exist for the entire runtime of the
program.
#include <stdio.h>

int globalVar = 20; // Global variable

void display() {

printf("Global variable: %d\n", globalVar);

int main() {

printf("Accessing global variable in main: %d\n", globalVar);

display(); // Also accesses globalVar

return 0;

In this case, globalVar is accessible both in main and display functions and remains in memory for the
program’s lifetime.

Example 3: Block Scope and Limited Lifetime

Block scope applies to variables declared within specific blocks like loops, conditionals, or other code
blocks.

#include <stdio.h>

int main() {

for (int i = 0; i < 3; i++) { // i has block scope

printf("i in loop: %d\n", i);

// printf("%d", i); // Error: i is not accessible here

return 0;

Here, the variable i has block scope, limited to the for loop. It is created when the loop starts and
destroyed when the loop ends.

Example 4: Static Local Variable

A static local variable has a local scope (accessible only within the function) but a static lifetime (it
retains its value between function calls).
#include <stdio.h>

void staticExample() {

static int count = 0; // Static local variable

count++;

printf("Static variable count: %d\n", count);

int main() {

staticExample(); // Output: 1

staticExample(); // Output: 2

staticExample(); // Output: 3

return 0;

Here, count is a local variable with static storage, so it retains its value between calls to staticExample.

Example 5: extern Keyword for Global Variables Across Files

The extern keyword is used to declare a global variable in another file, allowing access across multiple
files.

File 1 (file1.c):

#include <stdio.h>

int globalVar = 100; // Global variable definition

void display() {

printf("Global variable in file1: %d\n", globalVar);

File 2 (file2.c):

#include <stdio.h>

extern int globalVar; // Declaration of global variable in another file

int main() {
printf("Accessing globalVar from file2: %d\n", globalVar);

return 0;

In file2.c, we declare globalVar with extern, indicating that it is defined in another file. This
allows file2.c to access globalVar from file1.c.
C programming and problem solving Module 3

MODULE 3
Arrays
INTRODUCTION
Arrays: Array is a sequential collection of similar data items.
Pictorial representation of an array of 5 integers

10 20 30 40 50
A[0] A[1] A[2] A[3] A[4]

 An array is a collection of similar data items.


 All the elements of the array share a common name .
 Each element in the array can be accessed by the subscript(or index) and array name.
 The arrays are classified as:
1. Single dimensional array
2. Multidimensional array.

Single Dimensional Array.

 A single dimensional array is a linear list of related data items of same data type.
 In memory, all the data items are stored in contiguous memory locations.
Declaration of one-dimensional array(Single dimensional array)
Syntax:

datatype array_name[size];

 datatype can be int,float,char,double.


 array_name is the name of the array and it should be an valid identifier.
 Size is the total number of elements in array.
For example:
int a[5];
The above statement allocates 5*2=10 Bytes of memory for the array a.

a[0] a[1] a[2] a[3] a[4]

float b[5];

Dr. Jyoti Metan,CSE,ACSCE 1


C programming and problem solving Module 3

The above statement allocatests 5*4=20 Bytes of memory for the array b.

 Each element in the array is identified using integer number called as index.
 If n is the size of array, the array index starts from 0 and ends at n-1.

Storing Values in Arrays

 Declaration of arrays only allocates memory space for array. But array elements are not initialized
and hence values has to be stored.
 Therefore to store the values in array, there are 3 methods
1. Initialization
2. Assigning Values
3. Input values from keyboard through scanf()

Initialization of one-dimensional array


 Assigning the required values to an array elements before processing is called initialization.

data type array_name[expression]={v1,v2,v3…,vn};

Where
 datatype can be char,int,float,double
 array name is the valid identifier
 size is the number of elements in array
 v1,v2,v3…......vn are values to be assigned.

 Arrays can be initialized at declaration time.


Example:
int a[5]={2,4,34,3,4};

2 4 34 3 4

a[0] a[1] a[2] a[3] a[4]

 The various ways of initializing arrays are as follows:


1. Initializing all elements of array(Complete array initialization)
2. Partial array initialization

Dr. Jyoti Metan,CSE,ACSCE 2


C programming and problem solving Module 3

3. Initialization without size


4. String initialization

1. Initializing all elements of array:


 Arrays can be initialized at the time of declaration when their initial values are known in advance.
 In this type of array initialization, initialize all the elements of specified memory size.
 Example:
int a[5]={10,20,30,40,50};
10 20 30 40 50

2. Partial array initialization


 If the number of values to be initialized is less than the size of array then it is called as partial
array initialization.
 In such a case elements are initialized in the order from 0th element.
 The remaining elements will be initialized to zero automatically by the compiler.
 Example:
int a[5]={10,20};

10 20 0 0 0

3. Initialization without size


 In the declaration the array size will be set to the total number of initial values specified.
 The compiler will set the size based on the number of initial values.
 Example:
int a[ ]={10,20,30,40,50};
 In the above example the size of an array is set to 5

4. String Initialization
 Sequence of characters enclosed within double quotes is called as string.
 The string always ends with NULL character(\0)

char s[5]=”SVIT”; We can observe that string length is 4,but size


is 5 because to store NULL character we need
one more location.

So pictorial representation of an array s is as follows:

Dr. Jyoti Metan,CSE,ACSCE 3


C programming and problem solving Module 3

S V I T \0
S[0] S[1] S[2] S[3] S[4]

3.1.2 Assigning values to arrays


Using assignment operators, we can assign values to individual elements of arrays.
For example:
int a[3];
a[0]=10;
a[1]=20;
a[2]=30;

10 20 30

a[0] a[1] a[2]

Reading and writing single dimensional arrays.


To read array elements from keyboard we can use scanf() function as follows:

To read 0th element: scanf(“%d”,&a[0]);


To read 1st element: scanf(“%d”,&a[1]);
To read 2nd element: scanf(“%d”,&a[2]);
……
…….
th
To read n element : scanf(“%d”,&a[n-1]);
In general
To read ith element:
scanf(“%d”,&a[i]); where i=0; i<n; i++

To print array elements we can use printf() function as follows:

To print 0th element: printf(“%d”,a[0]);


To print 1st element: printf(“%d”,a[1]);
To print 2nd element :printf(“%d”,a[2]);
……..
……..

To nth element : printf(“%d”,&a[n-1]);


In general
To read ith element:
printf(“%d”,a[i]); where i=0; i<n; i++

Dr. Jyoti Metan,CSE,ACSCE 4


C programming and problem solving Module 3

1. Write a C program to read N elements from keyboard and to print N elements on


screen.
/* program to read N elements from keyboard and to print N elements on
screen */
#include<stdio.h>
void main()
{
int i,n,a[10];
printf(“enter number of array elements\n”);
scanf(“%d”,&n);
printf(“enter array elements\n”);
for(i=0; i<n;i++)
{
scanf(“%d”,&a[i]);
}

Printf(“array elements are\n”):


for(i=0; i<n;i++)
{
printf(“%d”,a[i]);
}
}

2. Write a C program to find sum of n array elements .

/* program to find the sum of n array elements.*/


#include<stdio.h>
void main()
{
int i,n,a[10],sum=0;
printf(“enter number of array elements\n”);
scanf(“%d”,&n);
printf(“enter array elements\n”);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
}

for(i=0; i<n;i++)
{
sum=sum+ a[i];

Dr. Jyoti Metan,CSE,ACSCE 5


C programming and problem solving Module 3

}
printf(“sum is %d\n”,sum):

3. Write a c program to find largest of n elements stored in an array a.

#include<stdio.h>
void main()
{
int i,n,a[10],big;
printf(“enter number of array elements\n”);
scanf(“%d”,&n);
printf(“enter array elements\n”);
for(i=0; i<n;i++)
{
scanf(“%d”,&a[i]);
}
big=a[0];
for(i=0; i<n;i++)
{
if(a[i]>big)
big=a[i];
}
printf(“the biggest element in an array is %d\n”,big);
}

4. Write a C program to generate Fibonacci numbers using arrays.

#include<stdio.h>
void main()
{
int i,n,a[10];
a[0]=0;
a[1]=1;
printf(“enter n\n”);
scanf(“%d”,&n);
if(n==1)
{
printf(“%d\t”,a[0]);
}
if(n==2)
{
printf(“%d\t %d\t”,a[0],a[1]);
}
if(n>2)

Dr. Jyoti Metan,CSE,ACSCE 6


C programming and problem solving Module 3

{
printf(“%d \t %d\t”,a[0],a[1]);
for(i=2;i<n;i++)
{
a[i]=a[i-1]+a[i-2];
printf(“%d\t”,a[i]);
}
}
}

Two Dimensional arrays:


 In two dimensional arrays, elements will be arranged in rows and columns.
 To identify two dimensional arrays we will use two indices(say i and j) where I index indicates row
number and j index indicates column number.

Declaration of two dimensional array:

data_type array_name[exp1][exp2];
Or
data_type
array_name[row_size][column_size];

 data_type can be int,float,char,double.


 array_name is the name of the array.
 exp1 and exp2 indicates number of rows and columns

For example:
int a[2][3];
 The above statements allocates memory for 3*4=12 elements i.e 12*2=24 bytes.

Initialization of two dimensional array


Assigning or providing the required values to a variable before processing is called initialization.
Data_type array_name[exp1][exp2]={

{a1,a2,......an}
{b1,b2,.....bn}
..............
{z1,z2........zn}

Dr. Jyoti Metan,CSE,ACSCE 7


C programming and problem solving Module 3

 Data type can be int,float etc.


 exp1 and exp2 are enclosed within square brackets .
 both exp1 and exp2 can be integer constants or constant integer expressions(number of rows and
number of columns).
 a1 to an are the values assigned to 1st row ,
 b1 to bn are the values assigned to 2nd row and so on.
 Example:
int a[3][3]={
{10,20,30},
{40,50,60},
{70,80,90}
};

10 20 30

40 50 60

70 80 90

Partial Array Initialization


 If the number of values to be initialized is less than the size of array, then the elements are
initialized from left to right one after the other.
 The remaining locations initialized to zero automatically.
 Example:
int a[3][3]={
{10,20},
{40,50},
{70,80}
};
10 20 0

40 50 0

70 80 0

Dr. Jyoti Metan,CSE,ACSCE 8


C programming and problem solving Module 3

1. Write a c program to read & print 2d array as a Array.

#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“eneter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“array elements are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
}

2 Write a c program to add two matrices.

#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3],b[3][3] ,c[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array a elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}

Dr. Jyoti Metan,CSE,ACSCE 9


C programming and problem solving Module 3

printf(“enter array b elements\n”);


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&b[i][j]);
}
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“resultant matrix c is \n”);

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}

3 Write a c program to copy one 2d array in to another 2d array


#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,i,j,a[3][3],b[3][3];
clrscr();
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array a elements\n”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf(“%d”, &a[i][j]);
}
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)

Dr. Jyoti Metan,CSE,ACSCE 10


C programming and problem solving Module 3

{
b[i][j]=a[i][j];
}
}
printf(“matrix b is \n”);

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
}

4 Write a c program to find biggest element in a matrix or 2D array.


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

int m,n,i,j,a[3][3];
clrscr();
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
big=a[0][0];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(big>a[i][j])
big=a[i][j];
}
}
printf(“big is %”,big);
}

Dr. Jyoti Metan,CSE,ACSCE 11


C programming and problem solving Module 3

5 Write a C program to implement Matrix Multiplication

#include<stdio.h>
void main()
{
int m,n,i,j,sum,p,q,k,a[3][3],b[3][3],c[3][3];
printf(“enter number of rows and columns of matrix a \n”);
scanf(“%d %d”,&m,&n);
printf(“enter number of rows and columns of matrix b \n”);
scanf(“%d %d”,&p,&q);
if(n!=p)
{
printf(“multiplication not possible\n”):
exit(0);
}

printf(“enter matrix a elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}

printf(“enter array b elements\n”);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf(“%d”,&b[i][j]);
}
}

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}

}
}
printf(“resultant matrix a is \n”);

for(i=0;i<m;i++)

Dr. Jyoti Metan,CSE,ACSCE 12


C programming and problem solving Module 3

{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix a is \n”);

for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix a is \n”);

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}

6 Write a program to find sum of each row and sum of each column
#include<stdio.h>
void main()
{

int m,n,i,j,rsum,csum,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{
rsum=0;

Dr. Jyoti Metan,CSE,ACSCE 13


C programming and problem solving Module 3

for(j=0;j<n;j++)
{
rsum=rsum+a[i][j];
}
printf(“sum is %d”,rsum);
}

for(i=0;i<m;i++)
{
csum=0;
for(j=0;j<n;j++)
{
csum=csum+a[i][j];
}
printf(“sum is %d”,csum);
}

7 Write a C program to add all 2D array elements

#include<stdio.h>
void main()
{
int m,n,i,j,sum=0,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{

sum=sum+a[i][j];

}
printf(“sum is %d”,rsum);
}

Dr. Jyoti Metan,CSE,ACSCE 14


C programming and problem solving Module 3

Searching
 The process of finding a particular item in the large amount of data is called searching.
 The element to be searched is called key element.
There are two methods of searching:
1] Linear search.
2] Binary search.

1] Linear Search:
 Linear search also called sequential search is a simple searching technique.
 In this technique we search for a given key item in linear order i.e,one after the other from
first element to last element.
 The search may be successful or unsuccessful.
 If key item is present, the search is successful, otherwise unsuccessful search.

1. Program to implement linear search.


#include<stdio.h>
void main()
{
int i,n,a[10],key;
clrscr( );
printf(“enter array elements\n”);
scanf(“%d”,&n);
printf(“enter array elements\n”);
for(i=0; i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter the key element\n”);
scanf(“%d”,,&key);

for(i=0; i<n;i++)
{if(key==a[i])

Dr. Jyoti Metan,CSE,ACSCE 15


C programming and problem solving Module 3

{
printf(“successful search\n”);
exit(0);
}
}
printf(“unsuccessful search\n”);
}

Advantages of linear search


 Very simple Approach.
 Works well for small arrays.
 Used to search when elements are not sorted.

Disadvantages of linear search


 Less efficient if array size is large
 If the elements are already sorted, linear search is not efficient.

2] Binary Search:
 Binary search is a simple and very efficient searching technique which can be applied if the items are
arranged in either ascending or descending order.
 In binary search first element is considered as low and last element is considered as high.
 Position of middle element is found by taking first and last element is as follows.
mid=(low+high)/2

 Mid element is compared with key element, if they are same, the search is successful.
 Otherwise if key element is less than middle element then searching continues in left part of the array.
 If key element is greater than middle element then searching continues in right part of the array.
 The procedure is repeated till key item is found or key item is not found.

write a C program to perform binary search on the array of integers

/* C program to search a name in a list of names using Binary


searching technique*/
#include<stdio.h>
void main()
{
int i, n, low, high, mid,a[50],key;
printf(“enter the number of elements\n”):
scanf(“%d”,&n);
printf(“enter the elements\n”);
for(i=0;i<n;i++)
{
Scanf(“%d”,&a[i]);
}

printf(“enter the key element to be searched\n”);


scanf(“%d”,&key);

Dr. Jyoti Metan,CSE,ACSCE 16


C programming and problem solving Module 3

low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
printf(“successful search\n”);
exit(0);
}
if(key<a[mid])
{
high=mid-1;
}
else
{
low=mid+1;
}
}
printf(“unsuccesfull seasrch\n”);
}

Advantages of binary search


1. Simple technique
2. Very efficient searching technique
Disadvantages
1. The elements should be sorted.
2. It is necessary to obtain the middle element, which are stored in array. If the elements are stored in linked
list, this method cannot be used.

Sorting
 The process of arranging elements in either ascending order or descending order is called Sorting.

Bubble Sort

 This is the simplest and easiest sorting technique.


 In this technique two successive elements of an array such as a[j] and a[j+1] are compared.
 If a[j]>=a[j+1] the they are exchanged, this process repeats till all elements of an array are arranged in
ascending order.
 After each pass the largest element in the array is sinks at the bottom and the smallest element in the
array is bubble towards top. So this sorting technique is also called as sinking sort and bubble sort.

Dr. Jyoti Metan,CSE,ACSCE 17


C programming and problem solving Module 3

Write a C program to sort numbers in ascending order using Bubble Sort


#include<stdio.h>
void main()
{
int i,j,n,a[50],temp;
printf(“enter n:\n”);
scanf(“%d”,&n);
printf(“enter array efficient \n”);
for(i=0; i<n;i++)
{
scanf(“%d”,&a[i]);
} for descending order sorting
for(i=0; i<n-1;i++) give a[j]<a[j+1]
{
for(j=0; j<n-1; j++)
{
if (a[ j ]>a[ j+1] )
{
temp= a[ j ];
a[ j ]= a[ j+1 ];
a[ j+1 ]=temp;
}
}
}

printf(“\n the sorted numbers are:\n”);


for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]);
}

getch();
}

Dr. Jyoti Metan,CSE,ACSCE 18


C programming and problem solving Module 3

Selection Sort
In Selection sort, the smallest element is exchanged with the first element of the unsorted list of elements
(the exchanged element takes the place where smallest element is initially placed). Then the second
smallest element is exchanged with the second element of the unsorted list of elements and so on until all
the elements are sorted. In the following C program we have implemented the same logic.

Before going through the program, lets see the steps of selection sort with the help of an example:
Entered elements: 22 0 -90 89 17
Step 1: -90 0 22 89 17 (22 and -90 exchanged position)
Step 2: -90 0 22 89 17 (0 is at right place, no exchange needed)
Step 3: -90 0 17 89 22 (22 and 17 exchanged position)
Step 4: -90 0 17 22 89 (89 and 22 exchanged position)

Selection sort Program


#include<stdio.h>
void main()
{
int i,j,n,a[20],temp,min;
printf(“enter n:\n”);
scanf(“%d”,&n);
printf(“enter array efficient \n”);
for(i=0; i<n;i++)
{
scanf(“%d”,&a[i]);
}

for(i=0; i<n-1;i++)
{
min=i;
//finding min value starting from index i+1
for(j=i+1; j<n; j++)
{
if (a[ j ]>a[ min] )
{
min=j;
}
}
//starting 1st element of unsorted part with min value
temp= a[ j ];
a[ j ]= a[ j+1 ];
a[ j+1 ]=temp;

Dr. Jyoti Metan,CSE,ACSCE 19


C programming and problem solving Module 3

printf(“\n the sorted numbers are:\n”);


for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]);
}

getch();
}

Write a C program to evaluate the polynomial using Horners method.


#include<stdio.h>
void main()
{
int i,x,n,a[10],sum;
printf(“enter n:\n”);
scanf(“%d”,&n);
printf(“enter n+1 co efficient\n”);
for(i=0; i<=n;i++)
{
scanf(“%d”,&a[i]);
}
sum=a[n]* x;
for(i=n-1; i>0; i--)
{
sum=(sum+a[i]) *x;
}
sum=sum+a[0];
printf(“sum of polynomial equation is %d”,sum);
}

Dr. Jyoti Metan,CSE,ACSCE 20


C programming and problem solving Module 3

Strings

Definition:
 A string is a sequence of characters within double quotes. A string constant is always terminated y null character.
 A string is pictorially represented as follows:

a S V I T \0
0 1 2 3 4

String Declaration:
 Like all other variable a string variable a string variable also has to be declared before it is used.

Syntax: char string_name[size];

Example: char s[10];

The above declaration statement allocates 10 bytes of memory to string s as follows:

0 1 2 3 4 5 6 7 8 9

String Initialization:
Initialization is a process of assigning values to a string, before doing manipulation.
Strings are initialized in 4 ways:
1. Initializing character by character
2. Partial Array Initialization
3. Initialization without size
4. Initialization of Array with string

Dept of CSE,ACSCE Page 1


[Link] character by character 2. Partial Array Initialization
 Consider following declaration and initialization  If the number of characters to be initialized is less than
char b[5]={ „S‟,‟V‟,‟I‟,‟T‟}; the size of array then the remaining locations will be
 The complier allocates 5 memory locations and these initialized to NULL as follows:
locations are initialized with the character in the order Char b[5]={ „H‟,‟I‟};
specified.
b S V I T \0 b H I \0 \0 \0
0 1 2 3 4 0 1 2 3 4

[Link] without Size [Link] of array with string


 If a string is declared without size then compiler will set
the array size to the total number of initialized values. char b[]=”SVIT”;
char b[]={ „S‟,‟V‟,‟I‟,‟T‟};
In the above initialization the string length is 4 bytes but size is
b H I \0 \0 \0 5 bytes.
0 12 3 4 b S V I T \0
Size of b is 4 0 1 2 3 4

String Input and Output functions:


 The strings can be read from the keyboard and can be displayed onto the monitor using various functions:

[Ty pe text] [Ty pe text] [Ty pe text]


C programming and problem solving

Formatted Input Function: scanf() Formatted Output Function: printf()


 The formatted input function is scanf().  The formatted output function is printff().
 It reads a string from the keyboard  It prints/displays a string which is stored on memory
 The format specifier is %s locations on monitor
 The string is terminated by NULL character(\0) Syntax: printf(“%s”,str);
Syntax: scanf(“%s”,str);  Example:
 Example: char str[5]=”SVIT”;
char str[5]=”SVIT”; printf(“%s”,str);
scanf(“%s”,str);

b S V I T \0
0 1 2 3 4
NOTE: scanf() cannot read spaces and any special symbols i.e
conversion code cannot read spaces, it will terminated as soon
as space appear.
Write a program to read and print an string using scanf() and printf()
#include<stdio.h>
void main()
{
char str[20];
printf(“enter the string\n”);
scanf(“%s”,str);
printf(“The entered string is \n”);
printf(“%s”,str);
}

Dept of CSE,ACSCE Page 3


C programming and problem solving

UnFormatted Input Function: scanf() UnFormatted output Function: puts()


 The Unformatted input function is gets().  The Unformatted output function is puts().
 It reads a sequence of characters(line) from the keyboard  This function displays all the character(line) stored in
with spaces in between and store them in memory variable str on the monitor till it encounters \0(Null
locations. Character)
Syntax: gets(str); Syntax: gets(str);
 Example:  Example:
char str[20]; char str[20]=”HELLO”;
printf(“enter the string\n”); printf(“the string is \n”);
gets(str); puts(str);

Write a program to read and print an string using gets() and puts()
#include<stdio.h> OutPut:
#include<string.h>
void main() Enter the string
{ HELLO HOW R U
char str[20]; The entered string is
printf(“enter the string\n”); HELLO HOW R U

gets(str);
printf(“The entered string is \n”);
puts(str);
}
H E L L O H O W R U \0

Dept of CSE,ACSCE Page 4


C programming and problem solving

Based on the kind of data processed, the I/O function are classified into
1. Token Oriented I/O functions:
2. Line Oriented I/O functions
3. Character Oriented I/O functions

1. Token Oriented I/O functions:


 The I/O functions processes individual units such as characters,integers,double values,float values and are separated by
whitespaces characters. Since these individual units are called tokens,the functions that perform these kind of operations are
called Token Oriented I/O functions.
 The functions scanf() and printf() are Token Oriented I/O functions.
2. Line Oriented I/O functions
 The I/O functions that process entire line are called line oriented I/O functions.
 The functions gets() and puts() are Line Oriented I/O functions.
3. Character Oriented I/O functions
a) getchar() and putchar()
 To read a character from the keyboard and store this character into memory location, getchar() function is used.
 We have to press the ENTER KEY after typing character.
Syntax: ch=getchar();
 To display a character stored in the memory on the screen ,putchar() function is used.
Syntax:putchar(ch);

Write a C program to Find the section of student.


#include<stdio.h>
#include<string.h>
void main()
{
char sec; OUTPUT
printf(“Enter your section\n”); Enter Your Section
scanf(“%d”,&sec); B

Dept of CSE,ACSCE Page 5


C programming and problem solving

sec=getchar(); Your section is


printf(“Your section is \n”); B
putchar(sec);
}
b) getch(),getche(),putch()
 The getch() function reads a character from the keyboard and copies it into specified memory location identified by ch.
 Syntax: ch=getch()
 The typed character will not be echoed(displayed) on the screen if we use getch() function.
 No arguments are required for this function
 The getche() function reads a character from the keyboard and copies it into specified memory location identified by ch.
 Syntax: ch=getche()
 The typed character will be echoed(displayed) on the screen if we use getche() function. No arguments are required for this
function
 The putchar() displays a character stored in memory location identified by variable ch on the screen.
 Syntax: putch(ch)

Dept of CSE,ACSCE Page 6


C Programming and Problem Solving (18PCD23)

String handling Functions


SL. Name Syntax Example Explanation
No
1 strlen int strlen (char str[ ]); char str[15]=”SVIT”; -This function returns the length of
int count; the string str.
count=strlen(str); -It counts all the characters until
S V I T \0 null character is encountered.
0 1 2 3 4
The example str variable contains 4
characters S,V,I,T , hence count is 4

2 strcpy strcpy(char dest[ ] , char src[ ]); char src[5] =”SVIT”;  This function copies content
char dest[5]; from source string to
strcpy(dest ,src); destination string including \0.
src[0] src[1] src[2] src[3] src[4]  Size of dest string should be
s V I T \0 greater or equal to the size of
source string src to store the
S V I T \0 entire source string.

dest[0] dest [1] dest [2] dest [3] dest [4]

Dept of CSEACSCE Page 7


C programming and problem solving

3. strncpy strcpy(char dest[ ] , char src[ ],int n); char src[5] =”SVIT”;  This function copies n
char dest[5]; characters from source string to
strcpy(dest ,src,2); destination string .
src[0] src[1] src[2] src[3] src[4]  In thisexample only 2
S V I T \0 characters are copied from src
to dest.
S V \0

dest[0] dest [1] dest [2] dest [3] dest [4]

4 strcat strcat(char s1[ ] , char s2[ ]); char s1[5]=”SVIT”;


char s2[5]=”ECE”;  This function copies the all
strcat(s1,s2); characters of s2 string to the
S V I T \0 end of s1 string.
0 1 2 3 4  The delimiter of s1 is replaced
by first character of s2.
E C E \0  Size of s1 string should be
0 1 2 3 4 greater or store the contents of
both the string
S1 S V I T E C E \0
0 1 2 3 4 4 6 7 8 9

5 strncat strncat(char s1[ ] , char s2[ ],n); char s1[5]=”SVIT”;  This function copies the n
char s2[5]=”ECE”; characters of s2 string to the
strncat(s1,s2,2); end of s1 string.
 The delimiter of s1 is replaced
S V I T \0 by first character of s2.
0 1 2 3 4

Dept of CSE,ACSCE Page 8


C programming and problem solving

E C E \0
0 1 2 3 4

S1 S V I T E C \
0
0 1 2 3 4 4 6 7 8 9

In the above example only 2 characters(EC)


from string s2 copies to string s1.

6 strcmp int strcmp( char s1[ ] , char s2[ ]); 1) Strings are equal where:
S1[4]=”RAM”; s1 is first string
S2[4]=”RAM”; s2 is second string
Strcmp(S1,S2);  This function used to
compare two strings.
R == S2[0] R  The comparison starts with
S1[0] first character of each
S1[1] A == S2[1] A string.
S1[2] M == S3[2] M  This comparison continues
S1[3] \0 == S4[3] \0 till the corresponding
character differ or until the
S1[0]==S2[0] end of the character is
R==R(ASCII value of R is compared) reached.
similarly for other characters.  The strcmp Returns 3values
S1[3]==S2[3] Possibly:
\0==\0(ASCII value of \0 is compared and it returns 0 if both strings are equal.
is 0.) returns positive value ,if s1>s2
2)String S1 is Lesser than String S2 returns negative value if s1<s2

Dept of CSE,ACSCE Page 9


C programming and problem solving

S1[4]=”ABC”;
S2[4]=”BAC”;
Strcmp(S1,S2);

S1[0] A == S2[0] B
S1[1] B == S2[1] A
S1[2] C == S3[2] C
S1[3] \0 == S4[3] \0

S1[0]==S2[0]
A==B(ASCII value of A is compared with
ASCII value of B)
i.e 65==66 returns S1<S2

3)String S1 is Greater than String S2


S1[4]=”BBC”;
S2[4]=”ABC”;
Strcmp(S1,S2);

S1[0] B == S2[0] A
S1[1] B == S2[1] B
S1[2] C == S3[2] C
S1[3] \0 == S4[3] \0

S1[0]==S2[0]
A==B(ASCII value of A is compared with
ASCII value of B)
i.e 66==65 returns S1>S2

Dept of CSE,ACSCE Page 10


C programming and problem solving

7 strncmp int strcmp( char s1[ ] , char s2[ ], n); 1) Strings are equal where:
S1[4]=”RAM”; s1 is first string
S2[4]=”RAM”; s2 is second string
strcmp(S1,S2,2);  This function used to
comparen number of
R == S2[0] R characters two strings.
S1[0]  The comparison starts with
S1[1] A == S2[1] A first character of each
S1[2] M == S3[2] M string.
S1[3] \0 == S4[3] \0  This comparison continues
till the corresponding
Only 2 characters from each S1 and S2 is character differ or until the
compared. end of the character is
Other function is similar to strcmp(). reached or specified number
of characters have been
tested..
 The strcmp Returns 3values
Possibly:
returns 0 if both strings are equal.
returns positive value ,if s1>s2
returns negative value if s1<s2

8 strrev( ) void strrev(char str[ ]); Given string  This function reverse all
S1 S V I T E C E \0 characters in the S1 except
0 1 2 3 4 5 6 7 89 Null character.
strrev(s1  The original string is lost.
Reverse String
S1 E C E T I V S \0
0 1 2 3 4 5 6 7 8 9

Dept of CSE,ACSCE Page 11


C programming and problem solving

S1[6]==S1[0]
S1[5]==S1[1]
S1[4]==S1[2]
S1[3]==S1[3]
S1[2]==S1[4]
S1[1]==S1[5]
S1[0]==S1[6]

Example Programs for string handling functions

strlen() strrev()
#include<stdio.h>
#include<stdio.h> #include<string.h>
#include<string.h> void main()
void main() {
{ char name[15]; char str[]=”INDIA”;
int len; strrev(str);
printf(“Enter the string\n”); printf(“string=%s”,str);
gets(name); }
len=strlen(name);
printf(“\n The string length is %d”,len); OUTPUT
} String=AIDNI

OUTPUT
Enter the string
COMPUTER
The string length is 8

Dept of CSE,ACSCE Page 12


C Programming and Problem Solving (18PCD23)

strcpy() strncpy()

#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
void main() void main()
{ {
char src[15],char dest[15]; char src[15],char dest[15];
printf(“Enter the source string\n”); int n;
gets(src); printf(“Enter the source string\n”);
strcpy(dest,src); gets(src);
printf(“\n The copied string is \n”); printf(“Enter n”);
puts(dest); scanf(“%d”,&n);
} strncpy(dest,src);
printf(“\n The copied string is \n”);
puts(dest);
OUTPUT }
Enter the source string
COMPUTER OUTPUT
The copied string is Enter the source string
COMPUTER COMPUTER
Enter n
3
The copied string is
COM
strcat() strncat()

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

Dept of CSE,ACSCE Page 13


C Programming and problem solving (18PCD23)

{ {
char S1[15],char S2[15]; char S1[15],char S2[15];
printf(“Enter the string 1\n”); int n;
gets(S1); printf(“Enter the string 1\n”);
printf(“Enter the string 2\n”); gets(S1);
gets(S2); printf(“Enter the string 2\n”);
strcat(S1,S2); gets(S2);
printf(“\n The Concatenated string is \n”); printf(“Enter n”);
puts(S1); scanf(“%d”,&n);
} strncat(S1,S2,n);
printf(“\n The Concatenated string is \n”);
OUTPUT puts(S1);
Enter the string1 }
HELLO
Enter the string 2 OUTPUT
ALL Enter the string1
The Concatenated string is HELLO
HELLOALL Enter the string 2
SVIT
Enter n
2
The Concatenated string is
HELLOSV
strcmp() strcnmp()
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
void main() void main()
{ {
char S1[15],char S2[15]; char S1[15],char S2[15];

Dept of CSE,ACSCE Page 14


C programming and problem Solving(18PCD23)

int res; int res,n;


printf(“Enter the string 1\n”); printf(“Enter the string 1\n”);
gets(S1); gets(S1);
printf(“Enter the string 2\n”); printf(“Enter the string 2\n”);
gets(S2); gets(S2);
res=strcmp(S1,S2); printf(“Enter n”);
if(res==0) scanf(“%d”,&n);
printf(“Strings are same\n”); res=strcmp(S1,S2,n);
else if(res>0) if(res==0)
printf(“String1 is greater than string2\n”); printf(“Strings are same\n”);
else else if(res>0)
printf(“String1 is lesser than string2\n”); printf(“String1 is greater than string2\n”);
} else
printf(“String1 is lesser than string2\n”);
}
OUTPUT OUTPUT
Enter the string1 Enter the string1
HELLO SVIT
Enter the string 2 Enter the string 2
HELLO SVCE
The Strings are equal Enter n
2
String1 is greater than String2
Edit Set Conversion Code (%[…])
 Using edit set conversion code ,it is possible to enter a line of text with white spaces such as blank character,\t etc…
 Syntax:scanf(%[....... ] ,str)

edit characters

Dept of CSE,ACSCE Page 15


C programming and problem solving

 edit characters represent the valid characters that are allowed in the string and should be enclosed within „ [ „ and „]‟
Working:
 Each character read by scanf is compared with edit character set.
 If the character read is in edit character set, it is copied into str
 The above procedure is repeated as long as the character read is in edit character set.
 If the character read does not match with edit character set, the reading process is stopped and remaining characters will still
be available in keyboard buffer.
 If the first character read is not in edit characters set, the scanf is terminated and a „\0‟ is copied into str indicating null
string.
 The edit characters set is indicated by the symbol caret(^)

scanf(“%[^\n]”,str); // read all characters except \n

Array of Strings
 Group of Strings is known as array of strings.
 To represent array of strings two dimensional array is required.
Declaration Syntax: char string_name[row][column];

Maximum length of each string


Number of Strings

Name of the Array

Example: char a[5][20];

Where a is the string name

5 indicates at most 5 names can be stored

20 indicate that each name can have at most 20 characters

Dept of CSE,ACSCE Page 16


C programming and problem solving

Initialization

char a[5][10]={

“ARJUN”,
“BHARATHI”,
“SAMAYA”,
“SVIT”,
“VINAYAKA”
};

 Memory representation of the above initialization is as follows..

0 1 2 3 4 5 6 7 8 9
0 A R J U N \0
a B H A R A T H I \0
1
2 S A M A Y A \0
3 S V I T \0
4 V I N A Y A K A \0
Note: Example program is binary search

Dept of CSE,ACSCE Page 17


C programming and problem solving

Dept of CSE,ACSCE Page 17


2.2 Pointers

1 Department of CSE
Objectives
• To understand the need and application of pointers
• To learn how to declare a pointer and how it is represented in
memory
• To learn the relation between arrays and pointers
• To study the need for call-by-reference
• To distinguish between some special types of pointers

2 Department of CSE
Agenda
• Basics of Pointers
• Declaration and Memory Representation
• Operators associated with pointers
• address of operator
• dereferencing operator
• Arrays and Pointers.
• Compatibility of pointers
• Functions and Pointers
• Special types of pointers
• void pointer
• null pointer
• constant pointers
• dangling pointers
• pointer to pointer

3 Department of CSE
Introduction

• A pointer is defined as a variable whose value is the address of


another variable.
• It is mandatory to declare a pointer before using it to store any
variable address.

4 Department of CSE
Pointer Declaration
• General form of a pointer variable declaration:-
datatype *ptrname;

• Eg:-
• int *p; (p is a pointer that can point only integer variables)
• float *fp; (fp can point only floating-point variables)

• Actual data type of the value of all pointers is a long hexadecimal


number that represents a memory address

5 Department of CSE
Initialization of Pointer Variable
• Uninitialized pointers will have some unknown memory address in them.

• Initialize/ Assign a valid memory address to the pointer.


Initialization Assignment
int a; int a;
int *p = &a; int *p;
p = &a;

• The variable should be defined before pointer.

• Initializing pointer to NULL


int *p = NULL;

6 Department of CSE
Why Pointers?
• Manages memory more efficiently.

• Leads to more compact and efficient code than that can be obtained
in other ways

• One way to have a function modify the actual value of a variable


passed to it.

• Helps to dynamically allocate memory when the exact amount of


memory required is not known in the beginning.

7 Department of CSE
Referencing/ “Address of ” operator
• To make a pointer point to another variable, it is necessary to obtain
the memory address of that variable.

• To get the memory address of a variable (its location in memory),


put the & sign in front of the variable name.

• & is called the address-of operator, because it returns the memory


address. It‟s a unary operator.

• It is also known as Referencing operator as it refers/points to


another variable of same data type.

8 Department of CSE
Dereferencing/Indirection Operator
• It‟s a unary operator - *

• „*‟ is followed by the pointer name, say p ; i.e.; *p.

• It looks at the address stored in p, and goes to that address and


returns the value.

• This is akin to looking inside a safety deposit box only to find the
number of (and, presumably, the key to ) another box, which you
then open.

9 Department of CSE
Referencing & Dereferencing Operators

10 Department of CSE
Sample Code -1 : Simple Pointer
#include<stdio.h> Output:-
int main()
{ Number : 10
int x=10;
int *ip;
Address: 0x7fff4fab3044
ip=&x; Number using pointer : 10
printf("Number : %d\n",x);
printf("Address: %p\n",(&x)); Address using Pointer: 0x7fff4fab3044
printf("Number using pointer : %d\n", *ip);
printf("Address using Pointer: %p\n",ip);
return 0;
}

11 Department of CSE
Sample Code -2 : Pointers to different types
#include<stdio.h> Output:-
int main()
{ Number using pointer : 10
int x=10;
int *ip;
Address using Pointer: 0x7fff4f5c31bc
float y=2.5, *fp; Decimal value : 2.500000
fp = &y;
ip=&x; Address of y : 0x7fff4f5c31b8
printf("Number using pointer : %d\n", *ip);
printf("Address using Pointer: %p\n",ip);
printf("Decimal value : %f\n",*fp);
printf("Address of y : %p\n",fp);
return 0;
}

12 Department of CSE
Sample Code -3 : Same pointer to multiple variables
#include<stdio.h> Output:-
int main()
{ Enter three integers : 10 20 30
int a,b,c,*p; //a,b and c are variables and p is a
pointer pointer points to a. Value is 10
printf("Enter three integers : "); pointer points to b. Value is 20
scanf("%d %d %d",&a,&b,&c);
p = &a; pointer points to c. Value is 30
printf("pointer points to a. Value is %d\n",*p);
p = &b;
printf("pointer points to b. Value is %d\n",*p);
p = &c;
printf("pointer points to c. Value is %d\n",*p);
return 0;
}

13 Department of CSE
Sample Code -4 : Multiple Pointers to same variable
#include<stdio.h> Output:-
int main()
{ Enter an integer : 15
int a;
int *p = &a; 15
int *q = &a; 15
int *r = &a;
15
printf("Enter an integer : ");
scanf("%d",&a);
printf("%d\n",*p);
printf("%d\n",*q);
printf("%d\n",*r);

return 0;
}

14 Department of CSE
Pointer and 1D Array

15 Department of CSE
Relationship between array and pointer
• The name of array is a pointer to the first element

• Address of first element and name of array represent the same memory address.

• Array name can be used as a pointer.

• When a separate pointer is used to point to an array, it is initialized using the


following syntax:-
datatype *ptrname = array_name;

Eg:- int a[5] = {1,2,3,4,5};


int *ptr = a; //Equivalent to writing int *ptr = &a[0];

16 Department of CSE
Sample Program 5 : Pointer and Array I
Output:-
#include<stdio.h>
int main() 0x7fff03b2d380 0x7fff03b2d380
{ 11
int a[5] = {1,2,3,4,5};
int *p = a;

printf("%p %p\n",&a[0],a);
printf("%d %d\n",*a,*p);

return 0;
}

17 Department of CSE
Sample Program 6 : Pointer and Array II
#include<stdio.h>
Output:-
int main()
First element : 1 1
{
int a[5] = {1,2,3,4,5}; Second element: 2 2
int *p = &a[1];

printf("First element : %d %d\n",a[0],p[-1]);


printf("Second element:%d %d\n",a[1],p[0]);

return 0;
}
Note:-When a pointer to an array is not pointing to the first
element, index can be negative.
18 Department of CSE
Pointer Arithmetic and 1D Arrays
• If „a‟ is an array name, then „a‟ points to first element
• a+1 points to the second element, a+2 points to third element and
so on.
• Generally (a+n) points to (n+1)th element.

• Similarly, for a pointer p, p±n points to a location which is n elements


away from current location.
• Actual address will be p+n*(size of one element).

19 Department of CSE
Pointer arithmetic on different data types
• Size of single element varies with respect
to data type of array.

• „char‟ takes one byte per character stored,


whereas „int‟ and „float‟ takes 4 bytes per
value stored.

• Hence adding 1 to array name points to


different addresses for different data types

20 Department of CSE
Modifying values using pointers

21 Department of CSE
Modifying value using pointer
• If ip points to an integer x, *ip can be used in places where x could
have been used.

• *ip = *ip + 10; will modify the value of x by 10

• y = *ip + 1; is equivalent to y = x+1;

• *ip += 1 can be written as ++(*ip) or (*ip)++

22 Department of CSE
Sample Code –7: Updating value using Pointer
#include<stdio.h>
int main() Output:-
{
Number using pointer : 10
int x=10;
int *ip; Address using Pointer:
float y=2.5, *fp; 0x7fff76d4f8ec
fp = &y;
ip=&x; Decimal value : 2.500000
printf("Number using pointer : %d\n", *ip); Address of y : 0x7fff76d4f8e8
printf("Address using Pointer: %p\n",ip);
printf("Decimal value : %f\n",*fp);
Updated Number : 11
printf("Address of y : %p\n",fp); Updated Number : 55
x+=1;
printf("Updated Number : %d\n", *ip);
Updated Number : 56
*ip *=5;
printf("Updated Number : %d\n", *ip);
++*ip;
printf("Updated Number : %d\n", *ip);
return 0;
}
23 Department of CSE
Sample Code -8 : Adding two numbers using Pointers
#include<stdio.h>
int main()
Output:-
{ 10 + 5 = 15
int a=10,b=5,c;
int *p1 = &a;
int *p2 = &b;
int *res = &c;

*res = *p1 + *p2;

printf("%d + %d = %d\n",*p1,*p2,c);

return 0;
}

24 Department of CSE
Pointer to array : Order of placing „*‟ and „++‟
• Assume that z is an inger array with two values 1 and 2 (int z[2]={1,2};)
• Let ip be a pointer to z; (int *ip = z;)

• printf("%d\n", ++*ip);
• increments content in the address pointed by ip.
• z[0]=1 was taken and incremented by 1.
• In output the value is 2

• printf("%d\n", *++ip);
• increments the address pointed by ip.
• ip currently points to z[1]=3
• In output the value is 3

• Order of placing ‘++’ and ‘*’ is crucial


• ++ followed by *  Value is incremented.
• * followed by ++  Address is incremented.

25 Department of CSE
Sample Code Snippet - 9a – ++ before *
#include<stdio.h> • Sample Output
main()
{ 0x7fff0fc66d30
int z[2]={1,3};
int * ip = z; 1
printf("%p\n",ip);
printf("%d\n", *ip);
2
printf("%d\n", ++*ip); 0x7fff0fc66d30
printf("%p",ip);
return 0;
}

26 Department of CSE
Sample Code Snippet -9b : * before ++
#include<stdio.h> • Sample Output
main()
{ 0x7ffffc801740
int z[2]={1,3};
int * ip = z; 1
printf("%p\n",ip);
printf("%d\n", *ip);
3
printf("%d\n", *++ip); 0x7ffffc801744
printf("%p",ip);
return 0;
}

27 Department of CSE
Pointer Compatibility

28 Department of CSE
Pointer Compatibility
• Pointers have a type associated with them  They can point only
to specific type.

• Two types:-
• Pointer Size Compatibility
• Pointer Dereferencing compatibility

29 Department of CSE
Pointer Size Compatibility
• Size of all pointers is the same; i.e.; every pointer variable holds the
address of one memory location. But the size of variable that the
pointer points to can be different.

• Size of the type that a pointer points to is same as its data size.

• Size is dependent on type; not on the value.

30 Department of CSE
Sample Code -10 : Pointer Size Compatibility
#include<stdio.h> printf("Size of c : %3d | ",sizeofc);
int main() printf("Size of pc : %3d | ",sizeofpc);
{ printf("size of *pc : %3d\n",sizeofstarpc);
char c; printf("Size of a : %3d | ",sizeofa);
char* pc; printf("Size of pa : %3d | ",sizeofpa);
int sizeofc = sizeof(c); printf("size of *pa : %3d\n",sizeofstarpa);
int sizeofpc = sizeof(pc); printf("Size of d : %3d | ",sizeofd);
int sizeofstarpc = sizeof(*pc); printf("Size of pd : %3d | ",sizeofpd);
printf("size of *pd : %3d\n",sizeofstarpd);
int a; return 0;
int* pa; }
int sizeofa = sizeof(a);
int sizeofpa = sizeof(pa); Sample Output
int sizeofstarpa = sizeof(*pa);
Size of c : 1 | Size of pc : 8 | size of *pc : 1
double d;
Size of a : 4 | Size of pa : 8 | size of *pa : 4
double* pd;
int sizeofd = sizeof(d); Size of d : 8 | Size of pd : 8 | size of *pd : 8
int sizeofpd = sizeof(pd);
int sizeofstarpd = sizeof(*pd);
31 Department of CSE
Dereferencing Compatibility
• Dereference type is the type of variable that the pointer is
referencing.

• It is usually invalid to assign a pointer of one type to address of a


variable of another type.

• It is also invalid to assign a pointer of one type to pointer of another


type.

• Exception : pointer to void (Will be discussed later.)

32 Department of CSE
Sample Code 11: Pointer Dereferencing Incompatibility
#include<stdio.h>
ptrcompat.c: In function ‘main’:
int main()
{ ptrcompat.c:13: warning: assignment from
int x=10; incompatible pointer type
int *ip;
float y=2.5, *fp;
fp = &y; Output:-
ip=&x;
printf("Number using pointer : %d\n", *ip); Number using pointer : 10
printf("Address using Pointer: %p\n",ip);
printf("Decimal value : %f\n",*fp);
Address using Pointer: 0x7fffda19b6ec
printf("Address of y : %p\n",fp); Decimal value : 2.500000
fp = &x;
printf("New value pointed by fp = %f\n",*fp); Address of y : 0x7fffda19b6e8
return 0; New value pointed by fp = 0.000000
}

33 Department of CSE
Pointers and Functions

34 Department of CSE
How to swap two numbers using function?
#include<stdio.h>
int main() Output:-
{ Enter first number : 5
int a,b;
Enter second number: 10
void swap(int ,int );
Numbers before function call: 5 10
printf("Enter first number : " );
scanf("%d",&a); Numbers before swapping : 5 10
printf("Enter second number: "); Numbers after swapping : 10 5
scanf("%d",&b); Numbers after function call : 5 10
printf("Numbers before function call: %d\t%d\n",a,b);
swap(a,b);
printf("Numbers after function call : %d\t%d\n",a,b);
return 0;
} void swap(int a, int b)
{
int t;
printf("Numbers before swapping : %d\t%d\n",a,b);
t = a;
a = b;
b = t;
printf("Numbers after swapping : %d\t%d\n",a,b);
35 Department of CSE }
How to swap two numbers using function?
• Values are getting interchanged inside the function. But that is not
getting reflected in main.

• Call-by-value will not interchange numbers.

• If you want to modify the actual parameters, you require „Call-by-


Reference‟.

• This type of function requires pointers.

36 Department of CSE
How to swap two numbers using function?
#include<stdio.h>
int main() Output:-
{ Enter first number : 5
int a,b;
Enter second number: 10
void swap(int *,int *);
Numbers before function call: 5 10
printf("Enter first number : " );
scanf("%d",&a); Numbers before swapping : 5 10
printf("Enter second number: "); Numbers after swapping : 10 5
scanf("%d",&b); Numbers after function call : 10 5
printf("Numbers before function call: %d\t%d\n",a,b);
swap(&a,&b);
printf("Numbers after function call : %d\t%d\n",a,b);
return 0;
} void swap(int *a, int *b)
{
int t;
printf("Numbers before swapping : %d\t%d\n",*a,*b);
t = *a;
*a = *b;
*b = t;
printf("Numbers after swapping : %d\t%d\n",*a,*b);
37 Department of CSE }
Points to be noted while using Call-by-Reference
Call-by-Value Call-by-Reference
Function Declaration void swap(int ,int ); void swap(int *,int *);
Function Header void swap(int a, int b) void swap(int *a, int *b)
Function Call swap(a,b); swap(&a,&b);

• Requires „*‟ operator along with data type of arguments – in


declaration as well as Function header.
• Requires „&‟ along with actual arguments in Function call.
• Requires „*‟ operator inside function body.

38 Department of CSE
When do you need pointers in functions?
• First scenario – In Call-by-Reference.
• There is a requirement to modify the values of actual arguments.

• Second scenario – While passing array as an argument to a function.

• Third Scenario - If you need to return multiple values from a


function.

39 Department of CSE
Passing array as an argument to a function
• When an array is passed as an argument to a function, it is actually
passed as reference.

• If any modification of array elements is done inside the function, it


actually changes the original value stored in the array.

• Since modifications affect actual values, array need not be returned


from the function.

40 Department of CSE
Sample Code 12 : Passing an array to a function
#include<stdio.h>
int main() void square(int *a,int n)
{ {
int a[5]={1,2,3,4,5}; int i;
int i; for(i=0;i<n;i++)
//First argumnt is an array and second argument is its size a[i] *= a[i];
void square(int *,int); }
printf("Array before modification:-\n");
for(i=0;i<5;i++)
printf("%d\t",a[i]);
square(a,5);
printf("\nArray after modification:-\n");
for(i=0;i<5;i++) Output:-
printf("%d\t",a[i]); Array before modification:-
printf("\n");
return 0;
1 2 3 4 5
} Array after modification:-
1 4 9 16 25

41 Department of CSE
Returning Multiple values from a function
• Normally, a function can return only a single value from it, using
„return‟.

• What if, you have to return two or more values from a function?

• You can make use of pointers to return multiple values.


• Use one or more additional pointer variables as arguments

42 Department of CSE
Sample Code 13 : Returning Multiple Values
#include<stdio.h> void MinMax(int *a, int n, int *min,int *max)
int main() {
{ int i;
int a[5]; *min = *max = a[0];
void MinMax(int *,int,int*,int*); for(i=1;i<n;i++)
int i,min,max; {
for(i=0;i<5;i++) if(a[i] < (*min))
{ *min = a[i];
printf("Number %d : ",(i+1)); }
scanf("%d",&a[i]); for(i=1;i<n;i++)
} {
MinMax(a,5,&min,&max); if(a[i] > (*max))
printf("Minimum element entered : %d\n",min); *max = a[i];
printf("Maximum element entered : %d\n",max); }
return 0; }
}

43 Department of CSE
Sample Code 13 : Returning Multiple Values - Output

Output:-
Number 1 : 2
Number 2 : 1
Number 3 : 3
Number 4 : 5
Number 5 : 4
Minimum element entered : 1
Maximum element entered : 5

44 Department of CSE
Special Pointers

45 Department of CSE
Void Pointer
• A generic type that is not associated with a reference type.
• It is not the address of a particular data type.
• A pointer with no reference type that can store only address of any
variable.
• Compatible for assignment purposes only with all other types of
pointers.
• A pointer of any reference can be assigned to void type and vice
verse.
• Restriction : It can not be dereferenced unless it is cast.
• Declaration:- void* pvoid;
• General Casting:- dest_ptr = (dest_ptr_type *) source_ptr_name;

46 Department of CSE
NULL Pointer
• A pointer of any type that is assigned the constant NULL
• The reference type of pointer will not change by the assignment of
NULL
• Eg:-
int* iptr = NULL; //NULL pointer of type „int‟
Char* cptr = NULL; //NULL pointer of type „char‟

47 Department of CSE
Dangling Pointer
• Arises during object destruction, when an object that has an incoming reference
is deleted or deallocated, without modifying the value of the pointer, so that the
pointer still points to the memory location of the deallocated memory.
• Example of creating Dangling pointer
int main()
{
char *ptr=NULL;
{
char c;
ptr = &c;
}
}

• c falls out of scope after the inner block making ptr a dangling pointer

48 Department of CSE
Constant pointer
• A pointer that cannot change the address its holding.
• Once a constant pointer points to a variable then it cannot point to any other variable.
• Declaration:- <type of pointer> * const <name of pointer>
• Example:- int* const ptr;
• Sample Code : Will give the error 7: error: assignment of read-only variable „ptr‟

#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 0;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}

49 Department of CSE
Pointer to a Pointer
• A pointer points to an address of another pointer.
• Also called Double Pointer.
• Declaration:- type **ptr_name;
• Example:- int **p;
• Sample:-
int main()
{
int p=5;
int *p1 = &p;
int **pp;
pp = &p1;
printf(“Value of P : %d\n”,**pp);
return 0;
}
Output : Value of P : 5
50 Department of CSE
Summary
• Discussed about Pointer and its importance.
• Discussed relationship between array and pointer
• Discussed about Call-by-Reference and other places where pointers
are needed for functions.
• Discussed special pointers.

51 Department of CSE
References
• Books/Materials
1. C Programming Course – Compiled HTML Help File
2. Brian W Kernighan, Dennis M Ritchie, “The C Programming
Language”, 2nd Edition, PHI
• Web
1. [Link]
2. [Link]

52 Department of CSE
2.3 DYNAMIC MEMORY
ALLOCATION

1 Department of CSE
Objectives
• Learn how to allocate and free memory, and to control dynamic
arrays of any type of data in general and structures in particular.

• Practice and train with dynamic memory in the world of work


oriented applications.
• To know about the pointer arithmetic
• How to create and use array of pointers.

2 Department of CSE
Agenda
• Dynamic memory allocation
• Malloc
• Calloc
• Realloc
• free
• Pointer Arithmetic
• Array of pointers

3 Department of CSE
Introduction
• While doing programming, if you are aware about the size of an
array, then it is easy and you can define it as an array.
• For example to store a name of any person, it can go max 100
characters so you can define something as follows:
• char name[100]
• But now let us consider a situation where you have no idea about
the length of the text you need to store, for example you want to
store a detailed description about a topic. Here we need to define
a pointer to character without defining how much memory is
required and later based on requirement we can allocate memory .

4 Department of CSE
Memory Allocation Function

5 Department of CSE
Difference between Static and Dynamic
memory allocation

Static memory Dynamic memory


[Link]
allocation allocation
In static memory allocation, memory
is allocated while writing the C In dynamic memory allocation, memory
1 program. Actually, user requested is allocated while executing the program.
memory will be allocated at compile That means at run time.
time.
Memory size can’t be modified while Memory size can be modified while
execution. execution.
2
Example: array Example: Linked list

6 Department of CSE
Introduction
• Creating and maintaining dynamic structures requires dynamic
memory allocation— the ability for a program to obtain more
memory space at execution time to hold new values, and to release space no
longer needed.

7 Department of CSE
Memory Allocation Functions

8 Department of CSE
Syntax
• The following are the function used for dynamic memory allocation
• void *malloc(int num);
• This function allocates an array of num bytes and leave them
uninitialized.
• void *calloc(int num, int size);
• This function allocates an array of num elements each of which
size in bytes will be size.
• void *realloc(void *address, int newsize);
• This function re-allocates memory extending it upto newsize.
• void free(void *address);
• This function releases a block of memory block specified by
address.
9 Department of CSE
Block Memory Allocation (malloc)
• Malloc function allocates a block of memory that contains the
number of bytes specified in its parameter.
• It returns a void pointer to the first byte of the allocated memory
• The allocated memory is not initialized . We should therefore assume
that it will contain unknown values and initialize it as required by our
program.
• The function declaration is as follows
• void* malloc (size_t size)
• If it is not successful malloc return NULL pointer.
• An attempt to allocate memory from heap when memory is
insufficient is known as overflow.

10 Department of CSE
malloc
• It is up to the program to check the memory overflow
• If it doesn't the program produces invalid results or aborts with
an invalid address the first time the pointer is used.

11 Department of CSE
malloc
• Malloc function has one more potential error.
• If we call malloc function with zero size , the results are
unpredictable.
• It may return a NULL pointer
• Never call malloc with a zero size!!!!!

12 Department of CSE
Contiguous Memory Allocation (calloc)
• Calloc is primarily used to allocate memory for arrays.
• It differs from malloc only in that it sets memory to null characters.
• void *calloc (size_t element-count, size_t element-size)

13 Department of CSE
Reallocation of memory(realloc)
• The realloc function can be highly inefficient and should be used
advisedly.
• When given a pointer to the previously allocated block of memory,
realloc changes the size of the block by deleting or extending the
memory at the end of the block.
• If memory cannot be extended because of other allocations, realloc
allocates a completely new block and copies the existing memory
allocation to new allocation, and deletes the old allocation.
• void *realloc (void* ptr, size_t newSize)

14 Department of CSE
realloc

15 Department of CSE
Releasing Memory (free)
• When memory locations allocated by malloc, calloc or realloc are no
longer needed, they should be freed using the predefined function
free.
• void free(void* ptr)
• Below shows the example where first one releases a
single element allocated with malloc
• Second example shows 200 elements were allocated
with calloc . When free the pointer 200 elements are
returned to the heap.

16 Department of CSE
free

17 Department of CSE
Difference between malloc and calloc
[Link] malloc() calloc()
It allocates only single block of requested
1 It allocates multiple blocks of requested memory
memory

int *ptr;ptr = malloc( 20 * sizeof(int) );For int *ptr;Ptr = calloc( 20, 20 * sizeof(int) );For
the above, 20*4 bytes of memory only the above, 20 blocks of memory will be created
2 allocated in one block. and each contains 20*4 bytes of memory.

Total = 80 bytes Total = 1600 bytes

malloc () doesn’t initializes the allocated


3 calloc () initializes the allocated memory to zero
memory. It contains garbage values
type cast must be done since this function
Same as malloc () function int *ptr;ptr =
4 returns void pointer int *ptr;ptr =
(int*)calloc( 20, 20 * sizeof(int) );
(int*)malloc(sizeof(int)*20 );
18 Department of CSE
Resizing and Releasing Memory
• When your program comes out, operating system automatically
release all the memory allocated by your program but as a good
practice when you are not in need of memory anymore then you
should release that memory by calling the function free().

• Alternatively, you can increase or decrease the size of an allocated


memory block by calling the function realloc().

19 Department of CSE
Example-1
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
} Enter number of elements: 3
printf("Sum=%d",sum);
Enter elements of array: 2 7 1
free(ptr);
return 0; Sum=10
}

20 Department of CSE Dynamic-ex1.c


Example - 2
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{ Enter number of elements: 3
scanf("%d",ptr+i);
Enter elements of array: 2 1 3
sum+=*(ptr+i);
} Sum=6
printf("Sum=%d",sum);
free(ptr);
return 0;
}

21 Department of CSE Dynamic-ex2.c


Example - 3
#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i); Enter size of array: 3
printf("\nEnter new size of array: "); Address of previously allocated memory: 7474944
scanf("%d",&n2); 7474948 7474952
ptr=realloc(ptr,n2); Enter new size of array: 5
for(i=0;i<n2;++i) 7474944 7474948 7474952 7474956 7474960
printf("%u\t",ptr+i);
return 0;
}

22 Department of CSE Dynamic-ex3.c


Example - 4
#include <stdio.h> Name = Zara Ali
#include <string.h> Description: Zara ali a DPS student in class 10th
int main()
{
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 200 * sizeof(char) );
if( description == NULL )
{
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else
{
strcpy( description, "Zara ali a DPS student in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
}
23 Department of CSE Dynamic-ex4.c
Example - 5
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char name[100];
char *description;
strcpy(name, "Zara Ali");
/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
if( description == NULL )
{
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else
{
strcpy( description, "Zara ali a DPS student.");
24 Department of CSE
}
Example – 5 Cont---
/* suppose you want to store bigger description */
description = realloc( description, 100 * sizeof(char) );
if( description == NULL )
{
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else
{
strcat( description, "She is in class 10th");
}
printf("Name = %s\n", name );
printf("Description: %s\n", description );
/* release memory using free() function */
free(description);
Name = Zara Ali
} Description: Zara ali a DPS [Link] is in class 10th

25 Department of CSE
Dynamic-ex5.c
Memory Leaks
• A memory leak occurs when allocated memory is never used again
but is not freed.
• I can happen when
• The memory’s address is lost
• The free function is never invoked though it should be
• The problem with memory leak is that the memory cannot be
reclaimed and use later. The amount of memory available t the heap
manager will be decreased.
• If the memory is repeatedly allocated and then lost, then the
program may terminate when more memory is needed but malloc
cannot allocate it because it ran out of memory.

26 Department of CSE
Example
char *chunk;
while(10
{
chunk=(char*) malloc (1000000);
printf(“allocating\n”);
}
• The variable chunk is assigned memory from heap. However this
memory is not freed before another block of memory is assigned to
it.
• Eventfully the application will run out of memory and terminate
abnormally.

27 Department of CSE
POINTER ARITHMETIC

28 Department of CSE
Pointer Arithmetic
• This section introduces the concept of pointer arithmetic, and this
will form one of the very important building blocks in understanding
the functionality of pointers.

29 Department of CSE
Pointer Expressions and Pointer Arithmetic
• Arithmetic operations can be performed on pointers
• Increment/decrement pointer (++ or --)
• Add an integer to a pointer( + or += , - or -=)
• Pointers may be subtracted from each other
• All these operations meaningless unless performed on an array

• NOTE: Division and Multiplication are not allowed.


Pointer Arithmetic
• int a,b,*p,*q
• p=-q /* illegal use of pointers*/
• p<<=1 /* illegal use of pointers*/
• p=p-b /*valid*/
• p=p-q /* nonportable pointer conversion*/
• p=(int*) p-q /*valid*/
• p=p-q-a /*valid*/
• p=p+a /*valid*/
• p=p+q /* invalid pointer addition*/
• p=p*q /* illegal use of pointers*/
• p=p/q /* illegal use of pointers*/
• p=p/a /* illegal use of pointers*/

31 Department of CSE
Pointer Increment – Example - 1
#include<stdio.h>
void main()
{
int n;
int *pn; 2686788 2686792
pn=&n; 2686768 2686776
int *pn1;
pn1=pn+1;
printf("%d %d\n", pn,pn1);

double d;
double *pd;
pd=&d;
double *pd1;
pd1=pd+1;
printf("%d %d\n", pd,pd1);
}
32 Department of CSE
Arithmetic-ex1.c
Incrementing Pointer :
• Incrementing Pointer is generally used in array because we have contiguous
memory in array and we know the contents of next memory location.
• Incrementing Pointer Variable Depends Upon data type of the Pointer variable

33 Department of CSE
Example – 2
#include<stdio.h>
int main()
{
int *ptr=(int *)1000;
printf(“Old Value of ptr : %u",ptr);
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
} Old Value of ptr : 1000
New Value of ptr : 1004

34 Department of CSE
Arithmetic-ex2.c
Difference between two integer Pointers –
Example - 3
#include<stdio.h>

int main(){

float *ptr1=(float *)1000;


float *ptr2=(float *)2000;

printf("\nDifference : %d\n",ptr2-ptr1);

return 0; Difference : 250


}

35 Department of CSE
Arithmetic-ex3.c
Explanation
• Ptr1 and Ptr2 are two pointers which holds memory address of Float
Variable.
• Ptr2-Ptr1 will gives us number of floating point numbers that can be
stored.
• ptr2 - ptr1 = (2000 - 1000) / sizeof(float)
• = 1000 / 4

36 Department of CSE
Pointer Division – Example - 4
#include<stdio.h>
int main()
{
int *ptr1,*ptr2;
ptr1 = (int *)1000;
ptr2 = ptr1/4;
return(0);
}
Illegal Use of operator : INVALID

37 Department of CSE
Arithmetic-ex4.c
Pointer Expressions and Pointer Arithmetic-Arrays
• 5 element int array on machine with 4 byte ints
• vPtr points to first element v[ 0 ]
• at location 3000 (vPtr = 3000)
• vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] (incremented by 2), but the machine has
4 byte ints, so it points to address 3008

Array v and a pointer variable vPtr that points to v.


The pointer vPtr after pointer arithmetic
Pointer Expressions and Pointer Arithmetic
• Subtracting pointers
• Returns number of elements from one to the other. If
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
• vPtr2 - vPtr would produce 2
• Pointer comparison ( <, == , > )
• See which pointer points to the higher numbered array element
• Also, see if a pointer points to 0
The Relationship Between Pointers and Arrays
• Arrays and pointers closely related
• Array name like a constant pointer
• Pointers can do array subscripting operations
• Define an array b[ 5 ] and a pointer bPtr
• To set them equal to one another use:
bPtr = b;
• The array name (b) is actually the address of first element of the
array b[ 5 ]
bPtr = &b[ 0 ]
• Explicitly assigns bPtr to address of first element of b
The Relationship Between Pointers and Arrays
• Element b[ 3 ]
• Can be accessed by *( bPtr + 3 )
• Where n is the offset. Called pointer/offset notation
• Can be accessed by bptr[ 3 ]
• Called pointer/subscript notation
• bPtr[ 3 ] same as b[ 3 ]

• Can be accessed by performing pointer arithmetic on the array


itself
*( b + 3 )
Example - 5
1
2 Using subscripting and pointer notations with arrays */
3
4 #include <stdio.h>
5
6 int main( void )
7 {
8 int b[] = { 10, 20, 30, 40 }; /* initialize array b */
9 int *bPtr = b; /* set bPtr to point to array b */
10 int i; /* counter */
11 int offset; /* counter */
12
13 /* output array b using array subscript notation */
14 printf( "Array b printed with:\nArray subscript notation\n" );
15 Array subscript notation
16 /* loop through array b */
17 for ( i = 0; i < 4; i++ ) {
18 printf( "b[ %d ] = %d\n", i, b[ i ] );
19 } /* end for */
20
21 /* output array b using array name and pointer/offset notation */
22 printf( "\nPointer/offset notation where\n"
23 "the pointer is the array name\n" ); Pointer/offset notation
24
25 /* loop through array b */
26 for ( offset = 0; offset < 4; offset++ ) {
27 printf( "*( b + %d ) = %d\n", offset, *( b + offset ) );
28 } /* end for */
29
30 /* output array b using bPtr and array subscript notation */
31 printf( "\nPointer subscript notation\n" );
32 Pointer subscript notation
33 /* loop through array b */
34 for ( i = 0; i < 4; i++ ) {
35 printf( "bPtr[ %d ] = %d\n", i, bPtr[ i ] );
36 } /* end for */
37
38 /* output array b using bPtr and pointer/offset notation */
39 printf( "\nPointer/offset notation\n" ); Pointer offset notation
40
41 /* loop through array b */
42 for ( offset = 0; offset < 4; offset++ ) {
43 printf( "*( bPtr + %d ) = %d\n", offset, *( bPtr + offset ) );
44 } /* end for */
45
46 return 0; /* indicates successful termination */
47
48 } /* end main */

Array b printed with:


Array subscript notation
Arithmetic-ex5.c
b[ 0 ] = 10
b[ 1 ] = 20
b[ 2 ] = 30
b[ 3 ] = 40
(continued on next slide… )
(continued from previous slide…)
Pointer/offset notation where
the pointer is the array name
*( b + 0 ) = 10
*( b + 1 ) = 20
*( b + 2 ) = 30
*( b + 3 ) = 40

Pointer subscript notation


bPtr[ 0 ] = 10
bPtr[ 1 ] = 20
bPtr[ 2 ] = 30
bPtr[ 3 ] = 40

Pointer/offset notation
*( bPtr + 0 ) = 10
*( bPtr + 1 ) = 20
*( bPtr + 2 ) = 30
*( bPtr + 3 ) = 40
1
2 Copying a string using array notation and pointer notation. */
3 #include <stdio.h>
4
5 void copy1( char * const s1, const char * const s2 ); /* prototype */
6 void copy2( char *s1, const char *s2 ); /* prototype */
7
8 int main( void )
9 {
10 char string1[ 10 ]; /* create array string1 */
11 char *string2 = "Hello"; /* create a pointer to a string */
12 char string3[ 10 ]; /* create array string3 */
13 char string4[] = "Good Bye"; /* create a pointer to a string */
14
15 copy1( string1, string2 );
16 printf( "string1 = %s\n", string1 );
17
18 copy2( string3, string4 );
19 printf( "string3 = %s\n", string3 );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */
24
25 /* copy s2 to s1 using array notation */
26 void copy1( char * const s1, const char * const s2 )
27 {
28 int i; /* counter */
29
30 /* loop through strings */
31 for ( i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ ) {
32 ; /* do nothing in body */
33 } /* end for */
34
35 } /* end function copy1 */
36 Condition of for loop
37 /* copy s2 to s1 using pointer actually performs an action
notation */
38 void copy2( char *s1, const char *s2 )
39 {
40 /* loop through strings */
41 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ ) {
42 ; /* do nothing in body */
43 } /* end for */
44
45 } /* end function copy2 */

string1 = Hello
string3 = Good Bye
ARRAY OF POINTERS

48 Department of CSE
Introduction
• An array of pointer is similar to an array of ant predefined data type
• As a pointer variable always contain an address, an array of pointer is
a collection of addresses.
• These can be address of ordinary isolated variable or of array
elements.
• The elements of an array of pointers are stored in the memory just
like elements of any other kind of array.
• Example is given below..
Arraypointer-ex1.c
Example - 1
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX]; //array of pointers
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0; Value of var[0] = 10
Value of var[1] = 100
} Value of var[2] = 200
Example - 2
#include<stdio.h>
void main()
{
int arr[3]={1,2,3};
int i, *ptr[3];
for(i=0;i<3;i++)
0028FF30 1
ptr[i]=arr+i; 0028FF34 2
for(i=0;i<3;i++) 0028FF38 3

printf("%p %d\n", ptr[i],*ptr[i]);


}

51
Arraypointer-ex2.c
Department of CSE
Arrays of Pointers - Strings
• Arrays can contain pointers
• For example: an array of strings
char *suit[ 4 ] = { "Hearts", "Diamonds",
"Clubs", "Spades" };
• Strings are pointers to the first character
• char * – each element of suit is a pointer to a char
• The strings are not actually stored in the array suit, only pointers to
the strings are stored

• suit array has a fixed size, but strings can be of any size
Case study: Roman numeral equivalents – Example
-3
#include <stdio.h>

void main( void ) {


int decimal_number = 101, a = 0, b = 0;
const char *x[11] = {"", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc", "c"};
const char *y[10] = {"", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"};

while ((decimal_number > 100) || (decimal_number < 0)) {


printf("Enter the decimal numbers in the range 1 to 100:\n");
scanf("%d", &decimal_number);
}
Enter the decimal numbers in the range 1 to 100:
a = decimal_number/10; 15
The equivalent roman is xv
b = decimal_number%10;

printf("The equivalent roman is %s%s\n", x[a], y[b]);


}
Arraypointer-ex3.c
Review
• Dynamic Memory allocation
• Pointer Arithmetic
• Array of pointers
Try it Yourself
• Write a program using dynamic memory allocation to get a student’s mark and
display it back.
• Write a program to do the following
The process for finding a prime is quite simple. First, you know by inspection that 2,
3, and 5 are the first three prime numbers, because they aren’t divisible by
anything other than 1 and themselves. Because all the other prime numbers must
be odd (otherwise they would be divisible by 2), you can work out the next
number to check by starting at the last prime you have and adding 2. When
you’ve checked out that number, you add another 2 to get the next to be
checked, and so on. to check whether a number is actually prime rather than just
odd, you could divide by all the odd numbers less than the number that you’re
checking, but you don’t need to do as much work as that. if a number is not prime,
it must be divisible by one of the primes lower than the number you’re checking.
Because you’ll obtain the primes in sequence, it will be sufficient to check a
candidate by testing whether any of the primes you’ve already found is an exact
divisor. Store all primes in an array using pointers and pointer arithmetic.
55 Department of CSE
Try it Yourself
• Find Largest Element Using Dynamic Memory Allocation and
pointer arithmetic to access the array
• Write a C program to find the sum of two 1D matrices using
dynamic memory and pointer arithmetic.

56 Department of CSE
Try it Yourself –Ans - Student mark
#include<stdio.h>
#include<stdlib.h>
void main()
{
int no, *pt,i;
clrscr();

printf("Enter no of Students :");


scanf("%d",&no);
pt=(int *)malloc(no*2);
if(pt== NULL)
{
printf("\n\nMemory allocation failed!");
exit(0);
}

57 Department of CSE
Student mark
printf("* * * * Enter roll no of students. * * * *\n");
for (i=0;i<no;i++)
{
printf("-->");
scanf("%d",(pt+i));
}

printf("\n* * * * Entered roll no. * * * *\n");


for (i=0;i<no;i++)
{
printf("%d, ",*(pt+i));
}
}

58 Department of CSE
Structures and Unions
Structure
A structure is a user defined data type. We know that arrays can be used to
represent a group of data items that belong to the same type, such as int or float. However
we cannot use an array if we want to represent a collection of data items of different types
using a single name. A structure is a convenient tool for handling a group of logically related
data items.
Structure is a user defined data type used to represent a group of data items of
different types using a single name.

The syntax of structure declaration is


struct structure_name
{
type element 1;
type element 2;
……………..
type element n;
};
In structure declaration the keyword struct appears first, this followed by structure
name. The member of structure should be enclosed between a pair of braces and it defines
one by one each ending with a semicolon. It can also be array of structure. There is an
enclosing brace at the end of declaration and it end with a semicolon.

We can declare structure variables as follows


struct structure_name var1,var2,…..,var n;
Example:
To store the names, roll number and total mark of a student you can declare 3
variables. To store this data for more than one student 3 separate arrays may be declared.
Another choice is to make a structure. No memory is allocated when a structure is declared.
It just defines the “form” of the structure. When a variable is made then memory is
allocated. This is equivalent to saying that there's no memory for “int”, but when we declare
an integer that is int var; only then memory is allocated. The structure for the above-
mentioned case will look like

struct student
{
int rollno;
char name[25];
float totalmark;
};

We can now declare structure variables stud1, stud2 as follows


struct student stud1,stud2;

SSASGFGC@Hospet Page 1
Structures and Unions
Thus, the stud1 and stud2 are structure variables of type student. The above
structure can hold information of 2 students.

It is possible to combine the declaration of structure combination with that of the


structure variables, as shown below.

struct structure_name
{
type element 1;
type element 2;
……………..
type element n;
} var1,var2,…,varn;

The following single declaration is equivalent to the two declaration presented in the
previous example.

struct student
{
int rollno;
char name[25];
float totalmark;
} stud1, stud2;

Accessing structure Variable


The different variable types stored in a structure are called its members. The
structure member can be accessed by using a dot (.) operator, so the dot operator is known
as structure member operator.

Example:
In the above example stud1 is a structure variable of type student. To access the
member name, we would write [Link]. Similarly, stud1’s rollno and stud1’s totalmark
can be accessed by writing [Link] and [Link] respectively.

Initializing Structure Members


Structure members can be initialized at declaration. This much the same manner as
the element of an array; the initial value must appear in the order in which they will be
assigned to their corresponding structure members, enclosed in braces and separated by
commas.
The general form is
struct structure_name var={val1,val2,val3…..};
Example:
#include <stdio.h>

SSASGFGC@Hospet Page 2
Structures and Unions
#include<conio.h>
void main()
{
struct student
{
char *name;
int rollno;
float totalmark;
};
struct student stud1={"Venkat",1,98};
struct student stud3= {"Shweta",3,97};
struct student stud2={"Arpita",2,99};
clrscr();
printf(“STUDENTS DETAILS:\n”);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, [Link], [Link],
[Link]);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, [Link], [Link],
[Link]);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, [Link], [Link],
[Link]);
getch();
}

Output
STUDENTS DETAILS:
Roll number: 1
Name: Venkat
Total Marks:98.000000

Roll number: 2
Name: Arpita
Total Marks:99.000000

Roll number: 2
Name:Shweta
Total Marks:99.000000

Array of structures:
It is possible to store a structure has an array element. i.e., an array in which each
element is a structure. Just as arrays of any basic type of variable are allowed, so are arrays
of a given type of structure. Although a structure contains many different types, the
compiler never gets to know this information because it is hidden away inside a sealed
structure capsule, so it can believe that all the elements in the array have the same type,
even though that type is itself made up of lots of different types.

The declaration statement is given below.

SSASGFGC@Hospet Page 3
Structures and Unions
struct struct_name
{
type element 1;
type element 2;
……………..
type element n;
}array name[size];

Example:
struct student
{
int rollno;
char name[25];
float totalmark;
} stud[100];

In this declaration stud is a 100-element array of structures. Hence, each element of


stud is a separate structure of type student. An array of structure can be assigned initial
values just as any other array. So the above structure can hold information of 100 students.

Program to demonstrate use of array of structure


#include <stdio.h>
#include <conio.h>
void main()
{
struct student
{
int rollno;
char name[25];
int totalmark;
}stud[100];

int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of %d-th student\n",i+1);
printf("Name:\n");
scanf("%s",&stud[i].name);
printf("Roll number:\n");
scanf("%d",&stud[i].rollno);
printf("Total mark:\n");
scanf("%d",&stud[i].totalmark);
}

SSASGFGC@Hospet Page 4
Structures and Unions

printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Total mark:%d\n",stud[i].totalmark);
}
getch();
}

OUTPUT
Enter total number of students:
3

Enter details of 1-th student


Name:SUBAHAS
Roll number:11
Total mark:589

Enter details of 2-th student


Name:RUKSANA
Roll number:12
Total mark:594
Enter details of 3-th student
Name:SANA
Roll number:13
Total mark:595

STUDENTS DETAILS:
Roll number:11
Name: SUBAHAS
Total mark:589

Roll number:12
Name: RUKSANA
Total mark:594

Roll number:13
Name: SANA
Total mark:595

Structure as structure member (Embedded structure):


A structure inside another structure is called an embedded structure. A structure
can have one or more of its member as another structure, but a structure cannot be
member to itself when a structure is used as structure member. In such situation, the

SSASGFGC@Hospet Page 5
Structures and Unions
declaration of the embedded structure must appear before the declaration of the outer
structure. For example

#include <stdio.h>
#include <conio.h>
void main()
{
struct dob
{
int day;
int month;
int year;
};

struct student
{
struct dob d;
int rollno;
char name[25];
int totalmark;
}stud[25];

int n,i;
clrscr();
printf("Enter total number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter details of %d student",i+1);
printf("\nName:");
scanf("%s",&stud[i].name);
printf("\nRoll number:");
scanf("%d",&stud[i].rollno);
printf("\nTotal mark:");
scanf("%d",&stud[i].totalmark);
printf("\nDate of birth (Format:01 06 2010):");
scanf("%d%d%d",&stud[i].[Link],&stud[i].[Link],&stud[i].[Link]);
}
printf("\nSTUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{

SSASGFGC@Hospet Page 6
Structures and Unions
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Total mark:%d\n",stud[i].totalmark);
printf("Date of birth : %d / %d / %d \n\n",
stud[i].[Link],stud[i].[Link],stud[i].[Link]);
}
getch();
}

OUTPUT
Enter total number of students 2

Enter details of 1 student


Name: karthik
Roll number:12
Total mark:588
Date of birth (Format:01 06 2010):11 12 1997

Enter details of 2 student


Name: sarita
Roll number:18
Total mark:598
Date of birth (Format:01 06 2010):1 2 1997

STUDENTS DETAILS:
Roll number:12
Name: karthik
Total mark: 588
Date of birth : 11 / 12 / 1997

Roll number:18
Name: sarita
Total mark:598
Date of birth : 1 / 2 / 1997

Union
Union is a user created data type similar to structure but in this case all the members
share a common memory location. The size of the union corresponds to the length of the
largest member. Since the member share a common location they have the same starting
address.

SSASGFGC@Hospet Page 7
Structures and Unions
The real purpose of unions is to prevent memory fragmentation by arranging for a
standard size for data in the memory. By having a standard data size we can guarantee that
any hole left when dynamically allocated memory is freed will always be reusable by
another instance of the same type of union. This is a natural strategy in system
programming where many instances of different kinds of variables with a related purpose
and stored dynamically.
A union is declared in the same way as a structure. The syntax of union declaration is
union union_name
{
type element 1;
type element 2;
……………..
type element n;
};

This declares a type template. Variables are then declared as:


union union_name x,y,z;

For example, the following code declares a union data type called Student and a
union variable called stud:
union student
{
int rollno;
float totalmark;
};
union student stud;
It is possible to combine the declaration of union combination with that of the union
variables, as shown below.
union union_name
{
type element 1;
type element 2;
……………..
type element n;
}var1,var2,…,varn;

The following single declaration is equivalent to the two declaration presented in the
previous example.
union student
{
int rollno;
float totalmark;

SSASGFGC@Hospet Page 8
Structures and Unions
}x,y,z;

Exercise: Compare structure and Union

The difference between structure and union is,

Structure Union

The amount of memory required to store a The amount of memory required is always equal
structure variable is the sum of the size of all the to that required by its largest member.
members.

Each member have their own memory space. One block is used by all the member of the
union.

Keyword struct defines a structure Keyword union defines a union.


struct s_tag union u_tag
{ {
int ival; int ival;
float fval; float fval;
char *cptr; char *cptr;
}s; }u;

Within a structure all members gets memory While retrieving data from a union the type
allocated; therefore any member can be that is being retrieved must be the type most
retrieved at any time. recently stored. It is the programmer's
responsibility to keep track of which type is
currently stored in a union; the results are
implementation-dependent if something is
stored as one type and extracted as another.

One or more members of a structure can be A union may only be initialized with a value
initialized at once. of the type of its first member; thus union u
described above (during example
declaration) can only be initialized with an
integer value.

Structure:
#include<stdio.h>
#include<conio.h>
void main()
{
struct testing
{

SSASGFGC@Hospet Page 9
Structures and Unions
int a;
char b;
float c;
}var;
clrscr();
printf(“\nsizeof(var) is %d”,sizeof(var));
printf(“\nsizeof(var.a) is %d”,sizeof(var.a));
printf(“\nsizeof(var.b) is %d”,sizeof(var.b));
printf(“\nsizeof(var.c) is %d”,sizeof(var.c));
var.a=10;
printf(“\nvalue of var.a is %d”,var.a);
var.b=’b’;
printf(“\nvalue of var.b is %c”,var.b);
var.c=15.55;
printf(“\nvalue of var.c is %f”,var.c);
printf(“\nvalue of var.a is %d”,var.a);
printf(“\nvalue of var.b is %c”,var.b);
printf(“\nvalue of var.c is %f”,var.c);
getch();
}

OUTPUT
sizeof(var) is 7
sizeof(var.a) is 2
sizeof(var.b) is 1
sizeof(var.c) is 4
value of var.a is 10
value of var.b is b
value of var.c is 15.550000
value of var.a is 10
value of var.b is b
value of var.c is 15.550000

Union:
#include<stdio.h>
#include<conio.h>
void main()
{
union testing
{

SSASGFGC@Hospet Page 10
Structures and Unions
int a;
char b;
float c;
}var;
clrscr();
printf(“\nsizeof(var) is %d”,sizeof(var));
printf(“\nsizeof(var.a) is %d”,sizeof(var.a));
printf(“\nsizeof(var.b) is %d”,sizeof(var.b));
printf(“\nsizeof(var.c) is %d”,sizeof(var.c));
var.a=10;
printf(“\nvalue of var.a is %d”,var.a);
var.b=’b’;
printf(“\nvalue of var.b is %c”,var.b);
var.c=15.55;
printf(“\nvalue of var.a is %f”,var.c);
printf(“\nvalue of var.a is %d”,var.a);
printf(“\nvalue of var.b is %c”,var.b);
printf(“\nvalue of var.c is %f”,var.c);
getch();
}
OUTPUT
sizeof(var) is 4
sizeof(var.a) is 2
sizeof(var.b) is 1
sizeof(var.c) is 4
value of var.a is 10
value of var.b is b
value of var.c is 15.550000
value of var.a is -13458
value of var.b is
value of var.c is 15.550000

SSASGFGC@Hospet Page 11
File Handling in C Language

File Handling in C Language

What is file?

File is a collection of bytes that is stored on secondary storage devices like disk. There are two kinds
of files in a system. They are,

1. Text files (ASCII)


2. Binary files

 Text files contain ASCII codes of digits, alphabetic and symbols.


 Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of text
files.

Basic file operations in C programming:


There are 4 basic operations that can be performed on any files in C programming language. They
are,
1. Opening/Creating a file
2. Closing a file
3. Reading a file
4. Writing in a file

C provides a number of functions that helps to perform basic file operations. Following are the
functions,

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

1 Asst. Prof. P. M. Patil


File Handling in C Language

Opening a File or Creating a File

fopen() function is used to open a file to perform operations such as reading, writing etc. In
a C program, we declare a file pointer and use fopen() as below. fopen() function creates a new file
if the mentioned file name does not [Link] *fp;

General Syntax : *fp = FILE *fopen(const char *filename, const char *mode);

fp=fopen (“filename”, ”mode”);

Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+ and a+. Please refer
below the description for these mode of operations.

Closing a file

fclose() function closes the file that is being pointed by file pointer fp. In a C program, we close a file
as below.
General Syntax : int fclose(FILE *fp);
fclose (fp);

fprintf()

fprintf() function writes string into a file pointed by fp. In a C program, we write string into a file as
below.
General Syntax : int fprintf(FILE *fp, const char *format, …);

e.g. fprintf (fp, “some data”);

Mode of operations performed on a file

mode description
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

2 Asst. Prof. P. M. Patil


File Handling in C Language

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

Input/Output operation on File

// Program to write 5 names in File and read from file and display on screen.

#include<stdio.h>
#include<conio.h>

void main()
{
FILE *fp;
char name[30];
int i;
clrscr();

fp=fopen("[Link]","a+");
for(i=0;i<5;i++)
{
printf("\n\t Name :-");
scanf("%s",&name);
fprintf(fp,"%s",name);
fprintf(fp,"\n"," ");
}
fp=fopen("[Link]","r");

while(!feof(fp))
{
fscanf(fp,"%s",name);
printf("\n %s",name);
}
getch();
}
3 Asst. Prof. P. M. Patil
File Handling in C Language

Following program reads a character from user and write in to file [Link].

# include<stdio.h>
# include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("[Link]", "w");
printf("Enter data");
while( (ch = getchar()) != EOF)
{
putc(ch,fp);
}
fclose(fp);
fp = fopen("[Link]", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
fclose(fp);
}

Reading and Writing from File using fprintf() and fscanf()

#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};

void main()
{
struct emp e;
FILE *p,*q;
4 Asst. Prof. P. M. Patil
File Handling in C Language

p = fopen("[Link]", "a");
q = fopen("[Link]", "r");
printf("Enter Name and Age");
scanf("%s %d", [Link], &[Link]);
fprintf(p,"%s %d", [Link], [Link]);
fclose(p);
do
{
fscanf(q,"%s %d", [Link], [Link]);
printf("%s %d", [Link], [Link]);
}
while( !feof(q) );
getch();
}

In this program, we have create two FILE pointers and both are referring 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 console usinf standard printf() function.

//Program to copy data from one file to another file


//read data from file [Link] and copy into file [Link]

#include <stdio.h>
#include<conio.h>

void main()
{
FILE *fp1,*fp2;
char name[30];
clrscr();
fp1=fopen("[Link]","r");
fp2=fopen("[Link]","w");
while(!feof(fp1))
{
fscanf(fp1,"%s",name);
fprintf(fp2,"%s",name);
}

:- For o/p open file [Link] in TC


5 Asst. Prof. P. M. Patil
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

FILE HANDLING
 A file is a collection of bytes stored on a secondary storage device, which is
generally a disk of some kind. The collection of bytes may be interpreted, for
example, as characters, words, lines, paragraphs and pages from a textual
document; fields and records belonging to a database; or pixels from a graphical
image.
 The meaning attached to a particular file is determined entirely by the data
structures and operations used by a program to process the file. It is conceivable
(and it sometimes happens) that a graphics file will be read and displayed by a
program designed to process textual data.
 The result is that no meaningful output occurs (probably) and this is to be
expected. A file is simply a machine decipherable storage media where
programs and data are stored for machine usage.

Why we need file?


 When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter
them all. However, if you have a file containing all the data, you can easily
access the contents of the file using few commands in C. It is possible easily
move your data from one computer to another without any changes.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

File Operations
 In programming, we may require some specific input data to be generated
several numbers of times. Sometimes, it is not enough to only display the data
on the console. The data to be displayed may be very large, and only a limited
amount of data can be displayed on the console, and since the memory is
volatile, it is impossible to recover the programmatically generated data again
and again.
 However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in
C.
 File handling in C enables us to create, update, read, and delete the files stored
on the local file system through our C program. The following operations can be
performed on a file.
 Creation of the new file
 Opening an existing file
 Reading from the file
 Writing to the file
 Deleting the file

Types of Files
 There are two kinds of files in which data can be stored in two ways either in
characters coded in their ASCII character set or in binary format. They are
1. Text Files (or) ASCII file
2. Binary Files
Text Files (or) ASCII file
 The file that contains ASCII codes of data like digits, alphabets and symbols is
called text file (or) ASCII file.
Binary Files
 A binary file is a file that uses all 8 bits of a byte for storing the information .It is
the form which can be interpreted and understood by the computer.
 The only difference between the text file and binary file is the data contain in
text file can be recognized by the word processor while binary file data can’t be
recognized by a word processor.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

1. wb(write)
This opens a binary file in write mode.
SYNTAX: fp=fopen(“[Link]”,”wb”);
2. rb(read)
This opens a binary file in read mode
SYNTAX:fp=fopen(“[Link]”,”rb”);
3. ab(append)
This opens a binary file in a Append mode i.e. data can be added at the end
of file.
SYNTAX: fp=fopen(“[Link]”,”ab”);
4. r+b(read+write)
This mode opens preexisting File in read and write mode.
SYNTAX: fp=fopen(“[Link]”,”r+b”);
5. w+b(write+read)
This mode creates a new file for reading and writing in Binary mode.
SYNTAX: fp=fopen(“[Link]”,”w+b”);
6. a+b(append+write)
This mode opens a file in append mode i.e. data can be written at the end of
file.
SYNTAX: fp=fopen(“[Link]”,”a+b”);
Opening Modes in Standard I/O
r Open for reading If the file does not exist, fopen() returns
NULL
rb Open for reading in binary If the file does not exist, fopen() returns
mode. NULL.
w Open for writing. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb Open for writing in binary If the file exists, its contents are overwritten.
mode. If the file does not exist, it will be created.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

a Open for append. i.e, Data is If the file does not exists, it will be created.
added to the end of file.
ab Open for append in binary If the file does not exists, it will be created.
mode. i.e, Data is added to
end of file.
r+ Open for both reading and If the file does not exist, fopen() returns
writing. NULL.
rb+ Open for both reading and If the file does not exist, fopen() returns
writing in binary file. NULL
w+ Open for both reading and If the file exists, its contents are overwritten.
writing. If the file does not exist, it will be created.
wb+ Open for both reading and If the file exists, its contents are overwritten.
writing in binary mode. If the file does not exist, it will be created.
a+ Open for both reading and If the file does not exists, it will be created.
appending.
ab+ Open for both reading and If the file does not exists, it will be created.
appending in binary mode.

Closing a File: fclose(fptr);


 The file (both text and binary) should be closed after reading/writing. Closing a
file is performed using library function fclose().
Reading and writing to a text file
 The functions fprintf() and fscanf() are used to read or write the file They are
just the file versions of printf() and scanf(). The only difference is that, fprint
and fscanf expects a pointer to the structure FILE.
Writing to a text file
Program 2.20: Write to a text file using fprintf()
#include <stdio.h>
int main()
{
int num;
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

FILE *fptr;
fptr = fopen(“C:\\[Link]”,”w”);
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
printf(“Enter num: “);
scanf(“%d”,&num);
fprintf(fptr,”%d”,num);
fclose(fptr);
return 0;
}
 This program takes a number from user and stores in the file [Link]. After
you compile and run this program, you can see a text file [Link] created in
C drive of your computer. When you open the file, you can see the integer you
entered.
Reading from a text file
Program 2.21: Read from a text file using fscanf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen(“C:\\[Link]”,”r”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

fscanf(fptr,”%d”, &num);
printf(“Value of n=%d”, num);
fclose(fptr);
return 0;
}
Reading and writing to a binary file
 Functions fread() and fwrite() are used for reading from and writing to a file on
the disk respectively in case of binary files.
Writing to a binary file
 To write into a binary file, you need to use the function fwrite(). The functions
takes four arguments: Address of data to be written in disk, Size of data to be
written in disk, number of such type of data and pointer to the file where you
want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Program 2.22: Writing to a binary file using fwrite()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\[Link]”,”wb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
 We declare a structure three Num with three numbers - n1, n2 and n3, and
define it in the main function as num. Now, inside the for loop, we store the
value into the file using fwrite.
 The first parameter takes the address of num and the second parameter takes the
size of the structure three Num. Since, we’re only inserting one instance of num,
the third parameter is 1. And, the last parameter *fptr points to the file we’re
storing the data. Finally, we close the file.
Reading from a binary file
 Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);
Program 2.23: Reading from a binary file using fread()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

struct threeNum num;


FILE *fptr;
if ((fptr = fopen(“C:\\[Link]”,”rb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf(“n1: %d\tn2: %d\tn3: %d”, num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
 This program will start reading the records from the file [Link] in the
reverse order (last to first)
Text Files
 In C, all components are files, each with a different behavior based on the
attached devices. To enable the I/O functions, several standard built-in functions
were created and stored in libraries.
 Some of the high level file I/O functions are given in Table 2.1
Table 2.1 High level file I/O functions
[Link] Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

6 fclose() closes the file


7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file

1. fopen () : It creates a new file for use or opens an existing file for use.
2. fclose (): It closes a file which has been opened for use.
3. fscanf( file pointer, format string, address of the variable)
Example: fscanf(fptr,”%d”, &num);
4. fprintf(console output, “format string”, file pointer);
Example: fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
5. getw (): This function returns the integer value from a given file and increment the
file pointer position to the next message.
Syntax: getw (fptr);
Where fptr is a file pointer which takes the integer value from file.
6. putw (): This function is used for writing an integer value to a given file.
Syntax: putw (value,fptr);
Where fptr is a file pointer Value is an integer value which is written to a given file.
Example Program for getw() and putw()
Program 2.24: Write a program to read integer data from the user and write it
into the file using putw() and read the same integer data from the file using getw()
and display it on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

int n;
clrscr();
fp=fopen(“[Link]”, “wb+”);
printf(“Enter the integer data”);
scanf(“%d”,&n);
while(n!=0)
{
putw(n,fp);
scanf(“%d”,&n);
}
rewind(fp);
printf(“Reading data from file”);
while((n=getw(fp))!=EOF)
{
printf(“%d\n”,n);
}
fclose(fp);
getch();
}
7. fwrite()
 This function is used for writing an entire block to a given file.
Syntax: fwrite(ptr,size,nst,fptr);
ptr is a pointer ,it points to the array of structure.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
8. fread()
 fread(ptr,size,position,fptr);similar to fwrite
9. fflush(stdin);To clean the input stream
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

Program 2.25: program for fwrite():


Write a program to read an employee details and write them into the file at a time
using fwrite().
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
int eno;
char ename[20];
float sal;
}e;
FILE *fp;
fp=fopen(“[Link]”, “wb”);
clrscr();
printf(“Enter employee number”);
scanf(“&d”,&[Link]);
printf(“Enter employee name”);
fflush(stdin);
scanf(“%s”,[Link]);
printf(“Enter employee salary”);
scanf(“%f”,&[Link]);
fwrite(&e,sizeof(e),1,fp);
printf(“One record stored successfully”);
getch();
}
Operations for Search data in a file
1. fseek()
2. ftell()
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

3. rewind()
fseek() : Getting data using fseek()
 When many records inside a file and need to access a record at a specific
position, you need to loop through all the records before it to get the record. This
will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
fseek(file pointer, displacement, pointer position);
 The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.
 This function is used for seeking the pointer position in the file at the specified
byte.
Syntax: fseek( file pointer, displacement, pointer position);
file pointer - It is the pointer which points to the file.
displacement -It is positive or negative.
 This is the number of bytes which are skipped backward (if negative) or forward
(if positive) from the current position. This is attached with L because this is a
long integer.
Pointer position: This sets the pointer position in the file.
Value Pointer position Value Pointer position
0 Beginning of file.
1 Current position
2 End of file

Example:
1. fseek( p,10L,0)
 This 0 means pointer position is on beginning of the file, from this statement
pointer position is skipped 10 bytes from the beginning of the file.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

2. fseek( p,5L,1)
 This 1 means current position of the pointer position. From this statement
pointer position is skipped 5 bytes forward from the current position.
3. fseek(p,-5L,1):
 From this statement pointer position is skipped 5 bytes backward from the
current position.

Program 2.26: for fseek()


#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\[Link]”,”rb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
// Moves the cursor to the end of the file
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

fseek(fptr, sizeof(struct threeNum), SEEK_END);


for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf(“n1: %d\tn2: %d\tn3: %d”, num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
ftell()
 This function is used to move the file pointer to the beginning of the given file.
This function returns the value of the current pointer position in the file. The
value is count from the beginning of the file.
Syntax: ftell(fptr); fptr is a file pointer.
rewind()
Syntax: rewind( fptr); fptr is a file pointer.
Program 2.27: program for fseek():
Write a program to read last ‘n’ characters of the file using appropriate file
functions(Here we need fseek() and fgetc()).
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen(“file1.c”, “r”);
if(fp==NULL)
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

printf(“file cannot be opened”);


else
{
printf(“Enter value of n to read last ‘n’ characters”);
scanf(“%d”,&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf(“%c\t”,ch);
}
}
fclose(fp);
getch();
}

PREPROCESSOR DIRECTIVES
 The C preprocessor is a microprocessor that is used by compiler to transform
your code before compilation. It is called micro preprocessor because it allows
us to add macros.
 Note: A macro is a segment of code which is replaced by the value of macro.
Macro is defined by #define directive.
Example
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

 All preprocessor directives starts with hash # symbol. Let's see a list of
preprocessor directives.
 #define: It substitutes a preprocessor using macro.
 #include: It helps to insert a certain header from another file.
 #undef: It undefines a certain preprocessor macro.
 #ifdef: It returns true if a certain macro is defined.
 #ifndef: It returns true if a certain macro is not defined.
 #if, #elif, #else, and #endif: It tests the program using a certain condition;
these directives can be nested too.
 #line: It handles the line numbers on the errors and warnings. It can be used
to change the line number and source files while generating output during
compile time.
 #error and #warning: It can be used for generating errors and warnings.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

 #error can be performed to stop compilation.


 #warning is performed to continue compilation with messages in the console
window.
 #region and #endregion: To define the sections of the code to make them
more understandable and readable, we can use the region using expansion
and collapse features.
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
The C Standard Library
C Programming and Software Tools
N.C. State Department of Computer Science
The Standard C Library
• A small set of highly useful functions,
standardized across all platforms
• Definitions are captured in 24 header files

• (Color-coding in the table on next slides


– green = we’ve already talked about
– red = will discuss now
– blue = will get too soon
– grey = skipping)

CSC230: C and Software Tools © NC State University Computer Science Faculty 2


The Standard Library
Testing for errors and printing helpful error
<assert.h>
messages
Classify characters, convert between upper and
<ctype.h>
lower case
Defined constants specifying the
<limits.h> implementation-specific properties of the
integer types
Accessing a varying number of arguments
<stdarg.h>
passed to functions
<stdbool.h> Defining boolean data types

<string.h> Manipulating strings


CSC230: C and Software Tools © NC State University Computer Science Faculty 3
The Standard Library (cont’d)
<errno.h> Testing error codes reported by library functions

<math.h> Computing common mathematical functions

Various; including conversion, pseudo-random


<stdlib.h> numbers, memory allocation, process control,
environment, signalling, searching, and sorting

Core input and output capabilities of the C


<stdio.h>
language

CSC230: C and Software Tools © NC State University Computer Science Faculty 4


The Standard Library (cont’d)
<stdint.h> Defining various integer types

<time.h> Converting between time and date formats

<complex.h> Functions for manipulating complex numbers.

<fenv.h> Controlling the floating-point environment


Constants specifying the implementation-specific properties
<float.h>
of the floating-point library
<inttypes.h> Precise conversion between integer types

<iso646.h> Programming in ISO 646 variant character sets

<setjmp.h> setjmp/longjmp for non-local exits

CSC230: C and Software Tools © NC State University Computer Science Faculty 5


The Standard Library (cont’d)
<locale.h> Choosing and customizing for a locale

<stddef.h> Defining several useful types and macros

<signal.h> Controlling asynchronous process interaction

Manipulating strings using wide characters - key to


<wchar.h>
supporting a range of languages

<wctype.h> Classifying wide characters

CSC230: C and Software Tools © NC State University Computer Science Faculty 6


<math.h>: Using the Math Library
• Note: to use math functions, be sure you specify
–lm to gcc (after the source file names)
> gcc pgmx.c -lm -o pgmx

• Some constants
M_E The base of natural logarithms
M_PI Value of π
M_SQRT2 Square root of 2

• See King, Chapter 23.4 for additional resources

CSC230: C and Software Tools © NC State University Computer Science Faculty 7


<math.h> Trigonometry
• Input type is a double, returns type double

cos(), Input in radians


sin(), Return value in [-1.0, 1.0]
tan()
acos(), Input in [-1.0, 1.0]
asin(), Return value in [-π, π] radians
atan()

CSC230: C and Software Tools © NC State University Computer Science Faculty 8


<math.h> Exponents, logs, and more
• Input types double, returns type double
exp(x) ex pow(x,y) xy
exp2(x) 2x sqrt(x) √x
exp10(x) 10x
log(x) logex
log2(x) log2x
log10(x) log10x

fabs(x) absolute value


floor(x) largest integer ≤ x
ceil(x) smallest integer ≥ x
CSC230: C and Software Tools © NC State University Computer Science Faculty 9
Exercise 21a
Trig tool
• Write a program that takes an integer number
of degrees on the command line and prints the
cosine of the value.
– Recall that trig functions take parameters in floating
point radians
𝜋
– Recall that 𝑟𝑎𝑑𝑖𝑎𝑛𝑠 = 𝑑𝑒𝑔𝑟𝑒𝑒𝑠
180
– You can skip error checking $ gcc –lm cos.c -o cos
$ ./cos 0
1.000000
$ ./cos 45
0.707107
CSC230 - C and Software Tools © NC State University Computer Science Faculty $ ./cos 90
Reminder: Go to course web page for link to exercise form. 0.000000
Paste code into [Link] and submit the link. 10
<errno.h>: System Error Messages
void perror(const char *s)

Prints string s + an implementation-defined error message


corresponding to value of the integer errno
– errno set by a previous standard library call
– perror is a function in stdlib.h
– Always set errno to 0 before any function call that you want to
test

See King Section 24.2

CSC230: C and Software Tools © NC State University Computer Science Faculty 11


<errno.h> …Error Messages (cont’d)
• Example
if ((myfile = fopen(“[Link]”, “r”)) == NULL {
perror(“[Link]”);
exit(-1);
};

Output
> [Link]
[Link]: No such file or directory

CSC230: C and Software Tools © NC State University Computer Science Faculty 12


<math.h> Errors
• Domain Error: argument outside domain
– EDOM is stored in errno
– Function may return NaN, but return value is
implementation defined
• Range Error: result is outside range of double
– ERANGE is stored in errno if overflow (may be stored
for underflow)
– Function returns + or – HUGE_VAL if overflow
– Function returns 0 for underflow

CSC230: C and Software Tools © NC State University Computer Science Faculty 13


<stdlib.h>: Miscellaneous
• void abort(void), void exit(int status)
– terminate execution, terminate with a non-zero return code
• void * bsearch(void * key, void *base,
size_t nelems, size_t size_elem,
int (*compar) (void *, void *))
– binary search in a sorted array starting at base, with
nelems elements each of size size_elem, looking for the
item with value key, using the comparison function compar
to determine equality

CSC230: C and Software Tools © NC State University Computer Science Faculty 14


<stdlib.h>: ...Miscellaneous
• void qsort(void *base, size_t
nelems, size_t size_elem,
int (*compar) (void *, void *))
– sort the array starting at base, with nelems
elements each of size size_elem, using the
comparison function compar to determine ordering

CSC230: C and Software Tools © NC State University Computer Science Faculty 15


<stdlib.h>: ...Miscellaneous
char strings[][20] = {
"apples",
"grapes",
"strawberries",
"bananas"};
char item[20] = "strawberries";

// sort the strings


qsort(strings, 4, 20, strcmp);

// search for "strawberries"


char *pos =
(char *) bsearch(item, strings, 4, 20, strcmp);

if (pos)
printf("The string \"%s\" was found.\n", pos);

CSC230: C and Software Tools © NC State University Computer Science Faculty 16


<stdint.h>: Standard size types!
signed type unsigned type description
intmax_t uintmax_t Integer type with the maximum width supported.
int8_t uint8_t Integer type with a width of exactly 8, 16, 32, or 64 bits.
int16_t uint16_t For signed types, negative values are represented using 2's
int32_t uint32_t complement.
No padding bits.
int64_t uint64_t Optional: These typedefs are not defined if no types
with such characteristics exist.
int_least8_t uint_least8_t
int_least16_t uint_least16_t Integer type with a minimum of 8, 16, 32, or 64 bits.
No other integer type exists with lesser size and at least the
int_least32_t uint_least32_t
specified width.
int_least64_t uint_least64_t
int_fast8_t uint_fast8_t
int_fast16_t uint_fast16_t Integer type with a minimum of 8, 16, 32, or 64 bits.
At least as fast as any other integer type with at least the
int_fast32_t uint_fast32_t
specified width.
int_fast64_t uint_fast64_t
Integer type capable of holding a value converted from
a void pointer and then be converted back to that type with a
intptr_t uintptr_t value that compares equal to the original pointer.
Optional: These typedefs may not be defined in some library
implementations.*
<time.h>: Time!
• UNIX Epoch Time: Number of seconds elapsed
since midnight on January 1st, 1970.
• A plain integer – lets you do math!
– Time elapsed: now – then
– Time in the future: now + delay

UNIX Epoch clock:


[Link]

CSC230: C and Software Tools © NC State University Computer Science Faculty 18


<time.h>: Time!
int main()
{
time_t epoch_time = time(NULL);
printf("Epoch time: %d\n",epoch_time);

struct tm* now = localtime(&epoch_time); // in our time zone


printf("Manual formatting: The date is %d/%d/%d.\n",
now->tm_mon+1, now->tm_mday, now->tm_year+1900);

char* now_str = asctime(now); // output includes newline


printf("asctime formatting: %s",now_str);

char buf[128];
strftime(buf, sizeof(buf),
"Date: %e %B %Y, Time: %H:%M %Z", now);
printf("strftime custom formatting: %s\n", buf);

}
Epoch time: 1405894768
Manual formatting: The date is 7/20/2014.
asctime formatting: Sun Jul 20 18:19:28 2014
strftime custom formatting: Date: 20 July 2014, Time: 18:19 EDT
CSC230: C and Software Tools © NC State University Computer Science Faculty 19
UNIX, POSIX, and you
• UNIX: The defining operating system of the 20th
century, created by Kernigan and Ritchie
(the C guys)
– Many descendants still in use today (HP-UX, Solaris, AIX,
*BSD, Mac OS X, Linux)
• POSIX: A standard where a bunch of UNIXy types
got together and standardized their APIs
• Even Windows supports the core of POSIX
• POSIX is not core C99, but it’s pretty much as well
supported.

CSC230: C and Software Tools © NC State University Computer Science Faculty 20


UNIX through time

CSC230: C and Software Tools © NC State University Computer Science Faculty 21


Useful POSIX calls
#include <unistd.h>

int chdir(const char *); // Change directory

char *getlogin(void); // Find current username

char *getcwd(char *, size_t); // Find current directory

unsigned int sleep(unsigned int); // Wait time

CSC230: C and Software Tools © NC State University Computer Science Faculty 22


Exercise 21b
Investigate
• Find out what the logged in user and current
directory are when you run something through
ideone

CSC230 - C and Software Tools © NC State University Computer Science Faculty


Reminder: Go to course web page for link to exercise form.
Paste code into [Link] and submit the link. 23
Any Questions?

CSC230 - C and Software Tools © NC State University Computer Science Faculty 24

You might also like