0% found this document useful (0 votes)
19 views114 pages

Programming With C

Notes of pwc fy bsc IT

Uploaded by

piyushayare7
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)
19 views114 pages

Programming With C

Notes of pwc fy bsc IT

Uploaded by

piyushayare7
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
You are on page 1/ 114

BSCIT 1.

F. Y. BSC. IT
SEMESTER - I
REVISED SYLLABUS AS PER NEP 2020

PROGRAMMING WITH C
© UNIVERSITY OF MUMBAI
Prof. Ravindra Kulkarni
Vice Chancellor
University of Mumbai, Mumbai.
Prin. Dr. Ajay Bhamare Prof. Dr. Shivaji Sargar
Pro Vice-Chancellor, Director
University of Mumbai. CDOE, University of Mumbai.

Programe Co-ordinator : Prof. Mandar L. Bhanushe


Head, Faculty of Science and Technology,
CODE, University of Mumbai – 400098.

Course Coordinator : Ms. Gouri S. Sawant


Assistant Professor B.Sc.IT,
CDOE, University of Mumbai- 400098.

Editor : Dr. Ghayathri J


Principal
Cheran Arts Science College,
Kangayam, Tamil Nadu.

Course Writers : Mr. Asif Rampurawala


Vice Principal,
Vidyalankar School of Information Technology

: Mrs. Sangeeta Menon


Assistant Professor
Pillai HOC College of Arts Science and Commerce

July 2025, Print I,

Published by
Director
Centre for Distance and Online Education, University of Mumbai,
Vidyanagari, Mumbai - 400 098.

DTP COMPOSED AND PRINTED BY


Mumbai University Press, Vidyanagari, Santacruz (E), Mumbai - 400098.
CONTENTS
Unit No. Title Page No

1. Introduction to Programming in C 1

2. Introduction to Programming in C 27

3. Controls in C 50

4. Basics of Function 70

5. Pointers and Addresses 84

6. User Defined Data Types 98

*****
Major Courses

Name of the Course: Programming with C

Sr.No Heading Particulars


.
1 Description the This course allows the students to understand the
course : fundamental concepts of programming which will allow them
Including but Not to program applications in C.
limited to:
2 Vertical : Major
3 Type : Theory
4 Credits : 2 credits (1 credit = 15 Hours for Theory in a semester)
5 Hours Allotted : 30 Hours
6 Marks Allotted: 50 Marks
7 Course Objectives(CO):
CO 1. To understand the concepts of computer programming.
CO 2. To understand syntax and semantics of the C language
CO 3. To understand loops and decision making in programming.
CO 4. To understand the use of arrays, structures, union and pointers.
CO 5. To understand functions for modular code and handle errors.

8 Course Outcomes (OC):


OC 1. Students can build flowcharts, pseudocode for C programs.
OC 2. Students can use C language syntax and semantics in their
programs.
OC 3. Students can implement loops and decision making.
OC 4. Students can use different types of data structures in their programs.
OC 5. Students can write well-structured, readable, and maintainable C
code and debug programs if there are any errors.
9 Modules:-
Module 1:
1. Introduction: Algorithms, History of C, Structure of C Program.
Program Characteristics, Compiler, Linker and preprocessor,
pseudo code statements and flowchart symbols, Desirable
program characteristics. Program structure. Compilation and
Execution of a Program, C Character Set, identifiers and
keywords, data types and sizes, constants and its types, 15 Hrs
variables, Character and character strings, typedef, typecasting
2. Type of operators: Arithmetic operators, relational and logical
operators, Increment and Decrement operators, assignment
operators, the conditional operator, Assignment operators and
expression, Precedence and order of Evaluation Block
Structure, Initialization, C Preprocessor
Module 2:
1. Control Flow: Statements and Blocks, If-Else, Else-If, Switch, 15 Hrs
Loops- While and For Loops Do-while, Break and Continue,
Goto and Labels
2. Basics of functions. User defined and Library functions
3. Pointer and Addresses, Pointer and Function Arguments,
Pointer and Arrays.
4. User-defined data types- structure and union
10 Books and References:

1. C Programming Language, Brian W. Kernighan, Dennis M. Ritchie , 2017


2. Let Us C, Yashvant Kanetkar, BPB Publications,2008.
3. Mastering in C, K. R. Venugopal and Sudeep R. Prasad, Tata McGraw-Hill
Publications.
4. A Computer Science –Structure Programming Approaches using C,
Behrouz Forouzan, Cengage Learning.
5.. Schaum’s outlines Programming with C, Byron S. Gottfried, Tata
McGraw- Hill Publications.
6. Basics of Computer Science, by Behrouz Forouzan, Cengage Learning.
7. Programming Techniques through C, by M. G. Venkateshmurthy, Pearson
Publication.
12 Internal Continuous Semester End Examination: 60%
Assessment: 40%
13 Continuous Evaluation through: Format of Question Paper: External
Class test of 1 of 15 marks Examination (30 Marks)– 1 hr duration
Class test of 2 of 15 marks
Average of the two: 15 marks

Quizzes/ Presentations/
Assignments: 5 marks
Total: 20 marks
14 Format of Question Paper: (Semester End Examination : 30 Marks. Duration:1
hour)
Q1: Attempt any two (out of four) from Module 1 (15 marks)
Q2: Attempt any two (out of four) from Module 2 (15 marks)
1
INTRODUCTION TO
PROGRAMMING IN C
Unit Structure
1.1 Introduction to Algorithms
1.2 History of C Programming Language
1.3 Structure of a C Program
1.4 Program Characteristics
1.5 Compiler, Linker, and Preprocessor
1.6 Pseudo Code Statements and Flowchart Symbols
1.7 Program Structure in C
1.8 Compilation and Execution of a Program
1.9 C Character Set, Identifiers, and Keywords
1.10 Data Types and Sizes
1.11 Constants and its Types
1.12 Variables in C
1.13 Characters and Character Strings
1.14 Typedef and Typecasting

1.0 LEARNING OUTCOMES


After completing this chapter, students will be able to:

 Define algorithms and explain their significance in problem-solving.

 Outline the history of the C programming language and its impact on


modern computing.

 Demonstrate the structure and key components of a simple C


program.

 Explain the role of the compiler, linker, and preprocessor in program


execution.

 Write pseudo code and draw flowcharts for simple algorithms.

1
Programming With C  Identify desirable program characteristics and apply them to improve
code quality.

 Understand and apply the steps involved in compiling and executing a


C program.

 Recognize and correctly use the C character set, identifiers, and


keywords in programming.

 Differentiate between various data types in C and understand their


sizes and ranges.

 Define constants and variables appropriately in C programs.

 Handle characters and character strings effectively.

 Apply typedef to create new data types and use typecasting for
conversions.

1.1 INTRODUCTION ALGORITHM


An algorithm is a well-defined step-by-step procedure or a set of
instructions designed to solve a specific problem or accomplish a
particular task. It can be thought of as a recipe for solving a problem,
where each step must be clearly defined, finite, and executable.
In the context of computer science, algorithms are the backbone of
programming and software development. They serve as the blueprint that
defines how a problem is approached and solved using a computer
program. For example, when writing a program to sort numbers, the
sorting technique (like bubble sort or quicksort) is essentially an
algorithm.

Characteristics of a Good Algorithm


A good algorithm has certain important characteristics. These
characteristics ensure that the algorithm is effective, efficient, and usable
across various scenarios. The following are key features of a well-
designed algorithm:
1. Input: It should have well-defined inputs. These inputs are taken
before the algorithm starts or as the algorithm runs.
2. Output: It must generate one or more outputs, which are the desired
result after the algorithm completes.
3. Finiteness: The algorithm must terminate after a finite number of
steps. An algorithm should not be infinite; it should stop after
achieving the goal.
4. Definiteness: Every step of the algorithm must be clearly and
precisely defined. This means that the instructions should be
unambiguous and easy to understand.

2
5. Effectiveness: Each step of the algorithm must be effective, meaning Introduction to Programming
In C
it should be simple enough to be carried out in a finite amount of
time.
6. Generality: The algorithm should be general enough to solve all
instances of the problem, not just one specific case.

Writing an Algorithm:
An algorithm is typically written in a structured, natural language or in the
form of pseudocode. This pseudocode is a high-level description of the
steps involved in solving a problem, without worrying about the syntax of
a particular programming language.

Example: Algorithm to find the sum of two numbers


1. Start
2. Declare two variables a and b.
3. Read the values of a and b.
4. Calculate the sum sum = a + b.
5. Print the sum.
6. Stop
This is a simple example that demonstrates the structure of an algorithm:
clear steps leading from start to finish, with a well-defined output (the sum
of two numbers).

Why are Algorithms Important?


Algorithms are essential for several reasons:
1. Efficiency: A good algorithm helps to solve problems in an efficient
manner, which is especially important for large datasets or complex
tasks. Well-designed algorithms optimize the time and resources
required to achieve the result.
2. Reusability: Once an algorithm is designed for a particular task, it
can often be reused for solving similar problems with minor
adjustments.
3. Problem Solving: Algorithms help in breaking down complex
problems into smaller, manageable steps. This systematic approach is
key to solving large-scale computational problems.
4. Foundation of Programming: Writing efficient programs requires
understanding algorithms. They form the foundation upon which
programming and software development are built.

3
Programming With C Common Algorithm Design Techniques:
There are several fundamental algorithm design strategies that computer
scientists use to approach and solve problems. Some of these include:
1. Divide and Conquer: This technique breaks a problem down into
smaller subproblems, solves each subproblem individually, and then
combines the solutions to solve the original problem. Example: Merge
Sort, Quick Sort.
2. Greedy Algorithms: This technique solves a problem step-by-step,
always choosing the best possible solution at each step without
considering the overall problem. It works well for optimization
problems. Example: Dijkstra's Shortest Path Algorithm.
3. Dynamic Programming: This approach breaks down a problem into
simpler subproblems, solves each subproblem once, and stores its
solution to avoid computing the same subproblem multiple times.
Example: Fibonacci sequence calculation.
4. Brute Force: This method involves trying every possible solution to
find the best one. While this is simple to implement, it can be
inefficient for large problems. Example: Exhaustive search
algorithms.

Algorithm Complexity:
When evaluating algorithms, it is important to understand their
complexity, which refers to the resources (time and space) required for the
algorithm to execute. Algorithm complexity is commonly measured in
terms of:
 Time Complexity: This is the amount of time an algorithm takes to
complete as a function of the input size. It's typically expressed using
Big O notation (e.g., O(n), O(log n)).
 Space Complexity: This refers to the amount of memory an
algorithm uses relative to the size of the input.
Big O Notation is a mathematical notation used to describe the efficiency
of an algorithm based on the input size. It helps us classify algorithms by
their worst-case performance. For instance, an algorithm with a time
complexity of O(n) means that the time taken grows linearly with the input
size, while O(log n) indicates logarithmic growth.

1.2 HISTORY OF C PROGRAMMING LANGUAGE


The C programming language is one of the most influential and widely
used programming languages in the history of computer science.
Developed in the early 1970s by Dennis Ritchie at Bell Labs, C has
served as the foundation for many modern programming languages,
including C++, Java, Python, and more.

4
C is a general-purpose, procedural programming language that is Introduction to Programming
In C
highly efficient and close to the machine level. This means it allows
programmers to write code that interacts directly with hardware, making it
suitable for system programming tasks such as operating system
development, embedded system programming, and hardware interfacing.

Origins of C:
The C language was developed as a successor to the B language, which
itself was influenced by an earlier language called BCPL (Basic
Combined Programming Language). B was created by Ken Thompson
in 1969, also at Bell Labs, as part of the development of the UNIX
operating system. However, B had limitations, especially when dealing
with the growing complexity of system development.
Dennis Ritchie saw the need for a more flexible and powerful language
that could take advantage of the growing capabilities of computer systems.
In 1972, he designed the C language, which retained many of B’s features
while adding critical improvements like:
 Data types: C introduced different types for integers, floating-point
numbers, and characters.
 Structured programming: C included control flow constructs such
as if-else, while, and for loops, which made writing structured
programs easier.
UNIX itself was rewritten in C, which played a significant role in the
adoption of the language, as UNIX became the dominant operating system
in academic and research environments.

Key Milestones in the Development of C:


1. Early 1970s: Creation of C:
o Dennis Ritchie developed C to support the growing needs of system
programming, especially for writing the UNIX operating system. It
combined features of the B language with improvements like richer
data types and more control structures.

2. 1978: The K&R C Standard:


o In 1978, Brian Kernighan and Dennis Ritchie published the book
“The C Programming Language,” which became known as K&R
C. This book provided a formal description of the language and
introduced a number of conventions that influenced the later
development of C.
o K&R C became the first widely used version of the language, serving
as a de facto standard.

5
Programming With C 3. 1989: ANSI C (C89)):
o As C gained popularity, the American National Standards Institute
(ANSI) formed a committee to standardize the language. The result
was ANSI C or C89, a version of the language that provided more
uniformity and portability. This standard became the basis for many C
compilers.

4. 1999: C99 Standard:


o In 1999, a new standard, C99, was introduced. This version added
several new features, including:
 Inline functions
 Variable-length arrays
 New data types such as long long int for larger integers and _Bool for
boolean logic
 Support for single-line comments (//), similar to C++.

5. 2011: C11 Standard:


o In 2011, another update known as C11 was introduced. It included
features for improved concurrency, better memory management, and
additional standard library functions, enhancing the language's ability
to meet modern programming needs.

6. Future of C:
o While newer languages have emerged, C continues to be widely used,
especially in system programming, embedded systems, and
performance-critical applications. Its legacy persists in modern
programming languages and software development practices.

Importance and Influence of C:


C's influence on programming has been profound for several reasons:
1. Foundation for Other Languages: Many modern programming
languages, such as C++, Java, and even Python, borrow heavily from
C in terms of syntax and concepts. For instance:
o C++ extends C by adding object-oriented features.
o Java adopts a syntax similar to C, making it easier for C
programmers to learn.
o The syntax of many popular scripting languages (like PHP,
JavaScript) also traces its roots to C.
2. Portability: C programs are highly portable, meaning they can run on
different hardware and operating systems with minimal modifications.

6
This portability made C an ideal choice for system programming and Introduction to Programming
In C
software development across platforms.
3. Efficiency: C is known for its efficiency, particularly in terms of
memory usage and execution speed. Since C programs allow low-
level manipulation of memory using pointers and direct hardware
access, it is widely used in areas where performance is critical, such
as:
o Operating systems (e.g., Linux, Windows kernel)
o Embedded systems (e.g., microcontrollers)
o High-performance computing applications.
4. System Programming: One of C’s primary strengths is in system
programming. Many of the world’s operating systems, including
UNIX, Linux, and parts of Windows, are written in C. C allows
programmers to write software that can interact with hardware at a
low level, giving it a unique advantage in this domain.
5. Wide Usage in Academia: Because of its simplicity, direct control
over hardware, and foundational nature, C is widely taught in
computer science programs as an introductory programming
language. Students who learn C acquire a deeper understanding of
how computers work, including memory management and algorithmic
problem-solving.

1.3 STRUCTURE OF A C PROGRAM


A C program is typically structured in a specific way, ensuring clarity and
proper execution of the program. The structure defines how various
components like functions, variables, and statements are arranged to form
a complete program. Understanding this structure is essential for writing
efficient and error-free C programs.
Every C program consists of several key components:
 Preprocessor directives
 Global declarations
 The main() function (which is the entry point of the program)
 User-defined functions (optional)
Let’s break down the structure in detail.

Basic Structure of a C Program:


A basic C program can be divided into the following sections:

7
Programming With C 1. Documentation Section:
This section includes comments that describe the purpose of the program,
author information, date of creation, and other relevant details. Although
this section is optional, it is highly recommended for code readability and
maintainability.
/*
Program to demonstrate the structure of a C program
Author: Asif R
Date: October 2024
*/

2. Preprocessor Directives:
Preprocessor directives are instructions given to the preprocessor, which
runs before the actual compilation of the program. These typically include
header files (#include) and macro definitions (#define).
Example:
#include <stdio.h> // Header file for standard input and output functions
#define PI 3.14 // Macro to define a constant value for PI

3. Global Declarations:
This section contains declarations of global variables and function
prototypes, which are accessible throughout the program. Global variables
are declared outside the main() function and can be used by any function
within the program.
int globalVar = 10; // Global variable declaration

4. The main() Function:


The main() function is the entry point of every C program. When the
program is executed, the control starts from the main() function. It
contains statements that form the core logic of the program. Every C
program must have exactly one main() function.
The general syntax of the main() function:
int main() {
// Code to be executed
return 0;
}
o int main() declares the function main() which returns an integer value
(commonly 0, indicating successful program termination).
8
o The body of the function, enclosed within curly braces {}, contains Introduction to Programming
In C
the executable code.
o The return 0; statement is used to return a value to the operating
system, typically indicating that the program executed successfully.

5. Local Declarations:
Inside the main() function (and other functions), you can declare variables
that are only accessible within that function. These are called local
variables.
int a, b; // Local variable declarations

6. Executable Statements:
This section contains the actual code or instructions to perform specific
tasks, such as input/output operations, mathematical calculations, and
control statements. Example:
a = 5;
b = 10;
printf("The sum of a and b is: %d", a + b);

7. User-Defined Functions (Optional):


If the program is large or complex, it is good practice to divide it into
smaller, reusable blocks of code called functions. Functions allow for
better modularity and code reusability. These functions can be defined
outside the main() function and can be called from anywhere in the
program. Example of a user-defined function:
int add(int x, int y) {
return x + y;
}

Example of a Simple C Program:


Here’s an example of a simple C program that adds two numbers and
prints the result:
#include <stdio.h> // Preprocessor directive to include standard I/O
functions

// Main function
int main() {
int num1, num2, sum; // Local variable declarations

9
Programming With C

// Input from the user


printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);

// Calculate the sum


sum = num1 + num2;

// Output the result


printf("The sum of %d and %d is: %d", num1, num2, sum);

return 0; // Return 0 to indicate successful execution


}

Explanation:
 #include <stdio.h>: Includes the standard input/output library, which
provides functions like printf() and scanf().
 int main(): This is the entry point of the program.
 Variables num1, num2, and sum are declared to store integer values.
 scanf() is used to get input from the user, and printf() is used to
display output.
 return 0; indicates the program has finished executing successfully.

Breakdown of Key Elements:


1. Preprocessor Directives: These lines start with #, such as #include,
and are used to include libraries or define constants. Preprocessor
directives are processed before the actual compilation begins. For
instance, #include <stdio.h> tells the compiler to include the standard
I/O library, which provides functions like printf() and scanf().
2. The main() Function: This is the heart of every C program. The
program execution starts and ends with main(). Any code written
inside the main() function will be executed when the program is run.
3. Variables and Declarations: Variables must be declared before they
are used in the program. The declaration tells the compiler about the
data type of the variable (e.g., int, float, char). In the example, int
num1, num2, sum; declares three integer variables.
10
4. Input/Output Functions: C provides several built-in functions for Introduction to Programming
In C
input and output. For example, scanf() reads input from the user, and
printf() prints output to the screen. These functions are part of the
stdio.h library.
5. Executable Statements: Statements inside the main() function define
the logic of the program. In the example, sum = num1 + num2; is a
statement that calculates the sum of two numbers.
6. Return Statement: The main() function typically ends with a return
0; statement. This is a signal to the operating system that the program
has executed successfully. A non-zero return value may indicate an
error or abnormal termination.

Understanding Program Flow:


1. Compilation: When the C program is written, it needs to be
compiled. The compiler translates the C code (source code) into
machine language (object code) that the computer can execute. The
compilation process checks for syntax errors and produces an
executable file.
2. Execution: Once compiled, the program can be executed. During
execution, the instructions in the main() function are followed step-
by-step, performing the necessary computations and providing output
as required.

1.4 INTRODUCTION TO PROGRAM


CHARACTERISTICS
A good program should have certain characteristics that make it effective
and easy to manage. These include:
1. Correctness: The program should do what it is supposed to do and
provide correct results for all valid inputs.
2. Readability: The code should be easy to read and understand. This is
achieved by using meaningful variable names, proper indentation, and
comments to explain complex sections.
3. Efficiency: The program should use system resources like time and
memory effectively. Optimized code runs faster and uses less
memory.
4. Maintainability: The program should be easy to modify, fix, or
update. Well-structured code with functions and modules makes
maintenance easier.
5. Portability: The program should work on different platforms
(Windows, Linux, macOS) with little or no modification. Writing
standard C code helps achieve portability.

11
Programming With C 6. Robustness: The program should handle errors gracefully and not
crash when given unexpected input. Input validation and error
handling are important.
7. Reusability: Code that can be reused in other programs saves time
and effort. Functions and modules can be designed to be reused across
different projects.

1.5 THE PREPROCESSOR


The preprocessor is the first step when a C program is compiled. It
processes instructions called preprocessor directives, which start with #.
These include:
 File inclusion: #include is used to add header files, like #include
<stdio.h>.
 Macro definition: #define creates constants or small code snippets,
like #define PI 3.14.
 Conditional compilation: Using #ifdef and #ifndef, code can be
included or excluded based on conditions.

The Compiler:
The compiler translates the preprocessed code into machine code (object
code). It checks the syntax and logic of the program and generates an
object file (.o or .obj) that contains machine-readable instructions.

Key stages of compilation:


 Lexical analysis: Breaks the code into tokens (e.g., variables,
keywords).
 Syntax and semantic analysis: Ensures the code follows the rules of
C and is logically correct.
 Code generation: Produces machine code that the computer can
understand.

The Linker:
The linker takes the object files created by the compiler and combines
them into a single executable file. It also links external libraries (like
printf() from the standard C library).

Tasks of the linker:


 Combine object files: Links multiple files into one executable.
 Resolve references: Finds addresses for functions and variables used
in different files.
 Library linking: Includes necessary libraries to make the program
complete.
12
Introduction to Programming
1.6 PSEUDO CODE In C

Pseudo code is a way to describe algorithms using plain, simple language


that is not tied to any specific programming syntax. It helps in planning
how a program will solve a problem before actually writing the code.
Pseudo code allows programmers to focus on the logic without worrying
about syntax errors.

Key Features of Pseudo Code:


 Simple language: It uses basic English-like phrases to describe each
step.
 No strict rules: There's no fixed syntax, but it should be clear and
understandable.
 Structured logic: It describes loops, conditions, and calculations like
real code, but in a simplified manner.
Example of Pseudo Code:
Start
Input two numbers: a, b
Set sum = a + b
Print sum
End

Introduction to Flowchart Symbols:


A flowchart is a visual representation of an algorithm or process. It uses
different shapes to represent different types of actions or decisions,
making it easy to follow the logic step-by-step.
Common Flowchart Symbols:
1. Oval (Terminator): Represents the start or end of a program.
o Example: Start, End
2. Rectangle (Process): Represents a step where a task or action is
performed.
o Example: Calculation, assignment
3. Parallelogram (Input/Output): Represents input from the user or
output to the screen.
o Example: Input numbers, Print result
4. Diamond (Decision): Represents a decision or branching point in the
flow (e.g., an if statement).

13
Programming With C o Example: If condition is true or false
5. Arrows: Show the flow of the program from one step to another.

Example of a Flowchart:

14
Introduction to Programming
1.8 INTRODUCTION TO PROGRAM STRUCTURE In C

In C programming, the structure of a program refers to how different parts


of the code are organized. A well-structured program is easier to write,
debug, and maintain. Understanding the basic structure helps in organizing
code into logical sections, making it more readable and efficient.

Basic Components of a C Program:


1. Preprocessor Directives:
These are the lines that start with #, like #include, and are processed
before the actual compilation. They include external libraries and define
constants.

Example:
#include <stdio.h> // Standard Input/Output functions

2. Global Declarations:
Variables and functions declared outside of all functions (including
main()) are considered global. Global variables can be accessed by any
function in the program.
3. The main() Function:
Every C program must have a main() function. This is the entry point of
the program, where execution begins. It can return an integer (typically 0
on successful completion) and includes the core logic of the program.
Example:
int main() {
// Program logic goes here
return 0;
}

4. Local Declarations:
Variables declared inside the main() function or any other function are
local. They are only accessible within that function.

5. Statements and Expressions:


These are the instructions that perform actions in the program, such as
calculations, input/output operations, or control statements (loops,
conditionals).

15
Programming With C 6. Functions (Optional):
In addition to main(), you can define your own functions to perform
specific tasks. These user-defined functions allow for modularity and
reusability of code.

Example of a Simple C Program Structure


Here’s a simple example demonstrating the basic structure of a C
program:
#include <stdio.h> // Preprocessor directive to include the standard I/O
library

// Function prototype (optional but useful for larger programs)


int add(int a, int b);

int main() { // Entry point of the program


int num1, num2, result;

// Input from the user


printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);

// Call the user-defined function


result = add(num1, num2);

// Output the result


printf("The sum is: %d\n", result);

return 0; // Indicate successful execution


}

// User-defined function to add two numbers


int add(int a, int b) {
16
return a + b; Introduction to Programming
In C

}
In this example:
 The #include <stdio.h> is a preprocessor directive.
 The main() function is the starting point, where we take input,
perform a calculation by calling the add() function, and print the
result.
 The add() function is an example of a user-defined function for
modularity.

1.9 COMPILATION AND EXECUTION OF A


PROGRAM
In C programming, writing the code is just the first step. After writing the
program, it needs to be compiled into machine-readable code and then
executed. The process involves several steps, starting with writing the
source code and ending with running the executable file. Understanding
the compilation and execution process is essential for debugging and
optimizing code.

Steps in Compilation and Execution:


1. Writing the Source Code:
The programmer writes the code in a text editor, saving it with a .c
extension. For example, program.c.

2. Preprocessing:
The preprocessor handles directives like #include and #define. It processes
these instructions before actual compilation, resulting in a modified source
file ready for compilation.

3. Compilation:
The compiler converts the preprocessed code into machine language,
generating an object file (with a .o or .obj extension). The compiler also
checks for syntax errors during this step. Example:
gcc -c program.c // Creates program.o

4. Linking:
The linker combines the object file with other necessary object files and
libraries to create a final executable file. If the program uses functions
from external libraries (like printf() from stdio.h), the linker ensures these
functions are linked to the program. Example:
gcc program.o -o program // Creates executable program

17
Programming With C 5. Execution:
Once the executable file is created, it can be run on the system. The
operating system loads the program into memory and starts executing the
instructions in the main() function. Example:
./program // Executes the program

Compilation Errors and Execution Errors


 Compilation Errors:
These occur when there are syntax errors in the code, such as missing
semicolons or incorrect variable declarations. The compiler will point out
these errors, and the code must be fixed before it can be compiled
successfully.

 Execution Errors (Runtime Errors):


These occur after the program has been successfully compiled and is
running. Examples include dividing by zero, accessing invalid memory, or
incorrect input data. These errors cause the program to behave
unexpectedly or crash during execution.

1.10 C CHARACTER SET


In C programming, the character set refers to the collection of valid
characters that can be used to write the source code. These characters
include letters, digits, and symbols that are used for writing variables,
keywords, operators, and more.
The C character set includes:
 Alphabets: Both uppercase (A-Z) and lowercase (a-z) letters.
 Digits: Numbers from 0-9.
 Special Symbols: Includes characters like +, -, *, /, =, (), {}, [], ;, ,,
etc.
 Whitespace Characters: These include spaces, tabs, newlines, and
other characters that help format the code but are not visible.

Identifiers in C:
Identifiers are the names given to various elements in a C program, such
as variables, functions, arrays, and structures. Identifiers must follow
certain rules to be valid in C.

Rules for Identifiers:


1. Must begin with a letter (A-Z or a-z) or an underscore (_).
2. Can contain letters, digits, and underscores, but cannot contain spaces
or special characters.
18
3. Cannot start with a digit. Introduction to Programming
In C

4. C is case-sensitive, so myVariable and myvariable are different


identifiers.
5. Identifiers should not be the same as C keywords.

Examples of valid identifiers:


 count
 total_sum
 _temp
 number1

Examples of invalid identifiers:


 1number (starts with a digit)
 total$sum (contains a special character $)
Keywords in C:
Keywords are reserved words in C that have special meanings and cannot
be used as identifiers. These keywords are part of the C language syntax
and are used to perform specific tasks or control the program's flow.

Some of the commonly used keywords in C include:


 Data types: int, float, char, double, void
 Control statements: if, else, while, for, switch, case
 Memory management: sizeof, return, break, continue
 Storage class specifiers: auto, static, extern, register
 Other keywords: const, volatile, typedef, enum, struct

1.11 INTRODUCTION TO DATA TYPES


In C programming, data types define the type of data a variable can hold.
They specify the amount of memory required and the range of values that
can be stored. Choosing the right data type is important for optimizing
memory usage and ensuring the correct handling of data.

Basic Data Types in C:


C provides several built-in data types. These are divided into primitive
data types (or basic data types) and derived data types.

19
Programming With C 1. Primitive Data Types:
 int: Used to store integers (whole numbers). It typically occupies 4
bytes of memory.
 float: Used for storing single-precision floating-point numbers
(decimal numbers). It typically occupies 4 bytes of memory.
 double: Used for storing double-precision floating-point numbers,
offering greater precision than float. It typically occupies 8 bytes of
memory.
 char: Used to store a single character. It typically occupies 1 byte of
memory.

Example:
int age = 20;
float price = 99.99;
double distance = 12345.6789;
char grade = 'A';
2. Derived Data Types: Derived types are based on primitive types but
are used for more complex data storage, such as arrays, pointers,
structures, and unions.

Sizes and Ranges of Data Types:


The size of data types in C may vary depending on the system architecture
(e.g., 32-bit or 64-bit). However, typical sizes and ranges are:

Data Type Size Range

int 4 bytes -2,147,483,648 to 2,147,483,647

float 4 bytes 3.4E-38 to 3.4E+38

double 8 bytes 1.7E-308 to 1.7E+308

char 1 byte -128 to 127 (or 0 to 255)

Modifiers:
C provides modifiers to change the size or range of basic data types.
Common modifiers include:
1. signed: Allows both positive and negative values.
2. unsigned: Only allows positive values but increases the range.
3. short: Reduces the size of the integer, usually 2 bytes.
20
4. long: Increases the size of the integer, usually 8 bytes. Introduction to Programming
In C

Examples:
unsigned int count = 5000; // Only positive integers
long int population = 7000000000; // Larger integer values

1.12 CONSTANTS AND ITS TYPES


A constant in C refers to a value that cannot be changed during the
execution of the program. Unlike variables, which can change their values,
constants remain fixed throughout. Constants are useful when you want to
ensure that certain values remain unchanged, like mathematical constants
(e.g., Pi) or fixed settings (e.g., maximum allowed value).

Types of Constants in C:
In C, constants can be of different types, based on the kind of value they
represent. These include:

1. Integer Constants:
Integer constants represent whole numbers (without any decimal points).
They can be written in three forms:
o Decimal: Base 10 numbers, like 100 or -42.
o Octal: Base 8 numbers, written with a leading 0 (e.g., 077).
o Hexadecimal: Base 16 numbers, written with a leading 0x
or 0X (e.g., 0x1A3).
Example:
const int maxScore = 100; // Integer constant
2. Floating-Point Constants
Floating-point constants represent numbers with a decimal point. They are
used for values that require precision, such as 3.14159.

Example:
const float pi = 3.14; // Floating-point constant

3. Character Constants:
Character constants are single characters enclosed in single quotes, like 'A'
or '5'. Each character constant has a corresponding ASCII value.

Example:
const char grade = 'A'; // Character constant

21
Programming With C 4. String Constants:
String constants are sequences of characters enclosed in double quotes,
like "Hello". String constants are stored as arrays of characters with a null
terminator (\0) at the end.

Example:
const char name[] = "Alice"; // String constant

5. Enumeration Constants:
Enumeration (or enum) constants define a set of named integer constants.
Each constant in an enum starts from 0 unless explicitly assigned a
different value.

Example:
enum days { MON, TUE, WED, THU, FRI }; // Enumeration
constants

Defining Constants in C:
In C, constants can be defined in two ways:

1. Using the const keyword:


This keyword is used to declare constants, ensuring that the value cannot
be modified after initialization.

Example:
const int maxSpeed = 120;

2. Using the #define preprocessor directive:


This is a preprocessor directive used to define symbolic constants, which
are replaced by the value throughout the code before compilation.

Example:
#define PI 3.14159

1.13 INTRODUCTION TO VARIABLES


In C programming, a variable is a named storage location in memory that
holds a value. Variables allow programmers to store, retrieve, and
manipulate data during the execution of a program. The value of a variable
can change throughout the program, making them a key element in any
computation.

22
Declaring and Initializing Variables: Introduction to Programming
In C

1. Declaration:
Before using a variable, it must be declared. A variable declaration
specifies the variable’s name and its data type (which defines what kind of
data it can hold).

Syntax:
data_type variable_name;

Example:
int age;
float price;
char grade;

2. Initialization:
Initialization means assigning an initial value to a variable at the time of
declaration.

Syntax:
data_type variable_name = value;
Example:
int age = 20;
float price = 99.99;
char grade = 'A';

Types of Variables:
Variables in C are classified based on where they are declared and how
they behave:

1. Local Variables:
o Declared inside a function or block.
o Accessible only within the function or block where they are defined.
o Automatically created when the function is called and destroyed when
the function exits.

Example:
void func() {
int num = 5; // Local variable

23
Programming With C }

2. Global Variables:
o Declared outside of all functions, usually at the top of the program.
o Accessible by all functions in the program.
o Global variables retain their values throughout the program's
execution.

Example:
int total = 100; // Global variable

void func() {
total = total + 10; // Modify global variable
}
3. Static Variables:
o Retain their value even after the function in which they are declared
has exited.
o Useful for preserving information between function calls.

Example:
void func() {
static int count = 0; // Static variable retains its value between calls
count++;
}

4. External Variables (Extern):


o Declared with the extern keyword to access global variables that are
defined in another file.
o Commonly used in multi-file programs.

Example:
extern int total; // Declare an external global variable

24
Scope and Lifetime of Variables: Introduction to Programming
In C

1. Scope:
The scope of a variable refers to the region of the program where the
variable can be accessed. Variables have either local scope (within a
function/block) or global scope (accessible anywhere in the program).

2. Lifetime:
The lifetime of a variable defines how long the variable exists in memory
during program execution. Local variables have a lifetime limited to the
execution of the function, while global and static variables exist for the
entire duration of the program.

SUMMARY
In this chapter, we explored the fundamentals of programming in C,
starting with the concept of algorithms, which are essential for solving
problems step-by-step. We then traced the history and significance of the
C programming language, emphasizing its role as a foundation for modern
languages.
We covered the structure of a C program, including its essential
components like the main() function, variables, and functions. Important
characteristics of a well-written program, such as correctness,
readability, efficiency, and maintainability, were discussed to guide the
writing of high-quality code. The compilation process was explained in
detail, highlighting the roles of the compiler, linker, and preprocessor,
which convert source code into executable files.
The chapter introduced key programming elements like pseudo code,
flowcharts, constants, variables, data types, and keywords, providing a
clear understanding of their purpose and usage in C. We also explored
how to declare and initialize variables, the different types of variables, and
their scope and lifetime.
Finally, we walked through the process of compiling and executing a C
program, ensuring a complete understanding of how to go from writing
code to running it successfully. These concepts form the building blocks
for more advanced programming in C, laying a strong foundation for
further learning.

QUESTIONS
1) What is an algorithm, and why is it important in programming?
2) Briefly describe the history of the C programming language.
3) What are the essential components of a C program’s structure?
4) What are the key characteristics of a well-written program?

25
Programming With C 5) Explain the role of the compiler, linker, and preprocessor in the C
compilation process.
6) What is pseudo code, and how is it useful in programming?
7) What is the difference between a constant and a variable in C?
8) What are the different data types available in C, and what are their
sizes?
9) Explain the concept of scope and lifetime of variables in C.
10) Outline the steps involved in writing, compiling, and executing a C
program.

*****

26
2
INTRODUCTION TO
PROGRAMMING IN C
Unit Structure
2.1 Introduction to Operators in C
2.2 Arithmetic Operators
2.3 Relational Operators
2.4 Logical Operators
2.5 Increment and Decrement Operators
2.6 Assignment Operators
2.7 The Conditional (Ternary) Operator
2.8 Order of Precedence and Associativity
2.9 Block Structure and Initialization
2.10 C Preprocessor
2.11 Summary
2.12 Questions

LEARNING OUTCOMES
 Understand and apply different types of operators in C, including
arithmetic, relational, and logical operators.

 Explain the difference between pre-increment/post-increment and pre-


decrement/post-decrement operations.

 Use assignment operators and compound assignment operators


effectively in expressions.

 Apply the conditional (ternary) operator for concise decision-making


in programs.

 Recognize the importance of operator precedence and associativity in


evaluating complex expressions.

 Use block structures to define scope and initialize variables within a


program.

 Understand the role of the C preprocessor and its features like macros,
conditional compilation, and file inclusion.
27
Programming With C  Write and evaluate expressions considering operator precedence and
order of evaluation to ensure correct program behaviour.

2.1 OPERATORS IN C
What is an Operator?
An operator in C is a symbol or keyword that tells the compiler to
perform specific mathematical, logical, or relational operations. Operators
are used in conjunction with operands (variables or values) to form
expressions. For example, in the expression a + b, + is the operator, and a
and b are the operands.
C provides a rich set of operators, allowing developers to perform various
tasks such as arithmetic calculations, comparisons, logical operations, and
more.

What is an Expression?
An expression is a combination of variables, constants, and operators that
produces a value. Expressions are evaluated to perform operations and
return results. For example, the expression a + b * c multiplies b and c,
then adds a to the result, following the rules of precedence.
Example:
int x = 5;
int y = 10;
int z = x + y; // Expression where + is the operator, x and y are operands
Here, x + y is an expression, and its result is stored in z.

Types of Operators in C
In C, operators are broadly categorized based on the type of operations
they perform. These categories include:
1. Arithmetic Operators: Perform basic mathematical operations like
addition, subtraction, multiplication, and division.
2. Relational Operators: Compare two values or variables and return a
boolean value (true or false).
3. Logical Operators: Used to perform logical operations, primarily in
decision-making (e.g., AND, OR, NOT).
4. Increment and Decrement Operators: Increase or decrease the
value of a variable by 1.
5. Assignment Operators: Assign values to variables. Includes simple
assignment and compound assignment operators.

28
6. Conditional (Ternary) Operator: A compact form of decision- Introduction to Programming
In C
making with the ? : syntax.
Each type of operator performs a specific role in manipulating data and
controlling the flow of a C program.

Importance of Operators and Expressions


Operators and expressions are fundamental to programming because they:
 Enable calculations and data manipulation.
 Allow for comparisons and decision-making.
 Control the flow of a program based on certain conditions.
 Help perform repetitive tasks like incrementing or decrementing
variables in loops.
By mastering operators and expressions, you can write more powerful and
efficient C programs that effectively manage data and handle logical
operations.

2.2 ARITHMETIC OPERATORS


Arithmetic operators in C are used to perform basic mathematical
operations on numerical values. These operators work with both integer
and floating-point data types. Arithmetic operations are commonly used in
programs for tasks such as calculations, counting, and other numerical
manipulations.
The following arithmetic operators are available in C:

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (remainder)

Addition (+)
The addition operator adds two operands together. It can be used with
integers, floating-point numbers, and even characters (as characters have
an ASCII integer value).
Example:
int a = 5;
29
Programming With C int b = 3;
int sum = a + b; // sum = 8

Subtraction (-)
The subtraction operator subtracts the second operand from the first. It is
also used with integers and floating-point numbers.
Example:
int x = 10;
int y = 4;
int difference = x - y; // difference = 6

Multiplication (*)
The multiplication operator multiplies two operands. It is commonly
used with integers and floating-point numbers.

Example:
int a = 7;
int b = 6;
int product = a * b; // product = 42

Division (/)
The division operator divides the first operand by the second. When both
operands are integers, the result is an integer (the fractional part is
discarded). For floating-point division, at least one of the operands must
be a floating-point number.

Example:
int a = 10;
int b = 3;
int quotient = a / b; // quotient = 3 (integer division)

Floating-point division:
float x = 10.0;
float y = 3.0;
float quotient = x / y; // quotient = 3.33 (floating-point division)

Modulus (%)

30
The modulus operator returns the remainder of a division between two Introduction to Programming
In C
integers. It is useful for determining if a number is even or odd, or for
cyclic operations.
Example:
int a = 10;
int b = 3;
int remainder = a % b; // remainder = 1
The modulus operator cannot be used with floating-point numbers.

Usage in Expressions:
Arithmetic operators can be combined in more complex expressions. C
follows the standard order of operations (also known as operator
precedence), which follows the rules of mathematics: parentheses first,
then multiplication and division, and finally addition and subtraction.

Example:
int result = (5 + 3) * 2 - 4 / 2; // result = 14

2.3 RELATIONAL OPERATORS


Relational operators in C are used to compare two values or expressions.
These operators evaluate relationships between operands and return a
boolean result (either true or false). In C, the result is represented by 1
(true) or 0 (false). Relational operators are crucial in decision-making and
conditional statements like if, while, and for.

List of Relational Operators:


The following are the relational operators available in C:

Operator Meaning Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

<= Less than or equal to a <= b

Equal to (==)
The equal to operator checks if two operands are equal. If they are, it
returns true (1); otherwise, it returns false (0).
31
Programming With C Example:
int x = 5, y = 5;
if (x == y) {
printf("x is equal to y\n");
}
In this example, since x is equal to y, the condition evaluates to true, and
the message is printed.

Not Equal to (!=)


The not equal to operator checks if two operands are not equal. It returns
true (1) if the values are different and false (0) if they are the same.

Example:
int a = 5, b = 10;
if (a != b) {
printf("a is not equal to b\n");
}
In this example, since a is not equal to b, the condition is true.

Greater Than (>)


The greater than operator checks if the left operand is greater than the
right operand. If it is, the result is true (1); otherwise, false (0).

Example:
int x = 8, y = 5;
if (x > y) {
printf("x is greater than y\n");
}
In this case, since x is greater than y, the condition is true.

Less Than (<)


The less than operator checks if the left operand is smaller than the right
operand. It returns true (1) if the left operand is less than the right operand
and false (0) otherwise.

32
Example: Introduction to Programming
In C

int a = 3, b = 7;
if (a < b) {
printf("a is less than b\n");
}
In this example, a is less than b, so the condition evaluates to true.

Greater Than or Equal To (>=)


The greater than or equal to operator checks if the left operand is either
greater than or equal to the right operand.

Example:
int x = 7, y = 7;
if (x >= y) {
printf("x is greater than or equal to y\n");
}
Since x is equal to y, the condition is true.

Less Than or Equal To (<=)


The less than or equal to operator checks if the left operand is either
smaller than or equal to the right operand.

Example:
int a = 4, b = 4;
if (a <= b) {
printf("a is less than or equal to b\n");
}
Here, since a is equal to b, the condition is true.

Using Relational Operators in Conditional Statements


Relational operators are commonly used in conditional statements like if,
while, or for loops. These operators help in controlling the flow of the
program based on comparisons.

Example:
int num = 10;
if (num > 5) {
33
Programming With C printf("Number is greater than 5\n");
}
In this case, the relational operator > is used to check if num is greater
than 5, allowing the program to print the message if the condition is true.

2.4 INTRODUCTION TO LOGICAL OPERATORS


Logical operators in C are used to perform logical operations on one or
more conditions or expressions. These operators are primarily used in
decision-making statements like if, while, and for loops, where multiple
conditions need to be evaluated together. Logical operators return a
boolean result: 1 for true and 0 for false.

List of Logical Operators


There are three main logical operators in C:

Operator Description Example

&& Logical AND (both true) (a > 0) && (b > 0)

|| Logical OR (Either true) (a>5) || (b<6)

! Logical NOT (negation) !(a > 0)

Logical AND (&&)


The logical AND operator returns true (1) only if both conditions are true.
If either or both of the conditions are false, the result is false (0).
Example:
int a = 5, b = 10;
if (a > 0 && b > 0) {
printf("Both a and b are positive.\n");
}
In this example, both a and b are positive, so the condition evaluates to
true, and the message is printed.

Logical OR (||)
The logical OR operator returns true (1) if at least one of the conditions is
true. It returns false (0) only if both conditions are false.
Example:
int a = -5, b = 10;
if (a > 0 || b > 0) {
34
printf("At least one of a or b is positive.\n"); Introduction to Programming
In C

}
Here, a is negative, but b is positive, so the condition is true, and the
message is printed.

Logical NOT (!)


The logical NOT operator is a unary operator that negates the condition.
If the condition is true, ! makes it false, and if the condition is false, !
makes it true.
Example:
int a = -5;
if (!(a > 0)) {
printf("a is not positive.\n");
}
In this case, a > 0 is false (since a is negative), but ! negates the result,
making the condition true, so the message is printed.

Using Logical Operators in Conditional Statements


Logical operators are often used in complex conditions where multiple
criteria need to be evaluated at once. They are frequently used in if, while,
and for loops.
Example:
int age = 20;
if (age >= 18 && age <= 25) {
printf("Eligible for the program.\n");
}
In this case, both conditions (age >= 18 and age <= 25) must be true for
the message to be printed, making the use of the && operator essential.

Short-Circuit Evaluation
C uses short-circuit evaluation with logical operators, meaning:
 In the case of &&, if the first condition is false, the second condition
is not evaluated because the whole expression cannot be true.
 In the case of ||, if the first condition is true, the second condition is
not evaluated because the whole expression is already true.

35
Programming With C Example:
int a = 0, b = 10;
if (a != 0 && b / a > 1) {
// This will not cause an error due to short-circuit evaluation
}
Here, since a != 0 is false, b / a > 1 is never evaluated, preventing a
division by zero error.

2.5 INCREMENT AND DECREMENT OPERATORS


The increment (++) and decrement (--) operators in C are used to
increase or decrease the value of a variable by 1, respectively. These
operators are frequently used in loops and other scenarios where values
need to be adjusted iteratively.
Both increment and decrement operators can be used in prefix or postfix
form, and understanding the difference between these two forms is
important for writing correct and efficient C code.

Increment Operator (++)


The increment operator (++) increases the value of a variable by 1. It can
be applied in two ways:
 Prefix (++variable): The value is incremented before it is used in an
expression.
 Postfix (variable++): The current value is used first, and then the
variable is incremented.

Example of Prefix Increment:


int x = 5;
int y = ++x; // x is incremented first, then y = 6
Example of Postfix Increment:
int x = 5;
int y = x++; // y = 5, then x is incremented to 6
In the prefix form, the variable is incremented before the expression is
evaluated, while in the postfix form, the expression is evaluated first, and
then the variable is incremented.

Decrement Operator (--)


The decrement operator (--) decreases the value of a variable by 1. Like
the increment operator, it can be used in both prefix and postfix forms.

36
Example of Prefix Decrement: Introduction to Programming
In C

int x = 5;
int y = --x; // x is decremented first, then y = 4

Example of Postfix Decrement:


int x = 5;
int y = x--; // y = 5, then x is decremented to 4
Again, in the prefix form, the variable is decremented before the
expression is evaluated, while in the postfix form, the expression is
evaluated first, and then the variable is decremented.

Using Increment and Decrement Operators in Loops


Increment and decrement operators are commonly used in loops,
especially in for and while loops, to update the loop counter.
Example using Increment Operator in a for loop:
for (int i = 0; i < 5; ++i) {
printf("%d ", i); // Output: 0 1 2 3 4
}
Example using Decrement Operator in a while loop:
int count = 5;
while (count > 0) {
printf("%d ", count); // Output: 5 4 3 2 1
count--;
}
In these examples, the increment and decrement operators efficiently
update the loop control variable.

Difference Between Prefix and Postfix Forms


1. Prefix (++x or --x): The variable is modified before the value is used
in the expression. It tends to be slightly faster because no temporary
copy of the variable is made.
2. Postfix (x++ or x--): The variable is modified after the value is used
in the expression. In this case, the current value is used, and then the
variable is incremented or decremented.
The choice between prefix and postfix depends on whether you need to
use the variable's value before or after modification in your program.

37
Programming With C
2.6 ASSIGNMENT OPERATORS
Assignment operators in C are used to assign values to variables. The
most basic assignment operator is the equals sign (=), which assigns the
value on the right to the variable on the left. C also provides compound
assignment operators that combine arithmetic or bitwise operations with
assignment.

Basic Assignment Operator (=)


The simple assignment operator (=) assigns the value of the right-hand
operand (an expression or constant) to the left-hand variable.
Syntax:
variable = value;
Example:
int a;
a = 10; // Assigns the value 10 to the variable a
Here, the value 10 is assigned to the variable a.

Compound Assignment Operators


Compound assignment operators perform an operation (such as addition
or multiplication) and then assign the result to the variable. They are a
shorthand for common operations and help reduce the length of the code.

Operator Example Equivalent to

+= a += b a=a+b

-= a -= b a=a-b

*= a *= b a=a*b

/= a /= b a=a/b

%= a %= b a=a%b

Examples of Compound Assignment Operators


1. Addition Assignment (+=):
int a = 5;
a += 3; // Equivalent to a = a + 3; a is now 8

2. Subtraction Assignment (-=):


int b = 10;

38
b -= 4; // Equivalent to b = b - 4; b is now 6 Introduction to Programming
In C

3. Multiplication Assignment (*=):


int x = 4;
x *= 2; // Equivalent to x = x * 2; x is now 8

4. Division Assignment (/=):


int y = 20;
y /= 5; // Equivalent to y = y / 5; y is now 4

5. Modulus Assignment (%=):


int z = 15;
z %= 4; // Equivalent to z = z % 4; z is now 3

Multiple Assignments in a Single Statement


C allows multiple variables to be assigned values in a single statement.
This can be done by chaining assignments.
Example:
int a, b, c;
a = b = c = 10; // Assigns 10 to a, b, and c
In this case, the value 10 is assigned to c, and then the same value is
assigned to b and a.

Order of Evaluation in Assignment


In C, assignment operators are evaluated right to left. This means that in
an assignment expression, the right-hand side is evaluated first, and then
the result is assigned to the variable on the left-hand side.

Example:
int a, b;
a = (b = 5) + 3; // First, b is assigned 5, then a is assigned 5 + 3, so a = 8

2.7 INTRODUCTION TO THE CONDITIONAL


(TERNARY) OPERATOR
The conditional operator, also known as the ternary operator, is a
compact way to perform conditional evaluations in C. It is the only
operator in C that takes three operands and is a shorthand for the if-else
statement. The conditional operator allows you to evaluate a condition and
choose one of two expressions to execute based on whether the condition
is true or false.

39
Programming With C Syntax of the Conditional Operator
The syntax of the ternary operator is:
condition ? expression1 : expression2;
 If the condition is true, expression1 is evaluated and returned.
 If the condition is false, expression2 is evaluated and returned.

Example of the Conditional Operator


1. Basic Example:
int a = 5, b = 10;
int max = (a > b) ? a : b; // max will be assigned the value of b (10)
In this example, the condition (a > b) is false, so b is assigned to max. If
the condition were true, a would have been assigned to max.
2. Another Example:
int num = 15;
char* result = (num % 2 == 0) ? "Even" : "Odd"; // Evaluates if num is
even or odd
Here, the condition checks if num is divisible by 2 (to determine whether
it's even). If true, "Even" is returned; otherwise, "Odd" is returned.

Using the Ternary Operator for Simple Decisions


The ternary operator is especially useful for simplifying simple decision-
making statements in a single line of code, which might otherwise
require an if-else block.
Example with if-else:
int a = 5, b = 10;
int min;
if (a < b) {
min = a;
} else {
min = b;
}
Equivalent using the Ternary Operator:
int a = 5, b = 10;

40
int min = (a < b) ? a : b; // A shorter version of the if-else statement Introduction to Programming
In C

Nesting the Ternary Operator:


Just like if-else statements, the ternary operator can be nested for
evaluating multiple conditions. However, it is recommended to avoid
over-nesting the ternary operator, as it can make the code harder to read.

Example of Nested Ternary Operator:


int a = 10, b = 20, c = 5;
int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
// Finds the largest of a, b, and c
In this example, the ternary operator is nested to find the maximum of
three numbers.

Limitation of the Ternary Operator:


While the ternary operator is a compact alternative to if-else, it is best used
for simple conditions. For complex conditions or multiple operations,
using if-else statements is preferred to ensure readability and
maintainability of the code.

2.8 INTRODUCTION TO OPERATOR PRECEDENCE


AND ASSOCIATIVITY
When writing expressions in C, multiple operators are often used together.
Operator precedence defines the order in which operators are evaluated
in an expression. Associativity defines the direction (left-to-right or right-
to-left) in which operators with the same precedence are evaluated.
Understanding operator precedence and associativity is crucial for writing
correct and predictable expressions.

Operator Precedence:
Operator precedence determines which operators are evaluated first when
there are multiple operators in a single expression. Operators with higher
precedence are evaluated before those with lower precedence.
For example, in the expression:
int result = 5 + 3 * 2;
Here, the multiplication operator (*) has higher precedence than the
addition operator (+), so 3 * 2 is evaluated first, making the expression
equivalent to 5 + 6, which results in 11.

Operator Precedence Table:


The following table lists common operators in C, ordered from highest
precedence to lowest precedence:

41
Programming With C Precedence Operators Associativity

1 (), [], ->, . Left-to-right

2 ++, --, + (unary), - (unary), !, Right-to-left


~

3 *, /, % Left-to-right

4 +, - Left-to-right

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

6 ==, != Left-to-right

7 && Left-to-right

8 `

9 ?: (conditional) Right-to-left

10 =, +=, -=, *=, /=, etc. Right-to-left

This table helps determine the order in which operations are performed
when evaluating an expression.

Associativity:
When two operators with the same precedence appear in an expression,
the associativity rule determines the order in which the operators are
evaluated.
 Left-to-right associativity: Operators are evaluated from left to right.
 Right-to-left associativity: Operators are evaluated from right to left.
Example of Left-to-Right Associativity:
int result = 10 - 5 + 2;
Here, subtraction and addition have the same precedence, and because
they are left-associative, the expression is evaluated from left to right: 10 -
5 = 5, then 5 + 2 = 7.

Example of Right-to-Left Associativity:


int a = 10;
int b = 20;
int c = 30;
a = b = c; // Right-to-left associativity: first b = c, then a = b

42
In this case, the assignment (=) operator is right-associative, so b is Introduction to Programming
In C
assigned the value of c first, and then a is assigned the value of b.

Overriding Precedence with Parentheses:


To control the order of evaluation explicitly, parentheses can be used.
Operators within parentheses are evaluated first, regardless of their
precedence.
Example:
int result = (5 + 3) * 2; // Parentheses change the order of evaluation
Here, the addition is evaluated first because of the parentheses, making the
result 8 * 2 = 16.

Common Mistakes with Precedence and Associativity:


One of the most common mistakes is misunderstanding how operators are
evaluated, leading to unexpected results. For example:
int result = 5 + 3 * 2; // Without understanding precedence, one might
expect 16
In reality, the multiplication happens first, resulting in 5 + 6 = 11. To get
the expected result, you must use parentheses.

2.9 BLOCK STRUCTURE


A block in C is a group of statements enclosed within curly braces {}.
Blocks allow you to group multiple statements together to be treated as a
single unit of execution. Block structures are essential for defining the
scope of variables, organizing code, and controlling the flow of execution
in functions, loops, and conditional statements.

Block Structure in C:
In C, blocks are used in functions, loops, conditionals, and other control
structures. Every block has its own scope, meaning that variables declared
inside a block are only accessible within that block and not outside of it.
Example of Block Structure:
int main() {
int a = 10; // 'a' is declared inside this block and cannot be accessed
outside
if (a > 5) {
int b = 20; // 'b' is only accessible inside this if block
printf("%d\n", b); // Prints 20
}
43
Programming With C // 'b' cannot be accessed here
return 0;
}
In this example, the variable b is declared inside the if block and cannot be
accessed outside of it.

Scope of Variables in Blocks:


Variables declared inside a block are called local variables and are only
accessible within that block. Once the block is exited, these variables are
destroyed, and their memory is freed.
Example:
int main() {
int x = 10;
{
int y = 20; // 'y' is local to this block
printf("%d\n", y); // Output: 20
}
// 'y' is not accessible here, only 'x' is
printf("%d\n", x); // Output: 10
return 0;
}
In this case, y is only accessible within the inner block, while x is
accessible throughout the main function.

Variable Initialization:
Initialization is the process of assigning an initial value to a variable at
the time of declaration. It's a good practice to initialize variables when
they are declared, as uninitialized variables may contain garbage values.
Example:
int a = 5; // Initialized with value 5
float b = 10.5; // Initialized with value 10.5

Initialization in Loops and Conditional Blocks:


Variables can be initialized inside loops or conditional blocks, but their
scope will be limited to that block.

44
Example in a Loop: Introduction to Programming
In C

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


printf("%d\n", i); // 'i' is initialized and used within the loop
}
In this example, i is initialized within the for loop and is only accessible
inside the loop. It is automatically destroyed once the loop is finished.

Best Practices for Block Structure and Initialization


1. Use blocks to manage scope: Keep variables in the smallest possible
scope to avoid conflicts and make the code easier to understand.
2. Always initialize variables: Initializing variables helps prevent
unexpected behaviors caused by uninitialized memory (garbage
values).
3. Limit scope in loops and conditionals: Define variables inside loops
or conditionals only if they are needed exclusively within that block.

2.10 C PREPROCESSOR
The C preprocessor is a tool that processes your program before it is
compiled. It performs various text substitutions in the source code and
handles directives that begin with the # symbol. These directives can
include files, define constants, and manage conditional compilation. The
preprocessor helps optimize the code and make it more maintainable and
portable.
The preprocessor does not produce machine code; instead, it prepares the
code for compilation by handling specific tasks like file inclusion, macro
expansion, and conditional compilation.

Common Preprocessor Directives:


Here are some of the most commonly used preprocessor directives in C:

Directive Description

#include Includes the contents of a file (usually a header file) into the
program.

#define Defines a macro or constant that can be used throughout the


program.

#undef Undefines a macro that was previously defined.

#ifdef Checks if a macro is defined.

#ifndef Checks if a macro is not defined.

45
Programming With C #endif Ends an #ifdef or #ifndef block.

#include Directive
The #include directive is used to include the contents of one file into
another file. This is commonly used to include standard library header
files or user-defined header files.
There are two types of file inclusion:
1. Standard library inclusion (uses angle brackets <>):
#include <stdio.h> // Includes the standard input/output library
2. User-defined file inclusion (uses double quotes ""):
#include "myheader.h" // Includes a user-defined header file

#define Directive
The #define directive is used to create symbolic constants or macros that
represent expressions. This allows for more readable and maintainable
code.

Example of defining a constant:


#define PI 3.14159
Here, the preprocessor replaces every occurrence of PI with 3.14159
before compilation.

Example of defining a macro:


#define SQUARE(x) ((x) * (x))
This macro expands any usage of SQUARE(x) to replace it with the value
of x * x.

#ifdef, #ifndef, and #endif Directives


The #ifdef and #ifndef directives allow conditional compilation, which
means certain sections of the code can be compiled or excluded based on
whether a macro is defined or not.
 #ifdef: Compiles the block if the macro is defined.
 #ifndef: Compiles the block if the macro is not defined.
 #endif: Marks the end of the conditional block.

Example:
#define DEBUG

46
#ifdef DEBUG Introduction to Programming
In C

printf("Debugging is enabled.\n");
#endif
In this example, the printf() statement is included in the compilation only
if DEBUG is defined. If DEBUG is undefined, the block is skipped.

#undef Directive
The #undef directive is used to undefine a macro that was previously
defined. This is useful when you want to stop using a particular macro at
some point in the program.

Example:
#define MAX 100
#undef MAX
After #undef MAX, any further use of MAX will result in a compilation
error unless it is redefined.

Conditional Compilation:
The preprocessor supports conditional compilation, which allows you to
compile certain parts of the code based on specific conditions. This is
particularly useful for platform-specific code or debugging purposes.

Example:
#ifdef WINDOWS
printf("Running on Windows.\n");
#else
printf("Running on a non-Windows system.\n");
#endif
Here, if WINDOWS is defined, the code for Windows is compiled;
otherwise, the non-Windows code is compiled.

Advantages of the C Preprocessor:


The C preprocessor provides several advantages:
 Code reusability: Using macros and header files makes code modular
and reusable.
 Simplified code: By using macros, constants, and file inclusion, the
code becomes more concise and easier to maintain.

47
Programming With C  Conditional compilation: Enables code to be written for multiple
platforms or configurations without duplicating the entire codebase.
 Enhanced debugging: Conditional compilation can be used to
include or exclude debugging code.

2.11 SUMMARY
In this chapter, we explored various types of operators and expressions
used in C programming. Starting with an introduction to operators, we
learned that operators perform specific tasks on variables and constants.
The chapter covered arithmetic operators like addition, subtraction,
multiplication, division, and modulus, which are used for basic
mathematical operations.
Next, we explored relational operators such as ==, !=, >, <, >=, and <=
that compare values and are crucial for decision-making in programs.
Logical operators like &&, ||, and ! were introduced, enabling the
combination of multiple conditions for evaluation. We also covered
increment and decrement operators (++ and --), which are used to
increase or decrease the value of variables by one.
The chapter then introduced assignment operators, which assign values
to variables, including simple and compound assignment operators. We
also discussed the conditional (ternary) operator, which provides a
concise way to evaluate conditions and choose between two expressions.
We explored operator precedence and associativity, which dictate the
order in which operators are evaluated in complex expressions. To manage
multiple operations and ensure the correct execution, we learned how to
control this order using parentheses.
The chapter also covered the concept of block structure, explaining how
blocks define variable scope and control the flow of code, as well as the
importance of initializing variables. Finally, we learned about the C
preprocessor, which handles tasks like file inclusion, macro definitions,
and conditional compilation to make code more efficient and adaptable.

2.12 QUESTIONS
1) What are arithmetic operators in C, and how are they used in
expressions?
2) Explain relational operators and give an example of how they are used
in decision-making.
3) Describe the logical operators in C and how they help combine
conditions in a program.
4) What is the difference between the prefix and postfix forms of the
increment and decrement operators? Provide examples.

48
5) Explain the purpose of assignment operators and provide examples of Introduction to Programming
In C
both basic and compound assignment operators.
6) How does the conditional (ternary) operator work? Give an example.
7) What is operator precedence, and how does it affect the evaluation of
expressions in C?
8) What is a block in C, and how does it define the scope of variables?
9) Why is it important to initialize variables? Provide an example.
10) What are the functions of the C preprocessor, and how do #include
and #define directives work?

*****

49
3
CONTROLS IN C
Unit Structure
3.0 Objective
3.1 Branching/Decision making
3.1.1 if statement
3.1.2 if else statement
3.1.3 nested if else statement
3.1.4 switch statement
3.2 Loops
3.2.1 while loop
3.2.2 for loop
3.2.3 do while loop
3.2.4 Differentiate between while and do while loop
3.3 Jump Statements
3.3.1 continue statement
3.3.2 break statement
3.3.3 return statement
3.3.4 goto statement
3.4 Miscellaneous Programs
3.5 Summary
3.6 Unit End Questions

3.0 OBJECTIVE
This chapter will help you understand the following concepts:
 Designing programs that use decision structures and loops
 How decision-making processes work
 Efficiently executing a series of statements repeatedly

50
Controls In C
3.1 BRANCHING/DECISION MAKING
Decision making in programming refers to the process of choosing
between different paths or actions based on certain conditions. It involves
evaluating a set of conditions or criteria to determine which course of
action to take.
This is typically implemented using control structures such as if, else,
switch, and case statements. Decision-making allows a program to
respond to various inputs or situations dynamically, enabling it to perform
different operations depending on the given conditions.
The decision making statements supported by c are as follows:
● if statement
● if else statement
● Nested if else statement
● switch statement

3.1.1 if statement:
Like many programming languages, C uses the keyword if to perform
decision-making. The general structure of an if statement is as follows:

if (condition) {
// Code to run if the condition is true }
If the condition is true, the code inside the curly brackets will run; if the
condition is false, nothing will happen.

Example:-
Write an Program In C to check Wether The No Is A Zero Or A Non
Zero Number
Here's a simple C program that checks whether a number is zero or non-
zero:

51
Programming With C Explanation:
1. Input: The program asks the user to enter a number.
2. Condition: It checks if the entered number is zero using if (number
== 0).
3. Output:
o If the condition is true, it prints "The number is zero."
o If the condition is false, it prints "The number is non-zero."

3.1.2 If else statement:


An if-else statement allows you to execute certain blocks of code based on
whether a condition evaluates to true or false. This control structure helps
you make decisions and execute different parts of code accordingly.

Syntax:-
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

Example:-
#include <stdio.h>
int main() {
int number = 10;

if (number > 0) {
printf("The number is positive.\n");
} else {
printf("The number is non-positive.\n");
}
return 0;
}

52
Output: Controls In C

When you run this program, the output will be:


The number is positive.

Explanation
 The variable number is initialized to 10.

 The if statement checks if number > 0. Since 10 is greater than 0, the


condition evaluates to true.

 Therefore, the code inside the if block executes, printing "The


number is positive."

 The else block is not executed because the if condition was true.

 This program is a simple demonstration of using if-else statements


to control the flow based on a condition.

3.1.3 Nested –if –else statements:


In C programming, you can always nest if-else statements. This means
you can place one if or else-if statement inside another. "Nesting" simply
means putting one programming element inside another similar one, like
loops or conditional statements. When you use an if statement within
another if statement, it’s called a nested if statement. This allows for more
complex decision-making in your code.

Syntax:
if (condition1) {
if (condition2) {
// Code to execute if both conditions are true
} else {
// Code to execute if condition1 is true and condition2 is false
}
} else {
// Code to execute if condition1 is false
}
Example: Write a program to determine if a given number is less than
100, between 100 to 200, or above 200.

53
Programming With C Algorithm:
Here’s the algorithm for the given C program that checks the value of the
variable a:

Algorithm
1. Start
2. Declare an integer variable a.
3. Initialize a to 277
4. Print the value of a.
5. Check if a is less than 100:
o If true, print "Value of a is less than 100."
6. Check if a is between 100 and 200 (inclusive of 100):
o If true, print "Value of a is between 100 and 200."
7. Check if a is greater than or equal to 200:
o If true, print "Value of a is more than 200."

8. End
This algorithm outlines the flow of the program and how it evaluates the
value of a to provide appropriate output messages.

Program: P.T.O

54
Output: Controls In C

Example 2: Write a C program to check if a given year is a leap year


or not
Algorithm: Here’s the algorithm for the given C program that checks if a
year is a leap year:

1. Start
2. Declare an integer variable year.
3. Initialize year to 2023.
4. Print the value of year.
5. Check if year is divisible by 4:
o If true:
 Check if year is divisible by 100:
 If true:
 Check if year is divisible by 400:
 If true, print "year is a Leap Year."
 If false, print "year is not a Leap
Year."
 If false, print "year is a Leap Year."
o If false, print "year is not a Leap Year."

6. End
This algorithm outlines the logic used to determine if the specified year is
a leap year based on the rules of the Gregorian calendar.

55
Programming With C Program:-

output:

3.1.4 Switch statement


The switch statement in C allows you to execute different parts of code
based on the value of a variable or expression. It is often used as a cleaner
alternative to multiple if-else statements when dealing with multiple
discrete values.

Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1

56
break; Controls In C

case value2:
// Code to execute if expression equals value2
break;
// You can have any number of case statements
default:
// Code to execute if expression doesn't match any case
}
Here’s a simple example of using a switch statement.

Example :-Write a program to print all the days of the week using
with statement
Algorithm:
Here’s the algorithm for a program that uses a switch statement to
determine the name of the day based on an integer input:

1. Start
2. Declare an integer variable day1.
3. Initialize day1 to a specific value (e.g.,5).
4. Print the value of day.
5. Evaluate day using a switch statement:
o Case 1: If day is 1, print "Monday."
o Case 2: If day is 2, print "Tuesday."
o Case 3: If day is 3, print "Wednesday."
o Case 4: If day is 4, print "Thursday."
o Case 5: If day is 5, print "Friday."
o Case 6: If day is 6, print "Saturday."
o Case 7: If day is 7, print "Sunday."
o Default: If day does not match any case (1-7), print "Invalid
day."

6. End
.

57
Programming With C P.T.O
Program:

Output:

Explanation
 Expression: The value of day is evaluated in the switch.
 Case Statements: Each case represents a possible value of day. If day
matches a case, the corresponding block of code is executed.
 Break Statement: The break statement prevents fall-through to
subsequent cases. Without it, execution would continue into the next
case block.

58
 Default Case: The default case executes if none of the specified cases Controls In C

match, serving as a catch-all.

Iteration statements:
We can create loops using iteration statements causes embedded
statements to be executed a number of times, subject to the loop
termination criteria. These statements are executed in order, expect the
jump statement is encountered.

3.2 LOOPS
Loops are used to repeat a block of code multiple times until a certain
condition is met. There are three main types of loops in C: while, for, and
do while.

3.2.1 While loop:


The while condition continues to execute as long as a specified condition
is true ,that means the condition will be repeated as long as the condition
is true.

Syntax:-
while (condition) {
// Code to execute repeatedly
}
Here is an example which explains while loop working in detail.

Example:4.3.1 Write a program for counting from 1 to 5 using while


loop in C
Program:

59
Programming With C Output:

Algorithm: Here’s the algorithm for counting from 1 to

1. Start
2. Choose a Loop Type (While, For, or Do While)

3. If Using While Loop:


o Declare an integer variable count and initialize it to 1.
o While count is less than or equal to 5:
 Print the value of count.
 Increment count by 1.

3.2.3 do while loop:


The do {} while statement allows a loop to continue whilst a condition
evaluation as TRUE (non zero value)

Syntax:
do {
// Code to execute
} while (condition);
Explanation:
 do: This keyword begins the loop.
 Code to execute: This block of code will run at least once.
 while (condition): After executing the code block, the loop checks
the condition. If the condition is true, the loop repeats; if false, the
loop ends.

60
Example:4.3.2 Here’s a simple example of a do while loop: Controls In C

Program

Output: Here is the output for the provided do while loop example is:

Algorithm: If Using Do While Loop:


 Declare an integer variable count and initialize it to 1.
 Do:
o Print the value of count.
o Increment count by 1.
 While count is less than or equal to 5.
 End
3.2.4 Difference between do while and while statements:
The do statement is similar to the while statement except that its
termination condition is at the end of the body of the loop only. If we want
to execute the body of the loop at least once, regardless of the condition,
then we have to use do construct with while

For Loop:-
The ‘for loop’loops from one number to another number and increases by
a specified value each time.
61
Programming With C Syntax:
For (initialization; condition; step)
{
Statements;
}
Here

 Setting a loop counter to an intial value(initialization)

 Testing the Loop (condition)

 Increasing /decreasing the value of loop counter(step)


Example: Write a program to print from 5 to 10 nmubers

Output:

Example 2: Program that initializes an integer and uses a for loop to print
the numbers from 1 to 10.

62
Algorithm Controls In C

1. Start
2. Declare an integer variable start.
3. Initialize start to 1.
4. For Loop:
o Set i to start (1).
o Continue Looping while i is less than or equal to 10:
 Print the value of i.
 Increment i by 1.

5. End
Program

Output:-

63
Programming With C
3.3 JUMP STATEMENTS
Jump statements in C are commands that allow you to transfer the flow of
control in a program. These statements are used for branching Here are the
main types:
3.3.1 break: This statement is used to exit a loop or switch statement
early.
For example, if you’re in a loop and want to stop when a certain
condition is met, you can use break.
Syntax:- break;
3.3.2continue: This statement skips the current iteration of a loop and
moves to the next one. It is used as a combination with for and while
statements. If you want to skip some code in a loop but keep going, you
use continue.
Syntax:- continue;
3.3.3goto: This statement jumps to a specific label in your code. It can
make the flow of your program less clear, so it’s generally best to use it
sparingly.
Syntax:
{
…….
goto label;
……..
……..
label;
statements;
}
3.3.4 return: This statement exits a function and can also send a value
back to the part of the program that called the function.

Syntax
return; // To exit a function without returning a value
// or
return expression; // To exit a function and return a value

64
Uses: Controls In C

 Control Flow: Jump statements help manage how and when certain
parts of your code run.
 Exiting Loops: They can help exit loops based on conditions.
 Skipping Iterations: You can skip certain steps in loops without fully
exiting.
 Function Returns: They help end functions and send results back.

3.4 MISCELLANEOUS PROGRAMS


1. Program to display if the number is negative or not

Output:

2. Program to relate two integers using =,>or < symbol.

65
Programming With C

Output:

3.5 SUMMARY
Lesson Summary: Control Statements in C
In this lesson, we explored control statements in C, which are essential for
directing the flow of a program. We covered the following key concepts:
1. Conditional Statements:
o if statement: Executes a block of code if a condition is true.
o if-else statement: Provides an alternative block of code if the
condition is false.
o switch statement: Allows multi-way branching based on the
value of a variable.
o Nested if statements: Allow you to check multiple conditions
within another if statement, enabling more complex decision-
making in your code.

66
2. Looping Statements: Controls In C

o for loop: Executes a block of code a specific number of times.


o while loop: Continues to execute as long as a condition is true.
o do-while loop: Similar to the while loop, but it guarantees at least
one execution of the code block.
3. Jump Statements:
o break: Exits a loop or switch statement.
o continue: Skips the current iteration of a loop and proceeds to the
next one.
o goto: Jumps to a labeled statement (use sparingly for clarity).
o return: Exits a function and optionally returns a value.

Key Takeaways:
 Control statements enable decision-making and repetition in
programs, making them more dynamic.
 Understanding how to use these statements effectively is crucial
for writing efficient and clear C code.

3.6 UNIT END QUESTIONS


1. What is the difference between an if statement and a switch
statement?
2. Describe the two different forms of if-else statements ?How do they
differ?
3. How does a for loop differ from a while loop in C?
4. Explain what a nested if statement is and provide an example?
5. What happens if the condition in a while loop is never true?
6. How does the break statement affect the flow of a loop?
7. What are the potential downsides of using the goto statement in a
program?
8. How can you skip the current iteration of a loop using a control
statement?

3.7 ACTIVITY
while Loop
[A] What would be the output of the following programs:

67
Programming With C (a) main( )
{
int j ;
while ( j <= 10 )
{
printf ( "\n%d", j ) ;
j=j+1;
}
}

(b) main( )
{
int i = 1 ;
while ( i <= 10 ) ;
{
printf ( "\n%d", i ) ;
i++ ; } }

(c)
main( )
{
int j ;
while ( j <= 10 )
{
printf ( "\n%d", j ) ;
j=j+1;
}
}
(d)

68
main( ) Controls In C

{
int x = 1 ;
while ( x == 1 )
{
x=x-1;
printf ( "\n%d", x ) ;
}
}

[B] Attempt the following:


1. Write a program to calculate overtime pay of 10 employees. Overtime
is paid at the rate of Rs. 12.00 per hour for every hour worked above
40 hours. Assume that employees do not work for fractional part of an
hour.
2. Write a program to find the factorial value of any number entered
through the keyboard.
3. Two numbers are entered through the keyboard. Write a program to
find the value of one number raised to the power of another.
4. Write a program to print all the ASCII values and their equivalent
characters using a while loop. The ASCII values vary from 0 to 255.

3.7 REFERNCES
1. www.tutorialspoint.com
2. www.geeksforgeeks.org
3. www.programiz.com
4. Let Us C by Yeshwant Kantekar
5. C Programming Language, 2nd edition

*****

69
4
BASICS OF FUNCTION
Unit Structure
4.1 Objective
4.2 Introduction
4.3 User Defined and Library functions:
4.4 Syntax for the User defined functions:
4.4.1 Function Prototype
4.4.2 Function Definition Parameters
4.4.2.1 Actual Arguments
4.4.2.2 Formal Arguments
4.4.3 Function Call
4.5 Global and local variables
4.6 Calling a function by passing values
4.7 Calling a function by passing references
4.8 Return type
4.9 Recursion
4.9.1 Advantages
4.9.2 Disadvantages
4.9.3 Program implementation and explation
4.10 Summary
4.11 Unit End Questions
4.12 Reference for further reading

4.1 OBJECTIVE
After studying functions we will be able to undesrtand the followins:
1. To understand the concept of functions in C programming.
2. To understand how to properly declare and define a function.
3. To understand the distinction between global and local variables.
70
4. To understand the difference between call by value and call by Basics of Function

reference.
5. To understand Tackle problems through the use of recursion.
6. To understand what a recursive function is and the advantages it
offers.

4.2 INTRODUCTION
A function is a self-contained block of statements designed to carry out a
specific task. You can think of any C program as a collection of these
functions. Utilizing a function is akin to hiring someone to perform a
particular job; sometimes, the interaction is straightforward, while at other
times, it can be quite complex. The use of function is to makes
programming easier since repeated statements can be grouped into
functions and then we can make the reference to them by just name of the
function(i.e by calling the functions)
If the program contains more lines then splitting the program into
functions makes the program more readable, testable and maintainable
.Every C program must include a single main function, along with any
additional functions defined or used by the programmer.

4.3 USER DEFINED AND LIBRARY FUNCTIONS:


In C programming, functions can be classified into two main categories:
user-defined functions and library functions.

4.3.1 Library Function:


Library functions are predefined functions provided by the C standard
library. These functions cover a wide range of tasks, from mathematical
calculations to input/output operations and string handlings. Using library
functions can significantly reduce development time, as they are optimized
and thoroughly tested.
These functions are defined in the header files.When we define them in
the headers, these functions are available for use in the code written by
the user.
Eg:- printf() is a standard library function to display output on the screen
of the user. This function is predefined in the library function “stdio.h”.

4.3.2 User Defined Function:


C language allows the programmer to define their own functions. Such
functions which are created by the user are called user defined functions.
They enhance code reusability and organization by allowing the developer
to break down complex problems into manageable components.
The programmer creates functions to do specific tasks that match the
needs of the application. Thus depending on the complexity and
71
Programming With C requirement these functions can be created by the user. The user can create
one or more functions to to match the required output.

4.3.2.1 Advantages of User-Defined Functions


1. User-defined functions allow you to break your code into smaller,
manageable pieces. Each function can handle a specific task, making
your code easier to read and understand.
2. Once you define a function, you can use it multiple times throughout
your program. This saves time and reduces code duplication.
3. When a function has a specific job, it’s easier to find and fix errors.
You can test each function separately to ensure it works correctly.
4. In team projects, different programmers can work on different
functions at the same time without interfering with each other’s code.
Hence large projects can be divided amazon many programmers.
5. If you need to change how a specific task is done, you only need to
update the function. This keeps your code clean and makes future
updates simpler.

4.4 SYNTAX FOR THE USER DEFINED FUNCTIONS:-


How to use User-Defined Functions in C?
To use a user-defined function, we first have to understand the different
parts of its syntax. The user-defined function in C can be divided into
three parts:

1. Function Prototype
2. Function Definition
3. Function Call
4.4.1 Function Prototype:
A function prototype is also known as a function declaration which
specifies the function’s name, function parameters, and return type. The
function prototype does not contain the body of the function. It is
basically used to inform the compiler about the existence of the user-
defined function which can be used in the later part of the program.
Syntax:
/*function prototype*/

return_type function_name (type1 arg1, type2 arg2, ... typeN argN);


We can also skip the name of the arguments in the function prototype.
/*function call in main*/

72
function _name() Basics of Function

/*function definition*/

return_type function_name (type1 , type2 , ... typeN);


{
/*Statements*/
}
Here return_type represents that data type of the item that is returned by
the function,
function_ name represents the name of the function , and type1,type 2
,......typen represents the data type of argos 1,args 2….. Argsn.

Prototype of function
In C programming language every function must be written to return a
specific TYPE of information and to accept specific types of data as
parameters. This information is communicated to the compiler via a
function prototype.
A prototype can occur at the top of the C source code file and it describes
what the function returns and what it takes as a return type and what will
be the parameter list. If functions is declared at the top of the file, the
function prototype should be followed by a semicolon.

Return type/statement:
A function may return a value. The return_type is normally the data type
of the value the function returns. Functions mostly perform the desired
operation without returning a value. In this case, the return_type is the
keyword void.
4.4.1 Function Call:
In C programming, a calling function refers to a function that invokes or
calls another function. When a calling function executes a function call,
control is transferred to the called function, which performs its operations
and then returns control back to the calling function. Once the function
ending or closing braces are reached then also the controls will be returned
to the main function.
To call a function in C, follow these simple steps:
1. Define the Function: Create the function you want to call.
2. Call the Function: Use the function's name followed by parentheses.

73
Programming With C Lets study with the help of an example.

Steps Explained:
● Define: void sayHello() { ... } defines what the function does.
● Call: sayHello(); is how you call the function to execute its code.
This message is printed to the console because the sayHello function is
called within the main function, which executes the printf statement inside
sayHello(). Here the function name is sayHello.
4.4.2 Function Parameters:
Function calls occur when the calling function
Invokes another function.When the function name is followed by a
semicolon,the complier calls these functions
Ex : function(param1,param2,param3);

4.4.3.1 Actual Argument:


The arguments that are stated or Used inside the call to the function are
called “real arguments “ and copies of these are provided to the function.
This can be expressed as constants, expression or function call, as given
below:
sample(t);
samplet(11,22);
sample(2,3,sum(t,s));
4.4.3.2 Formal arguments:
Formal arguments often called as dummy arguments, are the arguments
that are mentioned in the function definition.
These parameters are only used to store copies of the values that 0the
caller function sent when invoking the function. Similar to other local

74
variables. These arguments created at the beginning of the functions call Basics of Function

and discarded at its conclusion.


The order number and ghe type of the Formal arguments should match the
order and type of the real parameters in the function call.
Program for function with arguments and no return value in C
programming
In C programming, a function can accept arguments and have no return
value by using the void return type. Here's a simple example that shows a
function accepting arguments but returning nothing

Output:

In C language normally every program has global and local variables. Lets
study them one by one.

4.5 GLOBAL AND LOCAL VARIABLES IN C


A global variable is declared outside of any function, typically at the top
of the file or beginning of the program. Global variables are accessible
from any function within the same file (and from other files if declared
with extern).They exist for the entire duration of the program's execution.

75
Programming With C Local Variables in C:
A local variable is declared within a function, and its scope is limited to
that function. Local variables can only be accessed within the function
they are declared in. They exist only while the function is executing.

4.6 CALLING A FUNCTION BY PASSING VALUES


In C, when you pass an argument to a function by value, you are passing a
copy of the variable's value. This means changes made to the parameter
inside the function do not affect the original variable.
Here's a simple example that demonstrates a function call by value:

● Output:
● Before function call: originalValue = 5
● Inside modifyValue: num = 15
● After function call: originalValue = 5
Explanation:
1. Function Declaration: void modifyValue(int num) declares a
function that takes an integer argument.
2. Modification: Inside the function, we modify the local copy of the
variable.

76
3. Main Function: Basics of Function

○ We declare and initialize originalValue.


○ We print its value before the function call.
○ After calling modifyValue(originalValue), we print the value
again.
4. Output: You will see that originalValue remains unchanged after the
function call, demonstrating that it was passed by value.

4.7 CALLING A FUNCTION BY PASSING REFERENCE


In C, call by reference allows you to pass the address of a variable to a
function, enabling the function to modify the original variable's value.
This is typically done using pointers.
Here's an example that demonstrates call by reference in C:

Program for call by reference in C

Output:

Explanation:
1. Function Declaration: void modifyValue(int *num) declares a
function that takes a pointer to an integer.

77
Programming With C 2. Modification: Inside the function, we use *num to access and modify
the value at the address that num points to.
3. Main Function:
● We declare and initialize originalValue.
● We print its value before the function call.
● We pass the address of originalValue to modifyValue using the
address-of operator &.
● After the function call, we print the value again to see the change.
4. Output: You will see that originalValue is modified after the function
call, demonstrating that it was passed by reference.
Difference between call by reference and call by value in C

Here’s a concise differentiation between call by value and call by


reference in C:

Call by Value
1. Definition: A copy of the actual parameter's value is passed to the
function.
2. Effect on Original Variable: Changes made to the parameter inside
the function do not affect the original variable.
3. Memory Usage: Uses more memory for large data types since a copy
is created.
4. Syntax: You pass the variable directly to the function.

Call by Reference
1. Definition: The address of the actual parameter is passed to the
function, allowing direct access to the original variable.
2. Effect on Original Variable: Changes made to the parameter inside
the function affect the original variable.

78
3. Memory Usage: More efficient for large data types since no copy is Basics of Function

created.
4. Syntax: You pass the address of the variable using the & operator

4.8 RETURN TYPE


It is used to return value to the calling function. It can be used in two way
as return Or return(expression);

Ex:-
return (a);
return (a*b);
return (a*b+c);
Here the 1st return statement used to terminate the function without
returning any value
The void keyword, used in the previous examples, indicates that the
function should not return a value. If you want the function to return a
value, you can use a data type (such as int or float, etc.) instead of void,
and use the return keyword inside the function:
Ex:- /*summation of two values*/

Output

79
Programming With C
4.9 RECURSION
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems
which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out
how it works is to experiment with it
Adding two numbers together is easy to do, but adding a range of numbers
is more complicated. In the following example, recursion is used to add a
range of numbers together by breaking it down into the simple task of
adding two numbers:

Output

4.9.1 Advantages of Recursion:


1. Simplicity: Easier to understand for complex problems.
2. Less Code: Can write shorter, cleaner code.
3. Problem Breakdown: Naturally divides problems into smaller parts.
4. Algorithm Clarity: Expresses certain algorithms more clearly.
5. Automatic State Management: Handles function states without extra
code.

4.9.2 Disadvantages of Recursion:


1. Stack Overflow: Can crash if too many recursive calls are made.
2. Performance Cost: Slower due to overhead from multiple function
calls.
80
3. High Memory Use: Uses more memory because of the call stack. Basics of Function

4. Harder to Debug: Tracking issues can be more complicated.


5. No Tail Call Optimization: May not run efficiently if not designed
properly.

4.9.3 Program implementation and explanation:


Program for factorial of a number using recursive function

Output:

Explanation:
1. Function Definition: factorial(int n) computes the factorial. If n is 0,
it returns 1 (base case). Otherwise, it returns n * factorial(n - 1)
(recursive case).
2. Main Function: It prompts the user for input, checks for negative
numbers, and then calls the factorial function to compute and display
the result.
You can compile and run this program to calculate the factorial of any
non-negative integer.

81
Programming With C
4.10 SUMMARY
1. A function is a block of code designed to perform a specific task. It
helps organize code, improve readability, and enable code reuse.
2. Before using a function, it must be declared. This tells the compiler
about the function's name, return type, and parameters.
3. To use a function, you call it by its name followed by parentheses,
passing any required arguments.
4. The type of value that a function returns. If no value is returned, use
void.
5. Parameters are variables listed in the function's declaration and
definition. Arguments are the actual values passed to the function
when it is called.
6. Local variables are defined within a function and can only be
accessed there.
7. Global variables are defined outside all functions and can be accessed
by any function.
8. A function can call itself, either directly or indirectly. This is known
as recursion, useful for solving problems that can be broken down into
smaller sub-problems.
9. Scope refers to the visibility of variables. Local variables are visible
only within their function, while global variables can be accessed
throughout the program.

4.11 UNIT END QUESTIONS


1:-Insert the missing part of the code below to output "Hello World!".
int ()
{
("Hello World!");
return 0;
}
2:-Create a function named myFunction and call it inside main().
void () {
printf("I just got executed!");
}

82
int main() { Basics of Function

return 0;
}
1. What are functions ? Explain the Library and user defined
Functions?
2. What are function parameters? Write a short note?.
3. Write a short note on recursion ?
4. What are global and local variables?

4.12 REFERENCE FOR FURTHER READING


1. www.tutorialpoint.com
2. www.geeksofgeeks.com
3. www.programiz.com
4. www.guru99.com
5. Let us.C with yashwant kantekar

*****

83
5
POINTERS AND ADDRESSES
Unit Structure
5.1 Objectives
5.2 Introduction
5.3 Concept of a Pointer
5.4 Rules for assigning pointers
5.5 Declaration of Pointer variables
5.5 Initialization of Pointer Variables
5.6 Arrays
5.8 Declaration of array
5.9 Single dimension array
5.10 Multidimensional Array
5.11 Pointers to Function
5.12 Functions returning Pointers
5.13 Expected Questions
5.15 Summary
5.14 References

5.1 OBJECTIVES
1. To understand the relationship between arrays and pointers
2. To understand the design and concepts behind pointer arithmetic
3. To write programs using arrays and pointer arithmetic
4. To better understand the design behind passing arrays to functions
5. To understand the C implementation of dynamic memory
6. To write programs using static and dynamic memory allocation
7. To understand and implement ragged arrays (arrays of pointers)

84
Pointers And Addresses
5.2 INTRODUCTION
A pointer is a variable that contains the address of another variable of the
same data type; it is also referred to as a locator or indication that directs
to the address of a value. A pointer is a derived data type in C
programming.

Pointer offer a number of benefits to the programmers:-


1. They are more efficient in handling arrays and data tables.
2. Pointers support dynamic memory allocation.
3. They can be used to return multiple values from a function via
function.
4. Pointers reduce the length and the complexity of the code/programs.
5. Pointers permit the reference to the function and thereby facilitate the
passing of the parameters.
6. The use of pointers arrays to character strings results in saving of data
storage space in memory
Let's consider the computer memory just like a sequential collection of
cell as shown below in the diagram each cell commonly known as a byte
has a unique address associated with it. Typically the addresses are
numbers consequently starting from zero onwards full stop the last address
depends on the memories the system allocates somewhere in the memory
appropriate location to hold the value of the variable. Every cell has a
unique address; this location will have its own address.

5.3 CONCEPT OF A POINTER


When we declare a variable, the system allocates a space in the memory
location for it to store its value. This location will have its own address.
Now assume that the system allocates memory location 55A for the
variable named testVar
Int testVar=100;
Now we can access the value associated with the variable either by using
name testVar or by Using the address 55A.
As the memory address are just numbers,they can be assigned to the other
variables easily.These variables which hold the memory address are called
the pointer variables.
Apointer variable is simply a variable that contains the address of another
variable.

85
Programming With C

The value of a pointer variable is stored in yet another memory location.

The following program explain the above above memory allocation

86
OUTPUT Pointers And Addresses

Here the “0x7ffda3ac95f4”is the memory address allocated to the pointer


myAge and the value of the pointer is 43 .
A pointer is a variable that stores the memory address of another variable
as its value. A pointer variable points to a data type (like int) of the same
type, and is created with the * operator. The address of the variable you
are working with is assigned to the pointer:

5.4 RULES FOR ASSIGNING POINTER


Pointer Rules are very simple and easy to understand and work with.
These rules can be combined to obtain the complex results.

1. Pointers and Pointees:


Every pointer stores a reference to something. A pointer stores a reference
to a value or memory location called as pointee.

87
Programming With C 2. Dereferencing:
The dereference operation starts at the pointer and follows its arrow over
to access its pointee. The goal may be to look at the pointee state or to
change the pointee state.
The dereference operation on a pointer only works if the pointer has a
pointee -- the pointee must be allocated and the pointer must be set to
point to it. The most common error in pointer code is forgetting to set up
the pointee. The most common runtime crash because of that error in the
code is a failed dereference operation. In Java the incorrect dereference
will be flagged politely by the runtime system. In compiled languages
such as C, C++, and Pascal, the incorrect dereference will sometimes
crash, and other times corrupt memory in some subtle, random way.
Pointer bugs in compiled languages can be difficult to track down for this
reason.

3. Pointer Assignment:
Pointer assignment between two pointers makes them point to the same
pointee. So the assignment y = x; makes y point to the same pointee as x.
Pointer assignment does not touch the pointees. It just changes one pointer
to have the same reference as another pointer. After pointer assignment,
the two pointers are said to be "sharing" the pointee.

5.5 DECLARATION OF POINTER VARIABLES


In C programming, you can declare and initialize pointer variables to store
memory addresses. Here’s how you can declare and initialize pointer
variables:

Declaration of Pointer Variables:


The syntax of a pointer declaration is,

data_type *pointer_name;

88
data type of the pointer must be the same as the variable, which the pointer Pointers And Addresses

is pointing to . A void type pointer works with all types of data types,but it
is generally not used.
To declare a pointer variable, you use the asterisk (*) symbol followed by
the variable name. The type of the pointer must match the type of the
variable it will point to.
int *ptr; // Pointer to an integer
float *ptr_f; // Pointer to a float
char *ptr_c; // Pointer to a character

5.6 INITIALIZATION OF POINTER VARIABLES


Following is the syntax used for initializing the pointer variable in C.

pointer =&variable;
Pointers are always initialized before using in the program.
In the process of initialization the address of a variable is assigned to a
pointer variable. In the C language addresses operator & is used to
determine the address of the variable associated with it. Pointer variables
can be initialized to the memory address of another variable or to NULL.
Initializing a pointer variable to NULL indicates that it does not point to
any valid memory address.
int x = 10; // Variable ‘x’ of type integer
int *ptr; //Pointer initialization
ptr=&x;
or int *ptr=&x // initialization and declaration together//
Initialization of pointer can be done using the following 4 steps:-
1. Declare a pointer variable and note down the data type
2. Declare another variable with the same data type as that of the pointer
variable.
3. Initialize an ordinary variable and assign some value to it.
4. Now initialize pointer by assigning the address of ordinary variable to
pointer.
Here is an example for the intializing the integer Pointer

Example
/Program for intailizing Integer Pointer/

89
Programming With C

output

Dereferencing of pointer:
The pointer points to a memory location where data is stored that can be
accessed or modified.
The value of the variable it points to will be immediately impacted by any
operations performed on the dereferenced pointer.
//Program for dereferencing of the pointer/

90
Output: Pointers And Addresses

Output

Arrays:
An array is a collection of similar type variables accessed using a numeric
index, written in square brackets after the array name. An array is a
variable that can store multiple values.For example, if you want to store
100 integers, you can create an array for it.

Here int is the data type , data is the name of the array and square brackets
specify the array size . the elements will be sequentially stored and the
index will specify the position. starting from 0 to n-1.Arrays are stored in
continuous memory locations and can be single or multidimensional.

91
Programming With C Declaring single dimension arrays:
Its simple to create the single dimension array, it is just like a row of n
columns where each column is accessed with the zero base index. It is also
known as the linear array, in which accessing the elements using single
subscript which can either be row or column index
Syntax:-Type arrayname[size];
For example,
int mark[5];
Here, we declared an array, and its size is 5, its name is marks. Meaning, it
can hold 5 values.
It's important to note that the size and type of an array cannot be changed
once it is declared.
char arr[5];
here character string will be declared.

Single Dimension Array elements in memory


int num[4];

int num[]={12.13.14.15};

Memory representation of 15bit and 32 bit data type

92
may vary system to system. Pointers And Addresses

// Program to find the largest value that is stored in the array//

Output

Multidimensional Arrays;
A multidimensional array is also called a rectangular array with more than
one dimension. The form of a multidimensional array is a matrix.

Syntax : Type arrayname[rows][columns];


Eg int arr[2][2]; char arr[2][2];
//Program for Printing Elements of Two-dimensional Array//

93
Programming With C

Output:

Pointers to Functions:
The addresses of the arguments given during a function call, are stored in
a pointer that is a function argument. The another name for this call by
reference, as we pass a reference the original value is altered. The value
which is altered is the address. Since the real and the formal parameters in
this case share the same address space , any value changes made inside
the function will be reflected in outside it as well.
//*Program to demonstrate the use of the pointers to function*//
#include<stdio.h>
void demo(int a)
{
Printf(“a=%d\n”,a);
94
} Pointers And Addresses

int main()
{ void (*f)(int)=&demo;
(*f)(10);
return 0;
}
Output
Value=10

5.13 EXPECTED QUESTIONS


1. What is pointer in c programming? What are its benefit?
Pointer is a user defined data type that creates special types of variables
which can hold the address of primitive data type like char, int, float,
double or user defined data type like function, pointer etc. or derived data
type like array, structure, union, enum.

Examples:
int *ptr;
int (*ptr)();
int (*ptr)[2];

Benefits of using pointers are:-


1) Pointers are more efficient in handling arrays and data tables.
2) Pointers can be used to return multiple values from a function via
function arguments.
3) The use of pointer arrays to character strings results in saving of data
storage space in memory.
4) Pointers allow C to support dynamic memory management.
5) Pointers provide an efficient tool for manipulating dynamic data
structures such as structures, linked lists , queues , stacks and trees.
6) Pointers reduce length and complexity of programs.
7) They increase the execution speed and thus reduce the program
execution time.

95
Programming With C 2. Explain the concept of pointers?
In C programming every variable keeps two type of values.
1. Value of variable.
2. Address of variable where it has stored in the memory.
(1) Meaning of following simple pointer declaration and definition:
int a=5;
int * ptr;
ptr=&a;

Explanation:
About variable “a” :
1. Name of variable: a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory: 1025 (assume)
About variable “ptr” :
4. Name of variable: ptr
5. Value of variable which it keeps: 1025
6. Address where it has stored in memory: 5000 (assume)
After this we have to draw the representation diagram for the same

5.14 SUMMARY
1. A pointer is a variable that stores the address of another variable.
2. Syntax:

 Declaration: datatype *pointer_name;

 Initialization: pointer_name = &variable; (where & is the


address-of operator).
3. Dereferencing:

Use the * operator to access or modify the value at the address the pointer
points to. For example, *pointer_name gives you the value stored at
that address.

96
4. Pointer Arithmetic: Pointers And Addresses

You can perform arithmetic operations on pointers (e.g., incrementing a


pointer to point to the next memory location of the data type it points to).

5. Functions like malloc(), calloc(), and free() are used for


managing memory dynamically. Pointers are essential for using these
functions.
6. Arrays are closely related to pointers. The name of an array acts like a
pointer to its first element, and you can manipulate arrays using
pointer arithmetic.
7. Pointers can also point to functions, allowing for more flexible code
and the ability to pass functions as arguments.

5.15 UNIT END QUESTIONS


Q.1 What is a pointer? Explain the benefits of pointer?
Q.2 Explain the pointer rules?
Q3. How to declare and initialise a pointer?
Q4. Write a short note on pointer address operator?
Q5. What are the ways of declaring pointer variable?
Q5. Explain pointer address arithmetic
Q7. Write a short note on assigning pointer and references
Q8. Write a short note in incrementing and incrementing pointer with
suitable example?
Q9. Write a short note on pointer and array?
Q10 Write a short note on multi dimensional arrays?
Q11. Write a short note on single dimensional array?
Q12. What is array write a short note on function pointers?

5.15 REFERENCES
1. www.guru99.Com
2. www.tutorialpoint.com
3. www.geeksofgeeks.com
4. Let let us Yashwant Kanetkar

*****
97
6
USER DEFINED DATA TYPES
Unit structure
6.1 Objective
6.2 Introduction
6.3 Basics of structure
6.4 Declaring structure variable
6.4.1 First way
6.4.2 Second way
6.5 Initializing structure
6.5.1. Declare and initialize
6.5.2. Declaring and initializing multiple variables
6.5.3.Initializing single member variable
6.5.4.Initializing inside the main
6.6 Union in C programming
6 .7 Syntax for Declaring a C union
6.8 Unions inside structure
6.9 Structures inside Unions
6.10 Summary
6.11 Unit end exercises
6.12 References

6.1 OBJECTIVES
1. To understand the organization of data.
2. To understand the reuse of code
3. To understand how to save Memory

98
User Defined Data Types
6.2 INTRODUCTION
The categories of data that a programming language can keep in memory
are called data types. In essence, data types are used to specify the kind of
information that can be stored in a variable. Certain operations can be
carried out on these data kinds, and they have varying memory
requirements. Three categories can be used to broadly categorize these
data types:

 Primitive Data Types

 Derived Types

 User Defined Data Types

6.3 BASIS OF STRUCTURE


Structure:- A structure is a user defined data type. The structure is a
collection of different types of data types grouped together and each
element of the structure is called as a member.
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.
A structure is a collection of one or more data items of different data
types, grouped together under a single name. Variables inside the structure
are called members of structure. Each element of a structure is called a
member. struct keyword is used to define/create a structure. struct define a
new data type which is a collection of different type of data.

Syntax
struct structure_name /tag name
{
data_type member1;
data_type member2;
.
.
data_type member n;
};
Note: Don't forget the semicolon }; in the ending line.e.

99
Programming With C Example
struct employee
{ int id;
char name[50];
float salary;
};
Here, struct is the keyword, employee is the tag name of structure; id,
name and salary are the members or fields of the structure. Let's
understand it by the diagram given below:

@javatpoint

Syntax to create structure variable


struct tagname/structure_name variable;

6.4 DECLARING STRUCTURE VARIABLE


We can declare variable for the structure, so that we can access the
member of structure easily.

There are two ways to declare structure variable:


1. By struct keyword within main() function/ Declaring Structure
variables separately
2. By declaring variable at the time of defining structure
/ Declaring Structure Variables with Structure definition

6.4.1 First way:


Let's see the example to declare structure variable by struct keyword. It
should be declared
within the main function.

100
struct employee { User Defined Data Types

int id;
char name[50];
float salary;
};
Now write given code inside the main() function.

struct employee e1, e2;


6.4.2 Second way:
Let's see another way to declare variables at the time of defining structure.

struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
We can declare multiple variables by comma directly after closing the
curly brace.

6.5 IMPORTANT POINT FOR DECLARING


STRUCTURE VARIABLE
1. The closing braces of the structure declaration should always be
followed by a semicolon.
2. We shouldn’t forget to use the ‘struct’ keyword for declaring
structures.
3. The memory space will not be allocated just by declaring structures.
4. Inorder that the memory should be allocated to the structure we
should define it by writing as i.e mystruct s1;
5. It is not necessary to declare all the members of the structure.
6. For larger programs structure should be embedded in the separate
header file.
7. Structure need not be globally defined they can be written inside the
MaIns
8. Initializing the structure
We can initialize the structure variable in different ways.
101
Programming With C 6.5.1 Declare and initialize:
struct employee
{char name[30];
int employeeid;
float salary;}dept1={“Shlok”,21,200000};
In the above example, we have seen structure is declared and as soon as
after declaration we have initialized the structure variable.
dept1={“Shlok”,21,98,2};
This is the code for initializing structure in C programming language:

6.5.2 Declaring and initializing multiple variables


struct employee
{char name[30];
int employeeid;
float salary;}
dept1={“Shlok”,21,20000};
dept2={“Asmi”,26,25000};
In this example we have studied that we can declare two structure
variables in the above code. After the declaration of the variable we have
initialized two variables.
Example.
dept1={“Shlok”,21,20000};
dept2={“Asmi”,26,25000};

6.5.3 Initializing single member variable:


Even if there are three members of structure, only one is initialized then
remaining members are initialised with zero. The variables of other data
type will be initialized as given below

Data type Default value if not initialized


Integer 0
Float 0.00
Char NULL

102
6.5.4 Initializing inside the main: User Defined Data Types

When we declare the structure then memory will not be elected for that
structure. Only declaring a statement will never allocate memory. We need
to initialize variables to allocate some memory to the structure. The
example for initializing inside the main is given as follows
struct student
{
int marks1;
int marks2;
int marks3;
};
void main()
{
Struct students s1={23,25,26};
—-----
—-----
—------
};
When we declare a structure then memory won't be allocated for structure.
It will be allocated once we start writing the above declaration statements
struct student
{
int marks1;
int marks2;
int marks3;
};
We need to initialize structure variables to allocate memory to the
structure.
struct students s1={23,25,26};
Let's understand structure with a simple example.
#include<stdio.h>

103
Programming With C struct student {
int id;
char *name
float percentage;
}student 1;
Int main ()
{
Struct student st;
Student1.id=1;
Student1.name=”Shlok”;
Student1.percentage=98.9;
Printf(“ID is: %d \n”,student1.id);
Printf(“Name is: %d \n”,student1.name);
Printf(“Percentage is: %d \n”,student1.percentage);
getch();
return 0;
}

OUTPUT:
ID is : 1
Name is Shlok
Percentage is: 98.9

6.6 UNION IN C PROGRAMMING


Union is a user defined datatype in C programming language. It is a
collection of variables of different datatypes in the same memory location.
We can define a union with many members, but at a given point of time
only one member can contain a value. Unions can be very handy when
you need to talk to peripherals through some memory mapped registers.

Need for Union in C programming:


C unions are used to save memory. To better understand an union, think of
it as a chunk of memory that is used to store variables of different types.
When we want to assign a new value to a field, then the existing data is
replaced with new data.
104
C unions allow data members which are mutually exclusive to share the User Defined Data Types

same memory. This is quite important when memory is valuable, such as


in embedded systems. Unions are mostly used in embedded programming
where direct access to the memory is needed

Difference between structure and union:


The main difference between structure and a union is that Structs allocate
enough space to store all of the fields in the struct. The first one is stored
at the beginning of the struct, the second is stored after that, and so on.
Unions only allocate enough space to store the largest field listed, and all
fields are stored at the same space .

6.6 SYNTAX FOR DECLARING A C UNION


Syntax for declaring a union is same as that of declaring a structure except
the keyword struct
union union_name
{
datatype field_name;
datatype field_name;
// more variables
};
Note : Size of the union is the the size of its largest field because
sufficient number of bytes must be reserved to store the largest sized field.
To access the fields of a union, use dot(.) operator i.e., the variable name
followed by dot operator followed by field name.

105
Programming With C
6.7 INITIALIZING UNIONS
The difference between structure and union when their initialization is
given below.

Output:

The fields of a union cannot be initialized all at once. For a structure


variable the output is fine but for the union variable the answer does not
seem to be correct because union can hold single value for a member at a
time i.e., the data is over-written in the memory. Obviously the use case
we have chosen is not suited for union but only struct. This example is
only to demonstrate the behavior of union and structure.

6.8 UNIONS INSIDE STRUCTURE


In the below code, we have union embedded within a structure. We know,
the fields of a union will share memory, so in the main program we ask the
user which data he/she would like to store and depending on the user
choice the appropriate field will be used. By this way we can use the
memory efficiently.

106
User Defined Data Types

output:

6.9 STRUCTURES INSIDE UNIONS


Example for defining a structure inside union is given below:

107
Programming With C Output

6.10 SUMMARY
Let’s try to revise what we understood after reading the chapter
1. User-defined functions are custom functions created by the
programmer to perform specific tasks, enhancing code modularity and
reusability.
2. Syntax: Functions are defined using the following structure:
c
Copy code
return_type function_name(parameter_type
parameter_name) {
// function body
}
3. Before using a function, you can declare it (function prototype) to
specify its return type and parameters, allowing for flexibility in
calling it before its definition.
4. Functions can take parameters (input values) that allow them to
operate on different data. Parameters are specified in the function
definition, while arguments are the actual values passed during a
function call.

5. Functions can return values using the return statement. If a


function does not return a value, its return type should be declared as
void.

6. Variables defined within a function are local to that function and


cannot be accessed outside of it, helping to manage variable scope and
memory effectively.

108
User Defined Data Types
6.11 QUESTIONS
1. Write a short note of C structures.
2. What are the various ways to initialize the structures?
3. Explain nested structures with suitable example?
4. How to access the member of structure?
5. Write short note on Union?
6. How to declare a union in C programming language?
6. How to access the union in c programming?

6.12 REFERENCES
1. Let Us C by Yashavant Kanetkar
2. www.javatpoint.com
3. www.geeksofgeeks.com
4. https://www.w3schools.com/c/

*****

109

You might also like