Programming With C
Programming With C
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.
Published by
Director
Centre for Distance and Online Education, University of Mumbai,
Vidyanagari, Mumbai - 400 098.
1. Introduction to Programming in C 1
2. Introduction to Programming in C 27
3. Controls in C 50
4. Basics of Function 70
*****
Major Courses
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
Programming With C Identify desirable program characteristics and apply them to improve
code quality.
Apply typedef to create new data types and use typecasting for
conversions.
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.
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.
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.
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.
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.
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.
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
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);
// Main function
int main() {
int num1, num2, sum; // Local variable declarations
9
Programming With C
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.
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.
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.
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).
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
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.
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.
}
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.
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
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.
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.
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
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:
Example:
const int maxSpeed = 120;
Example:
#define PI 3.14159
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++;
}
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.
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.
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
== Equal to a == b
!= Not 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.
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.
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.
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.
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.
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.
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.
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.
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.
36
Example of Prefix Decrement: Introduction to Programming
In C
int x = 5;
int y = --x; // x is decremented first, then y = 4
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.
+= 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
38
b -= 4; // Equivalent to b = b - 4; b is now 6 Introduction to Programming
In C
Example:
int a, b;
a = (b = 5) + 3; // First, b is assigned 5, then a is assigned 5 + 3, so a = 8
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.
40
int min = (a < b) ? a : b; // A shorter version of the if-else statement Introduction to Programming
In C
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.
41
Programming With C Precedence Operators Associativity
3 *, /, % Left-to-right
4 +, - Left-to-right
6 ==, != Left-to-right
7 && Left-to-right
8 `
9 ?: (conditional) 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.
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.
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.
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
44
Example in a Loop: Introduction to Programming
In C
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.
Directive Description
#include Includes the contents of a file (usually a header file) into the
program.
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:
#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.
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."
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
Explanation
The variable number is initialized to 10.
The else block is not executed because the if condition was true.
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
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:
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
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.
Syntax:-
while (condition) {
// Code to execute repeatedly
}
Here is an example which explains while loop working in detail.
59
Programming With C Output:
1. Start
2. Choose a Loop Type (While, For, or Do While)
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:
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
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.
Output:
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
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.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 ) ;
}
}
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.
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*/
72
function _name() Basics of Function
/*function definition*/
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);
74
variables. These arguments created at the beginning of the functions call Basics of Function
Output:
In C language normally every program has global and local variables. Lets
study them one by one.
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.
● 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
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
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
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
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.
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?
*****
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.
85
Programming With C
86
OUTPUT Pointers And Addresses
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.
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
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.
int num[]={12.13.14.15};
92
may vary system to system. Pointers And Addresses
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.
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
Examples:
int *ptr;
int (*ptr)();
int (*ptr)[2];
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:
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
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:
Derived Types
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
100
struct employee { User Defined Data Types
int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
We can declare multiple variables by comma directly after closing the
curly brace.
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
105
Programming With C
6.7 INITIALIZING UNIONS
The difference between structure and union when their initialization is
given below.
Output:
106
User Defined Data Types
output:
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.
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