0% found this document useful (0 votes)
8 views132 pages

A Quick Notes On C Programming

This document is a comprehensive guide to C programming, covering topics such as the structure of C programs, data types, operators, arrays, strings, user-defined functions, structures, unions, pointers, dynamic memory allocation, and file management. It serves as a quick reference for both beginners and experienced programmers, detailing essential concepts and practical examples. The content is organized into sections that facilitate easy navigation and understanding of C programming principles.

Uploaded by

shruti2023pandey
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)
8 views132 pages

A Quick Notes On C Programming

This document is a comprehensive guide to C programming, covering topics such as the structure of C programs, data types, operators, arrays, strings, user-defined functions, structures, unions, pointers, dynamic memory allocation, and file management. It serves as a quick reference for both beginners and experienced programmers, detailing essential concepts and practical examples. The content is organized into sections that facilitate easy navigation and understanding of C programming principles.

Uploaded by

shruti2023pandey
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/ 132

1

A Quick Notes on

C Programming

A Quick Notes on C Programming -By Nilotpal Bhandary

September 2024
A Quick Notes on C Programming 2

Contents
Contents 3
1. Introduction to C Programming 9
1. Overview of C Programming Language 9
2. Why Learn C? 9

Y
2. The Structure of the C Programming 10
3. Structure of a C Program 10

AR
3. Getting Started With DevC++ 18
4. Constants, Variables and Data Types 22
1. Constants In C 22

D
2. Variables in C 23
3. Data Types in C 24

AN
4. Memory Size of Data Types 25
5. Storage Classes 27
1. auto Storage Class 27
BH
2. register Storage Class 28
3. static Storage Class 29
4. extern Storage Class 31
5. Operators 33
AL

1. Arithmetic Operators 33
2. Relational Operators 34
3. Logical Operators 35
TP

4. Bitwise Operators 36
5. Assignment Operators 37
6. Increment and Decrement Operators 39
O

7. Miscellaneous Operators 39
6. Expressions 43
IL

Components of an Expression 43
1. Arithmetic Expressions 43
N

2. Relational Expressions 43
3. Logical Expressions 44
4. Assignment Expressions 44
5. Conditional Expressions (Ternary Operator) 45
6. Increment/Decrement Expressions 45
7. Bitwise Expressions 45
Operator Precedence Table (in descending order of precedence): 46

2
A Quick Notes on C Programming 3

Type Conversion in C 48
1. Implicit Type Conversion (Automatic Type Conversion) 48
2. Explicit Type Conversion (Type Casting) 49
7. Decision Making and Branching in C 53
1. if Statement 53
2. if-else Statement 54
3. else-if Ladder 55
4. Nested if Statement 57

Y
5. switch Statement 58
6. Conditional (Ternary) Operator 59

AR
7. “goto” Statement 61
8. Array 63
1. What is an array in C? 63

D
2. How do you declare and initialize an array in C? 63
3. How do you access elements of an array? 64

AN
4. What happens if you access an array out of its bounds? 64
5. How do you find the size of an array in C? 64
Types of Multidimensional Arrays 65
BH
6. What is a multidimensional array? 65
Two-Dimensional (2D) Arrays in C 65
7. How do you access elements in a 2D array? 66
8. How do you pass an array to a function? 66
AL

9. What is the difference between an array and a pointer? 67


10. How do you copy elements of one array to another in C? 68
11. What are the limitations of arrays in C? 68
TP

12. How is a string represented as an array in C? 69


13. Can you change the size of an array once it is declared? 69
14. How do you sort an array in C? 69
O

9. String 71
1. What is a string in C? 71
IL

2. How do you declare and initialize a string in C? 71


3. How do you print a string in C? 71
N

4. How do you read a string input from the user in C? 72


4. How do you read a line(including white space) from the user in C? 72
6. How do you find the length of a string in C? 73
7. How do you copy one string to another in C? 74
8. How do you concatenate two strings in C? 74
9. How do you compare two strings in C? 75
10. What does the null character '\0' do in a string? 75

3
A Quick Notes on C Programming 4

11. How do you reverse a string in C? 76


12. What are common string functions in <string.h>? 76
13. How can you check if a string is empty in C? 77
14. How do you convert a string to uppercase or lowercase in C? 77
15. How do you find a substring within a string? 78
16. How does strcmp function work? 78
How strcmp Works Internally 79
Example of strcmp 79

Y
Explanation of Results 80
Note 80

AR
Examples of Lexicographical Order 80
10. User-defined function 81
1. What is a user-defined function in C? 81

D
2. Why do we use user-defined functions? 81
3. How do you declare a user-defined function in C? 81

AN
4. How do you define a user-defined function in C? 82
5. How do you call a user-defined function in C? 82
6. What are the components of a function in C? 83
BH
7. Can a function return more than one value? 83
8. What is the difference between void and other return types? 83
9. Can you pass an array to a function? How? 83
10. What is recursion? 84
AL

11. What is the scope of a function parameter? 85


12. What is a function prototype, and why is it needed? 85
13. What is the difference between actual and formal parameters? 85
TP

14. Can you nest functions in C? 86


15. What is a function pointer? 86
11. Structure and Unions 87
O

1. What is a structure in C? 87
2. How do you declare and define a structure? 87
IL

3. How do you access members of a structure? 87


4. Can structures in C contain other structures? 88
N

5. What is the difference between structure declaration and structure definition? 88


6. How do you pass a structure to a function? 89
7. Can you use an array within a structure? 89
8. What is typedef and how is it used with structures? 90
9. How is memory allocated for a structure? 90
10. Can you compare two structures directly using == or !=? 90
11. Can you initialize a structure at the time of declaration? 91

4
A Quick Notes on C Programming 5

12. What is a self-referential structure? 91


13. Can structures contain functions in C? 91
14. What is a bit field in a structure? 92
15. What is the size of a structure? 92
16. Can you use pointers with structures? 92
17. What is the purpose of the . and -> operators with structures? 92
18. Can structures be assigned directly in C? 93
19. Can structures be used with dynamic memory allocation? 93

Y
20. What are the advantages of using structures in C? 93
1. What is a union in C? 94

AR
2. How is memory allocated for a union? 94
3. How do you declare and initialize a union? 94
4. How do you access members of a union? 95

D
5. What happens when you assign values to multiple union members? 95
6. How do unions differ from structures? 96

AN
7. Can unions be nested within structures? 96
8. Can a union contain an array? 96
9. What is the purpose of using unions in C? 97
BH
10. Can unions be passed to functions? 97
11. How do you use pointers with unions? 97
12. Can you initialize a union with multiple values? 98
13. What is a bit field, and can it be used with unions? 98
AL

14. How do unions affect memory usage? 98


15. Can you compare two unions directly? 98
16. What is a self-referential union? 99
TP

17. How do you define and use an anonymous union? 99


18. What are some applications of unions? 100
19. Can unions be initialized with typedef? 100
O

20. How do unions compare to structures in terms of performance? 100


12. Pointers 101
IL

Introduction to Pointers in C 101


1. What is a Pointer? 101
N

2. Why Use Pointers? 102


3. Basic Pointer Syntax 102
4. Declaring and Initializing Pointers 102
5. Dereferencing a Pointer 102
6. Pointer Arithmetic 103
7. Pointers and Arrays 103
8. Pointers and Functions 103

5
A Quick Notes on C Programming 6

9. Dynamic Memory Allocation 104


10. Null Pointer 104
11. Common Errors with Pointers 105
Example 1: Simple Pointer Declaration and Dereferencing 105
Example 2: Changing Variable Value Through a Pointer 106
Example 3: Array Access with Pointers 107
Example 4: Pointer Arithmetic 107
Example 5: Dynamic Memory Allocation Using malloc 108

Y
Example 6: Null Pointer Check 109
Example 7: Pointer to Pointer 109

AR
Example 8: Function Returning a Pointer 110
13. Dynamic Memory Allocation in C 112
Dynamic Memory Allocation in C 112

D
1. Why Use Dynamic Memory Allocation? 112
2. Functions for Dynamic Memory Allocation 112

AN
3. Using malloc 112
4. Using calloc 113
5. Using realloc 113
BH
6. Using free 114
7. Example Program Using malloc and free 114
8. Common Errors in Dynamic Memory Allocation 115
14. File Management in C 117
AL

File Management in C 117


1. Types of File Operations 117
2. File Pointers and FILE Structure 117
TP

3. Opening a File with fopen 117


4. Closing a File with fclose 118
5. Writing to a File with fprintf and fputc 119
O

6. Reading from a File with fscanf and fgetc 119


7. Other Useful File Functions 120
IL

8. Checking the End of a File with feof 120


9. Binary File I/O with fread and fwrite 121
N

Explanation: 122
15. ASCII values 124
16. C Libraries 128

6
A Quick Notes on C Programming 7

Y
AR
D
AN
BH
AL
TP
O
IL
N

7
A Quick Notes on C Programming 8

1. Introduction to C Programming

1. Overview of C Programming Language

Y
● C Language:
○ Developed by Dennis Ritchie at Bell Labs in 1972.

AR
○ A general-purpose, procedural programming language.
○ Widely used for system programming (e.g., developing operating systems),
embedded systems, and other low-level applications.

D
● Key Features:
○ Portability: C programs can run on different machines with little or no
modification.

AN
○ Efficiency: C allows direct manipulation of memory, making it faster and
ideal for system-level programming.
BH
○ Flexibility: Offers rich sets of operators and data types.
○ Modularity: C programs can be split into smaller functions, which helps in
easier development and debugging.
AL

○ Standard Library: C provides a wide range of built-in functions for


input/output operations, memory allocation, and mathematical
computations.
TP

2. Why Learn C?
O

● Foundation for Other Languages: Many modern languages (C++, Java, Python)
are based on C or have syntax derived from it.
IL

● System-Level Access: C provides low-level access to memory and hardware,


making it useful for system programming.
N

● Embedded Systems: C is commonly used in programming microcontrollers and


embedded systems, which are found in electronic devices.
● Performance: C is highly efficient in terms of speed and resource usage, making it
a go-to language for performance-critical applications.

8
A Quick Notes on C Programming 9

2. The Structure of the C Programming

Y
AR
D
AN
BH
AL
TP
O

3. Structure of a C Program
IL

A typical C program consists of the following parts:


N

1. Link Section:
○ This tells the compiler to include libraries required by the program.
○ Example: #include <stdio.h> tells the compiler to include the
Standard Input/Output library, which contains functions like printf()
and scanf().

9
A Quick Notes on C Programming 10

2. Definition Section:
1. The #define directive in C is part of the preprocessor directives. It
allows the definition of symbolic constants and macros that are
substituted before the actual compilation process. The #define
directive essentially performs a text replacement wherever the
defined symbol or macro is used in the code.

Y
2. Syntax:

AR
○ #define name value_or_expression
3. name: The symbolic constant or macro name.
4. value_or_expression: The value or expression to be substituted.

D
AN
Key Uses of #define:

1. Defining Constants:
BH
○ Instead of using const, you can use #define to create
symbolic constants.
○ Example:
AL

#define PI 3.1415
TP

#define MAX_SIZE 100

○ In this example, whenever PI or MAX_SIZE is encountered in


O

the code, it will be replaced by 3.1415 and 100 respectively.


IL

2. Defining Macros:
○ Macros allow you to define expressions or code fragments
N

that can be reused.


○ Example:

#define SQUARE(x) (x * x)

10
A Quick Notes on C Programming 11

○ Here, SQUARE(x) is a macro that computes the square of a


number. Whenever SQUARE(num) is used in the program, it
will be replaced with the expression (num * num).
3. Conditional Compilation:
○ The #define directive is often used alongside #ifdef, #ifndef,
and #endif to conditionally include or exclude parts of the
code during compilation.

Y
○ Example:
1. #define DEBUG

AR
2. #ifdef DEBUG
3. printf("Debugging is enabled.\n");
4. #endif

D
○ If DEBUG is defined, the code inside the #ifdef block will be
included in the compilation.

Example Usage of #define: AN


BH
● #include <stdio.h>
● #define PI 3.1415
AL

● #define CIRCLE_AREA(r) (PI * (r) * (r))


● int main() {
TP

● float radius = 5.0;


● float area = CIRCLE_AREA(radius);
● printf("Area of the circle: %.2f\n", area);
O

● return 0;
● }
IL

In this example:
N

● #define PI 3.1415 defines a constant for the value of PI.


● #define CIRCLE_AREA(r) defines a macro that calculates the area of a circle
with radius r.

11
A Quick Notes on C Programming 12

Benefits of #define:

● Readability: Improves code readability by replacing magic numbers with


meaningful names.
● Code Reusability: Macros allow the reuse of code snippets or expressions,
reducing code duplication.

Y
● Maintenance: Makes code easier to maintain because changing the value

AR
in a single #define line updates it throughout the program.

D
Limitations of #define:

AN
○ No Type Checking: Since #define works as a simple text replacement,
there is no type checking, which can lead to unexpected results.
BH
○ Debugging Difficulty: It can make debugging more difficult because errors
in macros may not be immediately clear.
AL

3. Global Declaration Section


TP

Global Declaration Section in C Programming

5. The Global Declaration Section in C refers to the part of the program


O

where variables, constants, and functions are declared outside of all


IL

functions, typically at the beginning of the program. These global


declarations make variables and functions accessible to all parts of
N

the program, across different functions.


6.
7. Key Points about Global Declarations:
8. Global Variables:
○ Variables declared outside any function, typically at the start
of a program, are known as global variables.

12
A Quick Notes on C Programming 13

○ Global variables are accessible to all functions within the


program.
○ They retain their values throughout the execution of the
program, unlike local variables which are limited to a
function’s scope.
9. Syntax: data_type variable_name;
10. Example
○ int counter = 0; // Global variable

Y
○ int main() {
○ counter++;

AR
○ printf("Counter: %d", counter);
○ return 0;
○ }

D

○ void increment() {

AN
○ counter++;
○ }
11. Global Constants:
○ You can define constants globally to use them across the
BH
program.
12. Example: const float PI = 3.1415; // Global constant
13. Function Prototypes:
○ Function prototypes (also known as function declarations) can
AL

be placed in the global declaration section. These prototypes


inform the compiler about the function’s return type, name,
TP

and parameters before the function is used in main() or other


functions.
14. Syntax: return_type function_name(parameter_list);
O
IL

Example:
N

○ int add(int, int); // Function prototype


○ int main() {
○ int result = add(3, 4);
○ printf("Result: %d", result);
○ return 0;

13
A Quick Notes on C Programming 14

○ }

○ int add(int a, int b) {
○ return a + b;
○ }

Y
15. External Variables (extern):
○ If you want to share a global variable across multiple source

AR
files, the extern keyword is used. This tells the compiler that
the variable exists but is defined elsewhere.
16. Syntax: extern data_type variable_name;

D
Example:

AN
BH
// File1.c
int global_var = 10;
AL

// File2.c
extern int global_var;
TP
O

Advantages of Global Variables:


IL
N

1. Easy Access: Global variables are accessible from any function, making it easy to
share data across multiple functions.
2. Simplicity: It simplifies passing data between functions because global variables
don’t need to be passed as parameters.

Disadvantages of Global Variables:

14
A Quick Notes on C Programming 15

1. Risk of Errors: Since global variables can be modified by any function, tracking
changes can become difficult and lead to bugs.
2. Memory Usage: Global variables remain in memory for the entire duration of the
program, which may lead to inefficient memory usage in large programs.
3. Debugging Challenges: Changes in global variables can lead to unintended side
effects, making debugging more challenging.

Y
AR
Example Program with Global Declaration Section:

● #include <stdio.h>

D
● // Global variable

AN
● int counter = 0;

● // Function prototype
BH
● void incrementCounter();

● int main() {
● printf("Initial counter value: %d\n", counter);
AL

● incrementCounter(); // Increment the counter


● printf("Counter after increment: %d\n", counter);
TP

● return 0;
● }

O

● // Function to increment the counter


● void incrementCounter() {
IL

● counter++;
● }
N

In this program:

15
A Quick Notes on C Programming 16

4. int counter = 0; is a global variable that is accessible to both the main() and
incrementCounter() functions.
5. The global variable can be modified by any function, and its updated value is
retained throughout the program’s execution.

6. Main Function:

Y
○ Every C program has a main() function, which is the starting point of the
program.

AR
○ Example:
1. int main() {
2. // Program code goes here

D
3. return 0;

AN
4. }
7. Body of the Program:
○ The code that performs tasks is written inside the { } braces of the
BH
main() function.
8. Return Statement:
○ The return 0; statement at the end of main() signifies the successful
termination of the program.
AL

9. Comments:
○ Used to document the code.
TP

○ Example:
1. // This is a single-line comment.
2. /* This is a
O

3. multi-line comment. */
IL
N

16
A Quick Notes on C Programming 17

3. Getting Started With DevC++


How to Use Dev-C++ for C Programming: Step-by-Step Guide

Dev-C++ is an integrated development environment (IDE) for C and C++


programming, and it uses the MinGW compiler to compile and run code. Below is

Y
a step-by-step guide on how to set up and use Dev-C++ to write, compile, and run

AR
C programs.

Step 1: Download and Install Dev-C++

D
1. Download Dev-C++:
a. Go to the official website: Dev-C++ Download Link

AN
b. Click on the Download button to get the installer.

2. Install Dev-C++:
BH
a. Run the downloaded installer file.
b. Follow the installation prompts, selecting the appropriate options (like
installation directory, etc.).
AL

c. Once installed, launch Dev-C++.


TP

Step 2: Set Up a New C Project or File


O

1. Create a New Source File:


IL

○ Open Dev-C++.
○ Go to File → New → Source File.
N

○ A blank editor window will open where you can type your C code.
2. Save the Source File:
○ Before you start coding, save the file with a .c extension (e.g., program.c).
○ To save, go to File → Save As. Choose a location, give your file a name, and
set the Save as type to C source file.

17
A Quick Notes on C Programming 18

Step 3: Write Your C Code

1. Type in Your Code:


○ Write your C program in the editor. For example, here’s a simple “Hello,
World!” program:
1. #include <stdio.h>
2.

Y
3. int main() {

AR
4. printf("Hello, World!\n");
5. return 0;
6. }
2. Save the File:

D
○ After writing the code, save it by clicking File → Save, or simply press Ctrl + S.

Step 4: Compile the Program


AN
BH
○ Go to Execute → Compile (or press F9).
○ Dev-C++ will compile the code and show errors (if any) in the output
AL

window.
○ If there are no errors, the code is successfully compiled, and an executable
file (.exe) will be generated in the same directory where your source file is
TP

saved.
O

Step 5: Run the Program


IL

1. Run the Program:


N

○ After compiling, go to Execute → Run (or press F10).


○ A console window will open, displaying the output of your program.
2. For example, if you wrote a “Hello, World!” program, the output will be:

Hello, World!

18
A Quick Notes on C Programming 19

3. View and Close the Output Window:


○ Once the output is displayed, you can close the console window by clicking
the close button or pressing any key (depending on how your program is
written).

Y
Step 6: Debugging (Optional)

AR
Dev-C++ also provides basic debugging tools to help you find and fix errors in your code:

1. Debugging Tools:

D
○ To start debugging, go to Debug → Start/Continue Debugging (or press Ctrl

AN
+ F8).
○ You can set breakpoints by clicking on the left side of the code window to
pause the program at certain lines and examine variables or program flow.
BH
2. Viewing Variables:
○ While debugging, you can hover over variables to see their values, or use
the Watch window to monitor specific variables.
AL

Step 7: Additional Settings and Customization (Optional)


TP

1. Change Compiler Settings:


○ Go to Tools → Compiler Options to modify compiler settings (e.g.,
O

optimization levels, warning messages).


IL

2. Set Compiler Type:


○ By default, Dev-C++ uses the MinGW (GCC) compiler, which is fine for most
N

cases. But if you have other compilers installed, you can specify them here.
3. Customize Editor Appearance:
○ Go to Tools → Editor Options to change the font size, colors, and overall
appearance of the code editor.

Example Program to Test:

19
A Quick Notes on C Programming 20

Here’s a simple C program to try:

● #include <stdio.h>
● int main() {
● int number;
● printf("Enter an integer: ");
● scanf("%d", &number); //& is address of operator
● printf("You entered: %d\n", number); //%d is escape sequence for int

Y
● return 0;
● }

AR
D
1. Steps:
○ Open Dev-C++ and create a new source file.



AN
Type the code above into the editor.
Save the file as input_program.c.
Compile and run it. The program will prompt you to enter an integer and
BH
then print it back.
AL

Tips and Troubleshooting


TP

● Error in Compilation: If you encounter any errors while compiling, carefully check
the error messages in the output window. They will help you locate and fix the
issues in your code.
O

● Auto-Save Feature: To prevent losing code, enable auto-save from the options.
● Console Closes Too Fast: If the console window closes immediately after running
IL

your program, try adding the following line before the return statement:
system("pause");
N

● This will make the console wait for you to press a key before closing.

20
A Quick Notes on C Programming 21

4. Constants, Variables and Data Types


1. Constants In C

A constant is a value that cannot be changed during the execution of a program.


Constants in C are defined in various ways to represent fixed values that do not change.

Y
Types of Constants:

AR
1. Integer Constants:
○ A whole number without a fractional part.

D
○ Example: 10, -25, 0
2. Floating-Point Constants:

AN
○ A number that has a fractional part (with a decimal point).
○ Example: 3.14, -0.001, 5.0
3. Character Constants:
BH
○ A single character enclosed in single quotes.
○ Example: 'A', 'b', '5'
4. String Constants:
AL

○ A sequence of characters enclosed in double quotes.


○ Example: "Hello", "C programming"
5. Backslash Character Constants:
TP

○ C supports some special backslash character constants that are used in


output functions
○ Example: "\n" is for new line , "\t" for tab, "\a" for audible alert
O

6. Symbolic Constants (#define):


IL

○ Defined using the #define directive to represent fixed values.


○ Example: #define PI 3.1415
N

7. Constant Variables (const):


○ Variables declared with the const keyword cannot be modified after
initialization.
○ Example: const int max_limit = 100;

21
A Quick Notes on C Programming 22

2. Variables in C

A variable is a named location in memory that stores a value which can be modified
during the program execution. Variables must be declared before they are used.

Declaring Variables:

Y
Syntax: data_type variable_name;

AR
Example:

● int age;

D
● float height;

AN
● char grade;

Initializing Variables:
BH
Variables can be initialized when they are declared.

Syntax:
data_type variable_name = value;
AL

Example:

int age = 20;


TP

float height = 5.9;

char grade = 'A';


O

Rules for Naming Variables:


IL

● A variable name must start with a letter or an underscore (_) or $, but not
N

with a number.
● It can consist of letters, digits, and underscores.
● Variable names are case-sensitive (e.g., age and Age are different).
● Keywords like int, float, return, etc., cannot be used as variable names.

22
A Quick Notes on C Programming 23

3. Data Types in C

Data types define the type of data that can be stored in a variable and how much
memory will be allocated for that data. There are several types of data types in C:

Y
Primary Data Types:

AR
Integer (int):

○ Stores whole numbers (both positive and negative).

D
○ Example: int x = 10;

Floating-Point (float, double):


AN
BH
○ Stores real numbers with fractional parts.
○ float: Single precision (4 bytes).
○ double: Double precision (8 bytes) for more accuracy.
AL

○ Example:
float temp = 36.5;
double pi = 3.14159;
TP

Character (char):
O

○ Stores a single character.


IL

○ Requires 1 byte of memory.


○ Example: char letter = 'A';
N

Void (void):

Represents the absence of a value. Typically used for functions that return no
value.

23
A Quick Notes on C Programming 24

Derived Data Types:

Derived from basic data types and include:

○ Arrays: Collection of variables of the same data type.

○ Pointers: Stores memory addresses.

○ Structures: Groups different data types together.

Y
○ Unions: Stores different data types in the same memory location.

AR
Qualifiers:

Qualifiers modify the basic data types and allow for more precision.

D
signed and unsigned:

AN
signed: Can hold both positive and negative values.

unsigned: Can only hold positive values, giving a larger range of positive values.
BH
Example: unsigned int positive_num = 100;

○ short and long:


AL

○ short: Takes up less memory (e.g., short int).


○ long: Takes up more memory (e.g., long int).
TP

Example: long int big_number = 1000000;


O
IL
N

4. Memory Size of Data Types

24
A Quick Notes on C Programming 25

Data Type Memory Size (in bytes) Range

char 1 -128 to 127 or 0 to 255

int 2 or 4 -32,768 to 32,767 (2 bytes)

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

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

D
short int 2 -32,768 to 32,767

long int 4 AN -2,147,483,648 to


BH
2,147,483,647

unsigned 4 0 to 4,294,967,295
int
AL
TP

5. Example Program: Using Constants, Variables, and Data Types


O

1. #include <stdio.h>
IL

2. #define PI 3.14159 // Define a constant


N

3. int main() {
4. int radius; // Declare an integer variable
5. float area; // Declare a floating-point variable
6. printf("Enter the radius of the circle: ");
7. scanf("%d", &radius); // Input value for radius
8. area = PI * radius * radius; // Calculate the area of the circle
9. printf("The area of the circle is: %.2f\n", area); // Print the area

25
A Quick Notes on C Programming 26

10. return 0;
11. }

Explanation:

● #define PI 3.14159: Defines a constant value for PI.

Y
● Variables: int radius for storing the radius of the circle and float area for storing the

AR
calculated area.
● Data Types: int for integers and float for real numbers with decimal points.

D
5. Storage Classes

AN
In C programming, Storage Classes define the scope, visibility, lifetime, and default initial
value of variables/functions within a C program. These characteristics dictate how
BH
variables are stored and how they behave throughout the program. There are four
primary storage classes in C:

● auto (Automatic Storage Class)


AL

● register (Register Storage Class)


● static (Static Storage Class)
TP

● extern (External Storage Class)

Let’s go over each of these storage classes in detail.


O

1. auto Storage Class


IL
N

● Scope: Local to the block (usually within a function).


● Lifetime: Exists until the function or block completes execution.
● Default Initial Value: Garbage value (uninitialized unless explicitly assigned).
● Storage: Stored in the stack.

26
A Quick Notes on C Programming 27

By default, local variables declared inside a function have the auto storage class. There is
no need to explicitly specify auto as it is automatically assigned.

Example:

#include <stdio.h>

void function() {

Y
auto int x = 10; // Local variable with auto storage class

AR
printf("x = %d\n", x);

D
int main() {

AN
function();

return 0;
BH
}

Here, x has an automatic storage duration and is destroyed when the function function()
completes.
AL
TP

2. register Storage Class


O

● Scope: Local to the block (within a function).


● Lifetime: Exists until the function/block completes execution.
IL

● Default Initial Value: Garbage value (uninitialized unless explicitly assigned).


N

● Storage: Stored in CPU registers (if available); otherwise, in RAM.

The register storage class is used when you want a variable to be stored in the CPU’s
register instead of RAM for fast access. However, the request to store in a register is not
guaranteed; it depends on the system architecture.

27
A Quick Notes on C Programming 28

Example:

#include <stdio.h>

int main() {

register int count = 0; // Requesting to store count in a CPU register

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

Y
count += i;

AR
}

printf("Count = %d\n", count);

D
return 0;

AN
}

In this example, the variable count may be stored in a CPU register for faster access
BH
during the loop.
AL

3. static Storage Class


TP

● Scope: Local to the block (for local variables) or global (for global variables).
● Lifetime: Exists for the entire duration of the program.
● Default Initial Value: Zero (0) for integers, NULL for pointers.
O

● Storage: Stored in the global/static memory section of the program.


IL

The static storage class is used to retain the value of a variable between function calls.
N

For global variables, it restricts their visibility to the file in which they are declared.

Example (Static Variable in a Function):

#include <stdio.h>

void counter() {

28
A Quick Notes on C Programming 29

static int count = 0; // Static variable retains its value


between function calls

count++;

printf("Count = %d\n", count);

Y
int main() {

AR
counter();

counter();

D
counter();

AN
return 0;

}
BH
Output:

Count = 1

Count = 2
AL

Count = 3
TP

In this example, the static variable count retains its value between multiple calls to the
counter() function.
O

Example (Static Global Variable):


IL

#include <stdio.h>

static int globalVar = 10; // This variable is restricted to this file


N

int main() {

printf("GlobalVar = %d\n", globalVar);

return 0;

29
A Quick Notes on C Programming 30

In this case, globalVar is a static global variable, meaning it can only be accessed within
the same file and is not visible to other files.

4. extern Storage Class

Y
● Scope: Global (visible across multiple files).

AR
● Lifetime: Exists for the entire duration of the program.
● Default Initial Value: Zero (0) for integers, NULL for pointers.
● Storage: Stored in global/static memory section of the program.

D
AN
The extern storage class is used to declare a global variable or function that is defined in
another file. It is typically used to share variables or functions across multiple files.

Example (External Variable):


BH
File 1 (main.c):
AL

#include <stdio.h>

extern int globalVar; // Declaration of external variable


TP

int main() {

printf("GlobalVar = %d\n", globalVar);


O

return 0;
IL

}
N

File 2 (global.c):

int globalVar = 100; // Definition of external variable

30
A Quick Notes on C Programming 31

Here, the extern keyword tells the compiler that the variable globalVar is declared in
another file (in this case, global.c). This allows the main.c file to access the globalVar
variable.

Key Differences Between Storage Classes

Y
AR
Storage Scope Lifetime Default Keyword
Class Initial Value

D
auto Local to Exists until Garbage auto
block
AN
block/function
ends
value
BH
register Local to Exists until Garbage register
block block/function value
ends
AL

static Local (or Exists for the 0 (for static


TP

file-level) entire program numbers)

extern extern
O

Global Exists for the 0 (for


entire program numbers)
IL
N

31
A Quick Notes on C Programming 32

5. Operators

Operators in C Programming

An operator in C is a symbol that tells the compiler to perform specific operations

Y
on variables or values. Operators are used for various operations like arithmetic,

AR
comparison, bitwise manipulation, and logical decisions.

D
Types of Operators in C:

1.
2.
3.
Arithmetic Operators
Relational Operators
Logical Operators
AN
BH
4. Bitwise Operators
5. Assignment Operators
6. Increment & Decrement Operators
AL

7. Miscellaneous Operators
TP

1. Arithmetic Operators
O
IL

Arithmetic operators are used to perform mathematical operations.


N

Operat Description Example


or

+ Addition a + b

32
A Quick Notes on C Programming 33

- Subtraction a - b

* Multiplication a * b

/ Division a / b

Y
% Modulus a % b

AR
(Remainder)

Example:

D
int a = 10, b = 5;

int sum = a + b; // sum = 15

int diff = a - b; // diff = 5


AN
BH
int product = a * b; // product = 50

int quotient = a / b; // quotient = 2


AL

int remainder = a % b; // remainder = 0


TP
O

2. Relational Operators
IL

Relational operators are used to compare two values or expressions.


N

Operator Description Example

== Equal to a == b

33
A Quick Notes on C Programming 34

!= Not equal to a != b

> Greater than a > b

< Less than a < b

Y
>= Greater than or equal to a >= b

AR
<= Less than or equal to a <= b

D
Example:

int a = 10, b = 20;

int result;
AN
BH
result = (a > b); // result = 0 (false)

result = (a < b); // result = 1 (true)


AL

result = (a == b); // result = 0 (false)

result = (a != b); // result = 1 (true)


TP
O
IL

3. Logical Operators
N

Logical operators are used to perform logical operations in expressions and return a
boolean result.

Operat Descriptio Exampl


or n e

34
A Quick Notes on C Programming 35

&& Logical (a && b)


AND

|| Logical OR (a || b)

! Logical !(a)

Y
NOT

AR
Example:

int a = 1, b = 0;

D
int result;

result = (a && b);


AN
// result = 0 (false)
BH
result = (a || b); // result = 1 (true)

result = (!a); // result = 0 (false)


AL
TP

4. Bitwise Operators
O

Bitwise operators are used to perform operations at the bit level (binary digits).
IL

Operat Description Exampl


N

or e

& Bitwise AND a & b

| Bitwise OR a | b

35
A Quick Notes on C Programming 36

^ Bitwise XOR (Exclusive a ^ b


OR)

~ Bitwise NOT ~a

<< Left shift a << 2

Y
AR
>> Right shift a >> 2

Example:

D
int a = 5, b = 3; // 5 = 0101, 3 = 0011

int result;
AN
BH
result = a & b; // result = 1 (0001)

result = a | b; // result = 7 (0111)


AL

result = a ^ b; // result = 6 (0110)

result = ~a; // result = -6 (2's complement)


TP

result = a << 1; // result = 10 (shifts bits left)

result = a >> 1; // result = 2 (shifts bits right)


O
IL
N

5. Assignment Operators

Assignment operators are used to assign values to variables.

36
A Quick Notes on C Programming 37

Operat Description Exampl


or e

= Assigns value a = 10

+= Add and assign a += 5

Y
AR
-= Subtract and a -= 5
assign

D
*= Multiply and a *= 5

AN
assign

/= Divide and assign a /= 5


BH
%= Modulus and a %= 5
assign
AL

Example:
TP

int a = 10;
O

a += 5; // a = 15
IL

a -= 3; // a = 12
N

a *= 2; // a = 24

a /= 4; // a = 6

a %= 5; // a = 1

37
A Quick Notes on C Programming 38

6. Increment and Decrement Operators

-- Decrement a--

Y
Operator //a=a-1

AR
++ a++

D
Increment
Operator //a=a+1

AN
BH
7. Miscellaneous Operators

1. sizeof Operator:
○ Used to determine the size (in bytes) of a data type or variable.
AL

○ Example:
TP

int a = 5;

printf("%lu", sizeof(a)); // Output: 4 (size of int is 4 bytes)


O
IL


N

2. Comma Operator (,):


○ Used to separate expressions, and the last expression is
evaluated.
○ Example:

38
A Quick Notes on C Programming 39

int a = (3, 5); // a = 5


3. Pointer Operators (* and &):
○ &: Returns the address of a variable.
○ *: Dereferences a pointer to access the value at the address.
○ Example:

Y
AR
int a = 5;

int *p = &a; // p stores the address of a

D
printf("%d", *p); // Output: 5

○ AN
BH
4. Conditional/Ternary Operator (? :):
○ A shorthand for an if-else condition.
○ Syntax: condition ? expression1 : expression2
AL

○ Example:
TP

int a = 10, b = 20;

int max = (a > b) ? a : b; // max = 20


O

5. Type Casting Operator:


IL

○ Used to convert one data type to another.


N

Example:

float x = 5.5;

int y = (int)x; // y = 5

39
A Quick Notes on C Programming 40

Example Program Using Different Operators:


#include <stdio.h>

int main() {

Y
int a = 10, b = 20, result;

AR
// Arithmetic Operators

D
result = a + b;

AN
printf("Addition: %d\n", result);
BH
// Relational Operators

result = (a < b);


AL

printf("a < b: %d\n", result);


TP

// Logical Operators

result = (a && b);


O

printf("Logical AND: %d\n", result);


IL
N

// Bitwise Operators

result = a & b;

printf("Bitwise AND: %d\n", result);

40
A Quick Notes on C Programming 41

// Assignment Operators

a += 5;

printf("After += operation: %d\n", a);

// Conditional Operator

Y
result = (a > b) ? a : b;

AR
printf("Larger value: %d\n", result);

D
return 0;

AN
BH
AL
TP
O
IL
N

41
A Quick Notes on C Programming 42

6. Expressions
In C programming, an expression is a combination of variables, constants, operators, and
function calls that are evaluated to produce a value. Expressions can be simple or
complex, depending on how they are structured.

Y
Components of an Expression

AR
1. Operands: The values on which operations are performed. These can be
constants, variables, or function calls.

D
○ Example: In a + b, a and b are operands.

AN
2. Operators: The symbols that represent actions or operations to be performed
on the operands.
○ Example: In a + b, + is the operator.
BH
Types of Expressions

Expressions in C can be classified into various types based on the operations they
AL

perform:

1. Arithmetic Expressions
TP

These expressions use arithmetic operators such as +, -, *, /, and % to perform


mathematical calculations.
O

Example:
IL

int a = 10, b = 5;
N

int result = a + b; // result will be 15

2. Relational Expressions
These expressions compare two values and return either true (1) or false (0). The
operators used are relational operators like <, >, <=, >=, ==, and !=.

42
A Quick Notes on C Programming 43

Example:

int a = 10, b = 5;

int result = (a > b); // result will be 1 (true) since 10 is


greater than 5

Y
3. Logical Expressions

AR
Logical expressions use logical operators (&&, ||, !) to combine or invert conditions. These
expressions are evaluated as either true (1) or false (0).

D
Example:

AN
int a = 10, b = 5, c = 0;

int result = (a > b) && (b > c); // result will be 1 (true) since
both conditions are true
BH

4. Assignment Expressions
AL

Assignment expressions assign a value to a variable using the assignment operator (=).

Example:
TP

int a;

a = 10; // Assigns the value 10 to the variable 'a'


O
IL

You can also combine expressions in assignments:


N

int a = 5, b;

b = a + 10; // b will be 15 (5 + 10)

43
A Quick Notes on C Programming 44

5. Conditional Expressions (Ternary Operator)


A conditional expression uses the ternary operator (? :) to evaluate a condition and return
one of two values based on whether the condition is true or false.

Syntax:

(condition) ? expression_if_true : expression_if_false;

Y
AR
Example:

int a = 10, b = 5;

D
int max = (a > b) ? a : b; // max will be 10 because a is greater

AN
than b
BH
6. Increment/Decrement Expressions
These expressions use the increment (++) and decrement (--) operators to increase or
decrease the value of a variable by 1.
AL

● Postfix: The operator is placed after the operand (a++, a--).


● Prefix: The operator is placed before the operand (++a, --a).
TP

Example:
O

int a = 5;
IL

a++; // a is now 6 (post-increment)

++a; // a is now 7 (pre-increment)


N

7. Bitwise Expressions
Bitwise expressions perform operations on binary representations of integers using
bitwise operators (&, |, ^, ~, <<, >>).

44
A Quick Notes on C Programming 45

Example:

int a = 5; // Binary: 0101

int b = 3; // Binary: 0011

int result = a & b; // result will be 1 (Binary: 0001)

Y
Operator Precedence and Associativity

AR
When expressions involve multiple operators, the precedence of the operators
determines the order in which they are evaluated. The associativity defines the direction

D
in which expressions are evaluated when operators have the same precedence.

AN
Operator Precedence Table (in descending order of precedence):

1. (), [], ., ->


BH
2. ++, --, -, +, !, ~, *, &, sizeof
3. *, /, %
4. +, -
AL

5. <<, >>
6. <, <=, >, >=
7. ==, !=
TP

8. &
9. ^
O

10. |
11. &&
IL

12. ||
N

13. ? :
14. =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

Associativity:

45
A Quick Notes on C Programming 46

● Left to Right: Most operators, like arithmetic (+, -, *), relational (<, >, ==), logical
(&&, ||), and bitwise operators, are evaluated from left to right.
● Right to Left: Assignment (=) and conditional (? :) operators are evaluated from
right to left.

Y
Examples of Expression Evaluation

AR
Example 1:
int a = 10, b = 5, c;

D
c = a * b + 10;

AN
BH
● Here, a * b is evaluated first (because * has higher precedence than +),
resulting in 50.
● Then, 50 + 10 is evaluated, resulting in 60.
AL

Example 2:

int a = 10, b = 20, c;


TP

c = (a > b) ? a : b;
O

● The condition a > b is evaluated first. Since a is not greater than b, the
expression evaluates to b.
IL

● So, c is assigned the value b (which is 20).


N

46
A Quick Notes on C Programming 47

Type Conversion in C

In C programming, type conversion (also known as type casting) refers to converting one
data type into another. There are two main types of type conversion in C:

1. Implicit Type Conversion (Automatic Type Conversion)

Y
2. Explicit Type Conversion (Type Casting)

AR
1. Implicit Type Conversion (Automatic Type Conversion)
Implicit type conversion is automatically performed by the compiler when it encounters a

D
mismatch in data types during operations. The compiler promotes the data type to a
higher type in the expression to avoid data loss.

Rules for Implicit Type Conversion:


AN
BH
● If an operation involves an int and a float, the int is promoted to float.
● If an operation involves an int and a double, the int is promoted to double.
● If an operation involves a char and an int, the char is promoted to int.
AL

This process of converting a smaller data type (like int) to a larger data type (like double)
is called type promotion.
TP

Example of Implicit Type Conversion:

#include <stdio.h>
O

int main() {
IL

int num1 = 10;


N

float num2 = 3.5;

float result = num1 + num2; // Implicit type conversion: num1 (int) is


promoted to float

printf("Result = %.2f\n", result); // Output: 13.50

return 0;

47
A Quick Notes on C Programming 48

In this example, num1 (an int) is implicitly converted to float during the addition operation
with num2, and the result is stored in a float variable.

Y
2. Explicit Type Conversion (Type Casting)

AR
Explicit type conversion is performed manually by the programmer using a cast operator.
This type conversion is useful when we want to force a conversion that the compiler
would not automatically perform.

D
Syntax for Type Casting:

(type) expression;
AN
BH
Example of Explicit Type Conversion:

#include <stdio.h>
AL

int main() {

int num1 = 10, num2 = 3;


TP

// Explicit type conversion to float

float result = (float) num1 / num2; // Cast num1 to float


O

before division
IL

printf("Result = %.2f\n", result); // Output: 3.33


N

return 0;

Here, num1 is explicitly converted to float, ensuring that the division operation results in a
floating-point value rather than an integer value.

48
A Quick Notes on C Programming 49

Difference Between Implicit and Explicit Type Conversion

Implicit Type Conversion Explicit Type Conversion

Performed automatically by the Performed manually by the

Y
compiler. programmer.

AR
Also known as type promotion. Also known as type casting.

D
Usually safe and does not lead Can lead to data loss if the types

AN
to data loss. are not compatible.

Example: int to float. Example: (float) num1 / num2.


BH

Type Conversion in Expressions


AL

When different data types are used in a single expression, C applies implicit type
conversion to ensure all operands have the same type before performing the operation.
TP

Example:

#include <stdio.h>
O

int main() {
IL

int a = 5;
N

float b = 3.2;

float result = a * b; // Implicit type conversion: 'a' (int)


is converted to float

printf("Result = %.2f\n", result); // Output: 16.00

49
A Quick Notes on C Programming 50

return 0;

Potential Data Loss in Type Conversion

Y
When converting from a larger data type to a smaller data type, there is a potential for

AR
data loss. For example, converting a float to an int will discard the fractional part.

Example:

D
#include <stdio.h>

int main() { AN
BH
float num = 10.99;

int result = (int) num; // Explicit type conversion: float to


AL

int

printf("Result = %d\n", result); // Output: 10 (fractional


TP

part is discarded)
O

return 0;
IL

}
N

In this case, converting 10.99 (a float) to int results in the loss of the decimal part, and
only 10 is stored.

50
A Quick Notes on C Programming 51

Type Promotion in Functions

In C, when using functions without type-specific parameters, arguments of smaller types


like char and short are automatically promoted to int or unsigned int.

Example:

#include <stdio.h>

Y
AR
void display(int x) {

printf("Value = %d\n", x);

D
}

int main() { AN
BH
char ch = 'A';

display(ch); // Implicit type conversion: 'char' is promoted


to 'int'
AL

return 0;
TP

}
O

In this example, the char argument is promoted to int when passed to the display
IL

function.
N

51
A Quick Notes on C Programming 52

7. Decision Making and Branching in C


In C programming, decision making and branching are used to execute specific blocks of
code based on certain conditions. These control structures allow a program to make
decisions and take different paths, enabling dynamic behavior depending on the inputs
or conditions.

Y
Types of Decision Making and Branching in C:

AR
1. if Statement
2. if-else Statement

D
3. else-if Ladder

AN
4. Nested if Statement
5. switch Statement
6. Conditional (Ternary) Operator
BH

1. if Statement
AL

The if statement is used to evaluate a condition. If the condition is true (non-zero), the
block of code inside the if statement is executed; otherwise, the program skips the block.
TP

Syntax:
O

if (condition) {

// Code to execute if condition is true


IL

}
N

Example:

#include <stdio.h>

52
A Quick Notes on C Programming 53

int main() {

int number = 10;

if (number > 0) {

printf("The number is positive.\n");

Y
}

AR
return 0;

D
}

AN
In this example, if number is greater than 0, the message “The number is positive” will be
BH
printed.

2. if-else Statement
AL

The if-else statement extends the basic if statement by adding an alternative path. If the
condition is true, the if block is executed; if the condition is false, the else block is
TP

executed.

Syntax:
O

if (condition) {
IL

// Code to execute if condition is true


N

} else {

// Code to execute if condition is false

53
A Quick Notes on C Programming 54

Example:

#include <stdio.h>

int main() {

int number = -5;

if (number > 0) {

Y
printf("The number is positive.\n");

AR
} else {

printf("The number is not positive.\n");

D
}

}
return 0;

AN
BH
In this example, since number is less than 0, the program will print “The number is not
positive.”
AL

3. else-if Ladder
TP

The else-if ladder allows checking multiple conditions one by one. If one of the
conditions is true, its corresponding block is executed, and the rest of the ladder is
skipped.
O

Syntax:
IL

if (condition1) {
N

// Code to execute if condition1 is true

} else if (condition2) {

// Code to execute if condition2 is true

} else if (condition3) {

54
A Quick Notes on C Programming 55

// Code to execute if condition3 is true

} else {

// Code to execute if none of the conditions are true

Y
Example:

AR
#include <stdio.h>

D
int main() {

int number = 0;

AN
BH
if (number > 0) {

printf("The number is positive.\n");


AL

} else if (number < 0) {

printf("The number is negative.\n");


TP

} else {

printf("The number is zero.\n");


O

}
IL
N

return 0;

Here, the program checks if number is positive, negative, or zero, and prints the
appropriate message.

55
A Quick Notes on C Programming 56

4. Nested if Statement
You can use an if statement inside another if or else block, forming a nested if structure.
This allows more complex decision making based on multiple conditions.

Syntax:

if (condition1) {

Y
if (condition2) {

AR
// Code to execute if both condition1 and condition2 are
true

D
}

AN
}
BH
Example:

#include <stdio.h>

int main() {
AL

int number = 5;

if (number > 0) {
TP

if (number % 2 == 0) {

printf("The number is positive and even.\n");


O

} else {
IL

printf("The number is positive and odd.\n");


N

return 0;

56
A Quick Notes on C Programming 57

In this case, the program first checks if the number is positive and then further checks
whether it is even or odd.

5. switch Statement
The switch statement is used to perform different actions based on the value of an

Y
expression. It is an alternative to using multiple if-else-if statements when you are
working with multiple constant values.

AR
Syntax:

switch (expression) {

D
case value1:

AN
// Code to execute if expression equals value1

break;
BH
case value2:

// Code to execute if expression equals value2

break;
AL

// You can add more cases as needed

default:
TP

// Code to execute if none of the cases match

}
O

● The break statement is used to exit the switch after the matching case has been
IL

executed.
N

● The default case is optional and will be executed if none of the cases match.

Example:

#include <stdio.h>

int main() {

57
A Quick Notes on C Programming 58

int day = 3;

switch (day) {

case 1:

printf("Monday\n");

break;

Y
case 2:

AR
printf("Tuesday\n");

break;

D
case 3:

printf("Wednesday\n");

break; AN
BH
default:

printf("Invalid day\n");
AL

}
TP

return 0;

}
O
IL

In this example, since day equals 3, the program will print “Wednesday.”
N

6. Conditional (Ternary) Operator


The ternary operator (? :) is a shorthand way to write simple if-else statements. It
evaluates a condition and returns one of two values depending on whether the condition
is true or false.

58
A Quick Notes on C Programming 59

Syntax:

condition ? expression_if_true : expression_if_false;

Example:

#include <stdio.h>

Y
int main() {

AR
int number = 10;

char *result = (number > 0) ? "Positive" : "Not Positive";

D
printf("The number is %s.\n", result);

}
return 0;

AN
BH
In this example, if the number is greater than 0, the message will say “The number is
Positive”; otherwise, it will say “The number is Not Positive.”
AL
TP

Key Points about Decision Making and Branching:

1. if statements allow you to perform actions based on whether a condition is true.


O

2. if-else provides an alternative action if the condition is false.


IL

3. The else-if ladder allows for multiple conditions to be checked in sequence.


N

4. Nested if structures allow for more complex decision making by checking


conditions inside other conditions.

5. The switch statement is useful for selecting one out of many possible actions
based on the value of an expression.

6. The ternary operator offers a concise way to make decisions in expressions.

59
A Quick Notes on C Programming 60

7. “goto” Statement
The goto statement in C provides an unconditional jump to another part of the
program. It is often considered a controversial or “risky” control structure because it can
make code harder to understand and maintain. However, it may be useful in certain
situations where other control structures (like loops or functions) don’t provide an ideal

Y
solution, such as breaking out of deeply nested loops or error handling.

AR
Syntax of goto Statement

goto label;

D
...

label:

AN
// Code to execute when the label is reached
BH
● label: A user-defined identifier followed by a colon (:), which indicates the target
point where control should jump.
● goto: The statement that initiates the jump to the defined label.
AL
TP

How goto Works

1. The goto statement causes the program to jump to the part of the code marked by
O

a label.
IL

2. A label is an identifier followed by a colon (:), placed before a statement.


3. When the goto statement is encountered, control is transferred to the statement
N

marked by the label.

Example of goto Statement


#include <stdio.h>

int main() {

60
A Quick Notes on C Programming 61

int number = 10;

if (number > 0) {

goto positive;

printf("This will be skipped.\n");

Y
positive:

AR
printf("The number is positive.\n");

D
return 0;

AN
BH
● In this example, if the condition (number > 0) is true, the program will jump to the
label positive and skip the intermediate printf statement. The output will be:
● The number is positive.
AL
TP
O
IL
N

61
A Quick Notes on C Programming 62

8. Array

1. What is an array in C?

Answer:

Y
An array is a collection of elements of
the same data type stored in contiguous

AR
memory locations. It allows you to store
multiple values of a similar type under a
single name, which can be accessed

D
using indices.

Example: AN
BH
int numbers[5]; // Declares an array of 5 integers
AL

2. How do you declare and initialize an array in C?

Answer:
TP

You can declare an array using the following syntax:

data_type array_name[size];
O

To initialize an array, you can specify values in curly braces {}:


IL

int numbers[5] = {1, 2, 3, 4, 5};


N

Here, numbers is an array of 5 integers initialized with values 1, 2, 3, 4, 5.

62
A Quick Notes on C Programming 63

3. How do you access elements of an array?

Answer:
Elements of an array are accessed using zero-based indexing. The index starts from 0
and goes up to size - 1.

Example:

Y
int numbers[3] = {10, 20, 30};
printf("%d", numbers[0]); // Output: 10

AR
printf("%d", numbers[2]); // Output: 30

D
4. What happens if you access an array out of its bounds?

Answer:
AN
Accessing an array out of its bounds (using an index that is negative or greater than size -
BH
1) leads to undefined behavior. This can cause the program to read or write into
unintended memory locations, potentially leading to crashes or erroneous results.

Example:
AL

int arr[3] = {1, 2, 3};


printf("%d", arr[5]); // Undefined behavior, as the index 5 is out of bounds
TP

5. How do you find the size of an array in C?


O

Answer:
IL

You can find the size of an array using the sizeof operator, which returns the total memory
occupied by the array.
N

Example:

int arr[5] = {1, 2, 3, 4, 5};


int size = sizeof(arr) / sizeof(arr[0]); // Calculates the number of elements in the array
printf("Size of the array: %d", size); // Output: 5

63
A Quick Notes on C Programming 64

If we initialize an array using an initializer list, we can skip declaring the size of the
array as the compiler can automatically deduce the size of the array in these cases.
The size of the array in these cases is equal to the number of elements present in the
initializer list as the compiler can automatically deduce the size of the array.

int arr[ ] = {1, 2, 3, 4, 5};

Y
AR
Types of Multidimensional Arrays

In C programming, arrays can have various dimensions, but the two most commonly used

D
types are:

AN
1. Two-Dimensional Array (2D Array)
2. Three-Dimensional Array (3D Array)
BH
6. What is a multidimensional array?

Answer:
A multidimensional array is an array of arrays. A multi-dimensional array can be defined
AL

as an array that has more than one dimension and the most common is the 2D array,
which can be visualized as a table with rows and columns.
TP

Two-Dimensional (2D) Arrays in C

A 2D array is the simplest form of a multidimensional array. It can be thought of as a table


O

with m rows and n columns, where each element is stored in a row-column pair. In C,
arrays are 0-indexed, meaning that row indices range from 0 to m-1 and column indices
IL

range from 0 to n-1.


N

64
A Quick Notes on C Programming 65

Y
AR
D
Example:

int matrix[3][3] = { AN
BH
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
AL

In this example, matrix is a 2D array with 3 rows and 3 columns.


TP

7. How do you access elements in a 2D array?


O

Answer:
IL

You access elements of a 2D array using two indices: array_name[row][column].

Example:
N

int matrix[2][2] = {{1, 2}, {3, 4}};


printf("%d", matrix[0][1]); // Output: 2 (element in the first row, second column)

8. How do you pass an array to a function?

65
A Quick Notes on C Programming 66

Answer:
When passing an array to a function, you need to pass the array name (which acts as a
pointer to the first element) and, optionally, the size of the array.

Example:

#include <stdio.h>

Y
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {

AR
printf("%d ", arr[i]);
}
}

D
int main() {

AN
int numbers[5] = {10, 20, 30, 40, 50};
printArray(numbers, 5); // Passing array to function
return 0;
BH
}
AL

9. What is the difference between an array and a pointer?

Answer:
TP

- An array is a collection of elements stored in contiguous memory locations, and its size
is fixed. - A pointer can point to any memory location and can be incremented to access
different elements of an array. - When you pass an array to a function, it decays into a
O

pointer to its first element.


IL

Example:
N

int arr[3] = {1, 2, 3};


int *ptr = arr; // Pointer points to the first element of the array

printf("%d", *(ptr + 1)); // Output: 2 (Accessing the second element)

66
A Quick Notes on C Programming 67

10. How do you copy elements of one array to another in C?

Answer:
To copy elements from one array to another, you need to use a loop to copy each
element individually since arrays do not support direct assignment.

Example:

Y
#include <stdio.h>

AR
int main() {
int source[3] = {1, 2, 3};
int destination[3];

D
AN
for (int i = 0; i < 3; i++) {
destination[i] = source[i];
}
BH
// Print copied elements
for (int i = 0; i < 3; i++) {
printf("%d ", destination[i]); // Output: 1 2 3
}
AL

return 0;
}
TP
O

11. What are the limitations of arrays in C?


IL

Answer:
- Fixed Size: Once an array is declared, its size cannot be changed during runtime. -
N

Homogeneous Elements: Arrays can store only elements of the same data type. -
Contiguous Memory: Requires contiguous memory allocation, which might be a
limitation for large arrays. - Lack of Bounds Checking: C does not perform bounds
checking, which means accessing elements outside the array’s limits can lead to
undefined behavior.

67
A Quick Notes on C Programming 68

12. How is a string represented as an array in C?

Answer:
In C, a string is represented as an array of characters terminated by a null character ('\0').

Example:

Y
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Array representation of a string

AR
// or
char str[] = "Hello"; // Easier way to represent a string

printf("%s", str); // Output: Hello

D
AN
13. Can you change the size of an array once it is declared?
BH
Answer:
No, you cannot change the size of an array once it is declared in C. Arrays have a fixed
size, which must be defined at compile time. To work with dynamic sizes, you need to
use pointers and dynamic memory allocation (malloc, calloc, realloc).
AL
TP

14. How do you sort an array in C?

Answer:
O

You can sort an array using sorting algorithms like Bubble Sort, Selection Sort, or using
the qsort() function provided by the stdlib.h library.
IL

Example (Bubble Sort):


N

#include <stdio.h>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {

68
A Quick Notes on C Programming 69

int temp = arr[j];


arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

Y
int main() {
int arr[5] = {5, 3, 8, 1, 2};

AR
bubbleSort(arr, 5);

// Print sorted array

D
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]); // Output: 1 2 3 5 8

AN
}

return 0;
BH
}
AL
TP
O
IL
N

69
A Quick Notes on C Programming 70

9. String

1. What is a string in C?

Answer:

Y
A string in C is a sequence of characters terminated by a null character (\0). In C, strings
are stored as arrays of characters.

AR
Example:

char str[] = "Hello";

D
Here, str is a string that contains “Hello” and is stored as {'H', 'e', 'l', 'l', 'o', '\0'}.

AN
BH
2. How do you declare and initialize a string in C?

Answer:
You can declare and initialize a string using either a character array or a string literal.
AL

Example:
TP

char str1[6] = "Hello"; // Using a character array


char str2[] = "Hello"; // Using a string literal
char str3[] = {'H', 'i', '\0'}; // Manually adding the null character
O
IL

3. How do you print a string in C?


N

Answer:
You can print a string in C using printf with %s as the format specifier.

Example:

70
A Quick Notes on C Programming 71

char str[] = "Hello, World!";


printf("%s", str); // Output: Hello, World!

4. How do you read a string input from the user in C?

Answer:
To read a string, you can use scanf with %s or gets (though gets is generally avoided due

Y
to security issues).

AR
Example using scanf:

char name[20];

D
printf("Enter your name: ");
scanf("%s", name);

AN
4. How do you read a line(including white space) from the user in C?
BH
In C, the gets function was traditionally used to read an entire line of text, but it’s now
discouraged because it doesn’t limit input length, which can lead to buffer overflow
AL

vulnerabilities. Instead, you can use fgets to read a line safely. However, if you are
required to use gets, here’s how you would do it, keeping in mind that it may not be
allowed in newer standards like C11.
TP

Using gets (not recommended due to safety risks)


O

#include <stdio.h>
IL

int main() {

char str[100]; // Buffer to store the input string


N

printf("Enter a line of text: ");

gets(str); // Reads a line from standard input (unsafe)

printf("You entered: %s\n", str);

71
A Quick Notes on C Programming 72

return 0;

Using fgets (recommended approach)

#include <stdio.h>

int main() {

Y
char str[100]; // Buffer to store the input string

AR
printf("Enter a line of text: ");

D
fgets(str, sizeof(str), stdin); // Reads up to 99 characters or until newline

AN
printf("You entered: %s", str);

return 0;
BH
}

In fgets, sizeof(str) ensures that fgets only reads up to the buffer limit, making it safer
than gets. fgets also stores the newline character (\n) at the end if there’s space in the
AL

buffer. This is a safer and preferred way to read a line in C.


TP
O

6. How do you find the length of a string in C?


IL

Answer:
You can find the length of a string using the strlen function from <string.h>, which counts
N

characters until the null character.

Example:

#include <stdio.h>
#include <string.h>

72
A Quick Notes on C Programming 73

int main() {
char str[] = "Hello";
int length = strlen(str);
printf("Length of the string: %d", length); // Output: 5
return 0;
}

Y
7. How do you copy one string to another in C?

AR
Answer:
To copy a string, use the strcpy function from <string.h>.

D
Example:

AN
#include <stdio.h>
#include <string.h>
BH
int main() {
char str1[] = "Hello";
char str2[10];
strcpy(str2, str1);
AL

printf("Copied string: %s", str2); // Output: Hello


return 0;
}
TP
O

8. How do you concatenate two strings in C?


IL

Answer:
You can concatenate two strings using the strcat function from <string.h>.
N

Example:

#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello, ";

73
A Quick Notes on C Programming 74

char str2[] = "World!";


strcat(str1, str2);
printf("Concatenated string: %s", str1); // Output: Hello, World!
return 0;
}

9. How do you compare two strings in C?

Y
AR
Answer:
Use the strcmp function from <string.h>, which returns 0 if strings are equal, a negative
value if the first string is less, and a positive value if the first string is greater.

D
Example:

AN
#include <stdio.h>
#include <string.h>
BH
int main() {
char str1[] = "Hello";
char str2[] = "World";
AL

if (strcmp(str1, str2) == 0) {
printf("Strings are equal.");
} else {
TP

printf("Strings are not equal.");


}
return 0;
O

}
IL
N

10. What does the null character '\0' do in a string?

Answer:
The null character '\0' marks the end of a string in C. It is essential because functions like
strlen and printf rely on it to determine where the string ends.

74
A Quick Notes on C Programming 75

11. How do you reverse a string in C?

Answer:
You can reverse a string by swapping characters from both ends without using strrev.

Example:

#include <stdio.h>

Y
#include <string.h>

AR
int main() {
char str[] = "Hello";
int len = strlen(str);

D
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
AN
BH
}

printf("Reversed string: %s", str); // Output: olleH


return 0;
AL

}
TP

12. What are common string functions in <string.h>?


O

Answer:
Some common string functions are:
IL

➢ strlen – Get string length


N

➢ strcpy – Copy one string to another


➢ strcat – Concatenate two strings
➢ strcmp – Compare two strings
➢ strstr – Find a substring in a string

75
A Quick Notes on C Programming 76

13. How can you check if a string is empty in C?

Answer:
Check if the first character is the null character ('\0') or if strlen returns 0.

Example:

#include <stdio.h>

Y
#include <string.h>

AR
int main() {
char str[] = "";

D
if (strlen(str) == 0) {
printf("The string is empty.");
} else {

}
printf("The string is not empty.");
AN
BH
return 0;
}
AL

14. How do you convert a string to uppercase or lowercase in C?


TP

Answer:
Use toupper and tolower functions from <ctype.h> to convert each character.
O

Example (Converting to Uppercase):


IL

#include <stdio.h>
#include <ctype.h>
N

int main() {
char str[] = "Hello";
for (int i = 0; str[i] != '\0'; i++) {
str[i] = toupper(str[i]);
}
printf("Uppercase: %s", str); // Output: HELLO

76
A Quick Notes on C Programming 77

return 0;
}

15. How do you find a substring within a string?

Answer:
Use the strstr function from <string.h>. It returns a pointer to the first occurrence of the

Y
substring, or NULL if not found.

AR
Example:

#include <stdio.h>

D
#include <string.h>

AN
int main() {
char str[] = "Hello, World!";
char *substr = strstr(str, "World");
BH
if (substr != NULL) {
printf("Substring found: %s", substr); // Output: World!
} else {
AL

printf("Substring not found.");


}
return 0;
TP

16. How does strcmp function work?


O

The strcmp function in C, defined in the <string.h> library, is used to compare two strings
IL

character by character. It returns an integer value based on the *lexicographical


comparison of the two strings:
N

• Returns 0 if both strings are equal.

• Returns a negative value if the first string is lexicographically less than the
second.

77
A Quick Notes on C Programming 78

• Returns a positive value if the first string is lexicographically greater than the
second.

How strcmp Works Internally

1. strcmp starts comparing the two strings from the first character of each string.

2. It moves character by character, comparing ASCII values, until it finds a


difference or reaches the null character ('\0') in either of the strings.

Y
AR
3. If it finds a difference in ASCII values, it returns the difference (positive or
negative).

4. If it reaches the end of both strings without finding any difference, it returns 0.

D
Example of strcmp

#include <stdio.h>
#include <string.h> AN
BH
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
AL

char str3[] = "World";

int result1 = strcmp(str1, str2); // Comparing "Hello" and "Hello"


TP

int result2 = strcmp(str1, str3); // Comparing "Hello" and "World"

if (result1 == 0) {
O

printf("str1 and str2 are equal.\n"); // Output: str1 and str2 are equal.
} else {
IL

printf("str1 and str2 are not equal.\n");


}
N

if (result2 < 0) {
printf("str1 is less than str3.\n"); // Output: str1 is less than str3.
} else if (result2 > 0) {
printf("str1 is greater than str3.\n");
} else {
printf("str1 and str3 are equal.\n");

78
A Quick Notes on C Programming 79

return 0;
}

Explanation of Results

1. For strcmp(str1, str2), the result is 0 because "Hello" and "Hello" are identical.

Y
2. For strcmp(str1, str3), the result is negative because "Hello" is lexicographically

AR
less than "World". This is because H (ASCII 72) is less than W (ASCII 87).

Note

D
• strcmp is case-sensitive, so "hello" and "Hello" are considered different strings.

AN
• strcmp stops comparing at the first difference found, making it efficient.

• Lexicographical order is the ordering of strings based on the alphabetical order


BH
of their component characters, similar to how words are arranged in a
dictionary. In programming, lexicographical ordering is based on the ASCII (or
Unicode) values of characters, meaning that:
AL

1. Lowercase letters are treated differently than uppercase letters because


lowercase letters have higher ASCII values.
TP

2. Numbers and special characters also follow a specific order in ASCII, where 0-9
come before A-Z, and lowercase a-z follow uppercase letters.
O

Examples of Lexicographical Order


IL

1. "Apple" comes before "Banana" because A is lexicographically smaller than B.


N

2. "Apple" comes before "apple" in strict lexicographical order since uppercase A


(ASCII 65) is less than lowercase a (ASCII 97).

3. "Cat123" comes before "Cat2" because 1 (ASCII 49) is less than 2 (ASCII 50).

79
A Quick Notes on C Programming 80

10. User-defined function


1. What is a user-defined function in C?

Answer:
A user-defined function is a function created by the programmer to perform specific
tasks. Unlike built-in functions (like printf and scanf), user-defined functions are defined by

Y
the user and can be customized to perform particular operations repeatedly throughout

AR
the program.

D
2. Why do we use user-defined functions?

Answer:

AN
User-defined functions improve code readability, modularity, and reusability. By
organizing code into functions, complex programs become easier to understand and
BH
debug. Functions also help eliminate code duplication by allowing specific tasks to be
executed by simply calling the function instead of rewriting the code.
AL

3. How do you declare a user-defined function in C?


TP

Answer:
A function declaration (also called a prototype) tells the compiler about a function’s name,
O

return type, and parameters. It is typically placed before the main() function.
IL

Syntax:

return_type function_name(parameter_type1 parameter1, parameter_type2 parameter2, ...);


N

Example:

int add(int, int); // Declares a function 'add' that returns an int and takes two int parameters

80
A Quick Notes on C Programming 81

4. How do you define a user-defined function in C?

Answer:
A function definition provides the actual body of the function, containing the code that
will execute when the function is called.

Y
AR
D
AN
BH
AL

Syntax:
TP

return_type function_name(parameter_type1 parameter1, parameter_type2 parameter2, ...) {


// Function body (statements)
O

return value; // Optional return statement if the function returns a value


}
IL

Example:
N

int add(int a, int b) {


return a + b; // Adds two integers and returns the result
}

5. How do you call a user-defined function in C?

81
A Quick Notes on C Programming 82

Answer:
To call a function, use its name followed by parentheses with the required arguments
inside.

Example:

int result = add(3, 4); // Calls the 'add' function with arguments 3 and 4, stores the result in 'result'

Y
AR
6. What are the components of a function in C?

Answer:

D
A function has three main components: 1. Function Declaration: Informs the compiler
about the function. 2. Function Definition: Contains the actual code for the function. 3.

AN
Function Call: Executes the function.
BH
7. Can a function return more than one value?

Answer:
AL

No, a function can only return a single value directly. However, you can use pointers or
structures to return multiple values indirectly.
TP

8. What is the difference between void and other return types?


O

Answer:
IL

- void: Indicates that a function does not return a value. - Other return types (e.g., int,
float, char): Specifies that the function returns a value of that type.
N

9. Can you pass an array to a function? How?

82
A Quick Notes on C Programming 83

Answer:
Yes, you can pass an array to a function by specifying the array type followed by empty
square brackets.

Example:

void printArray(int arr[], int size) {


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

Y
printf("%d ", arr[i]);
}

AR
}

To call the function:

D
int arr[] = {1, 2, 3, 4};

AN
printArray(arr, 4); // Passes the array to the function
BH
10. What is recursion?

Answer:
Recursion is a process in which a function
AL

calls itself, either directly or indirectly, to


solve a problem. Recursive functions typically
TP

have a base case to terminate the recursion.


O

Example:
IL

int factorial(int n) {
if (n == 0) return 1; // Base case
N

return n * factorial(n - 1); // Recursive call


}

83
A Quick Notes on C Programming 84

11. What is the scope of a function parameter?

Answer:
The scope of a function parameter is local to the function, meaning the parameter is only
accessible within that function. It cannot be accessed outside the function.

Y
12. What is a function prototype, and why is it needed?

AR
Answer:
A function prototype is a declaration of a function that specifies its return type, name, and
parameters but does not include the function body. Prototypes allow the compiler to

D
check for errors in function calls before the function is defined.

Example:

int add(int, int); // Prototype AN


BH

13. What is the difference between actual and formal parameters?


AL

Answer:
- Actual parameters are the values passed to the function during a call. - Formal
TP

parameters are the variables defined in the function definition that receive the actual
parameter values.
O

Example:
IL

int add(int a, int b) { // a and b are formal parameters


return a + b;
N

int main() {
int result = add(3, 4); // 3 and 4 are actual parameters
}

84
A Quick Notes on C Programming 85

14. Can you nest functions in C?

Answer:
No, C does not support nested functions (i.e., defining a function within another function).
Functions must be defined separately at the same level.

Y
15. What is a function pointer?

AR
Answer:
A function pointer is a pointer that stores the address of a function. Function pointers
allow functions to be passed as arguments and executed dynamically.

D
Example:

#include <stdio.h>
AN
BH
int add(int a, int b) { return a + b; }

int main() {
int (*funcPtr)(int, int) = &add; // Function pointer to 'add'
AL

int result = funcPtr(5, 3); // Calls 'add' through the pointer


printf("Result: %d", result); // Output: Result: 8
return 0;
TP

}
O
IL
N

85
A Quick Notes on C Programming 86

11. Structure and Unions


1. What is a structure in C?

Answer:
A structure in C is a user-defined data type that groups different data types under a
single name, allowing for more complex data storage. It is created using the struct

Y
keyword and is useful for representing real-world objects with various properties.

AR
Example:

struct Person {

D
char name[50];

AN
int age;
float height;
};
BH
2. How do you declare and define a structure?
AL

Answer:
A structure is declared using the struct keyword, followed by the structure name and a
block containing the members (variables). You can also create structure variables at the
TP

time of declaration.

Example:
O

struct Car {
IL

char model[20];
int year;
N

float price;
} car1, car2;

3. How do you access members of a structure?

86
A Quick Notes on C Programming 87

Answer:
You can access members of a structure using the dot (.) operator.

Example:

struct Person person1;


strcpy(person1.name, "Alice");
person1.age = 25;

Y
printf("Name: %s\nAge: %d\n", person1.name, person1.age);

AR
4. Can structures in C contain other structures?

D
Answer:

AN
Yes, structures can be nested within other structures, allowing for complex data
organization.

Example:
BH
struct Address {
char city[30];
int zip;
AL

};
TP

struct Person {
char name[50];
struct Address address; // Nested structure
};
O
IL

5. What is the difference between structure declaration and structure definition?


N

Answer:
- Declaration: Provides the structure’s name and data type but does not allocate memory
for it. - Definition: Declares the structure and allocates memory for its members.

Example:

87
A Quick Notes on C Programming 88

struct Person; // Declaration


struct Person { // Definition
char name[50];
int age;
};

6. How do you pass a structure to a function?

Y
AR
Answer:
A structure can be passed to a function by value (copying the data) or reference (using a
pointer). Passing by reference is more efficient, especially with large structures.

D
By Value:

AN
void printPerson(struct Person p) {
printf("Name: %s\nAge: %d\n", p.name, p.age);
}
BH
By Reference:

void printPerson(struct Person *p) {


AL

printf("Name: %s\nAge: %d\n", p->name, p->age);


}
TP

7. Can you use an array within a structure?


O

Answer:
Yes, you can include arrays within a structure. This is commonly used for storing
IL

collections of data, such as names or lists of values.


N

Example:

struct Student {
char name[50];
int grades[5];
};

88
A Quick Notes on C Programming 89

8. What is typedef and how is it used with structures?

Answer:
The typedef keyword allows you to create an alias for the structure, making it easier to
declare variables of that structure type without repeatedly using struct.

Example:

Y
AR
typedef struct {
char name[50];
int age;
} Person;

D
AN
Person person1; // Now we can declare 'Person' without 'struct'
BH
9. How is memory allocated for a structure?

Answer:
Memory is allocated to each member of a structure individually, based on its data type.
AL

Padding bytes may also be added by the compiler to ensure alignment for efficient
access.
TP

10. Can you compare two structures directly using == or !=?


O

Answer:
IL

No, structures cannot be compared directly using == or !=. To compare two structures, you
must compare each member individually or use memcmp from the <string.h> library.
N

Example:

if (person1.age == person2.age && strcmp(person1.name, person2.name) == 0) {


printf("Both persons have the same data.\n");
}

89
A Quick Notes on C Programming 90

11. Can you initialize a structure at the time of declaration?

Answer:
Yes, a structure can be initialized when it is declared.

Example:

Y
struct Person person1 = {"Alice", 25, 5.6};

AR
12. What is a self-referential structure?

D
Answer:

AN
A self-referential structure is a structure that includes a pointer to itself. This is commonly
used to build linked data structures like linked lists and trees.
BH
Example:

struct Node {
int data;
AL

struct Node *next; // Pointer to another Node


};
TP

13. Can structures contain functions in C?


O

Answer:
No, structures in C cannot contain functions directly. However, they can contain pointers
IL

to functions, which can then be assigned functions to operate on structure data.


N

Example:

struct Operation {
int (*operation)(int, int); // Function pointer
};

90
A Quick Notes on C Programming 91

14. What is a bit field in a structure?

Answer:
A bit field is a way to allocate a specific number of bits for a structure member, allowing
efficient use of memory when storing flags or small values.

Example:

Y
struct Flags {

AR
unsigned int flag1 : 1;
unsigned int flag2 : 1;
};

D
AN
15. What is the size of a structure?

Answer:
BH
The size of a structure is the sum of the sizes of its members plus any padding added by
the compiler. Padding ensures efficient memory access by aligning data to specific
memory boundaries.
AL

16. Can you use pointers with structures?


TP

Answer:
Yes, pointers can be used with structures to dynamically allocate memory and access
O

structure members through pointers. The arrow (->) operator is used to access members
via pointers.
IL

Example:
N

struct Person *p = &person1;


p->age = 30; // Using a pointer to access and modify members

17. What is the purpose of the . and -> operators with structures?

91
A Quick Notes on C Programming 92

Answer:
The . operator is used to access structure members through a variable, while the ->
operator is used to access members through a pointer to a structure.

Example:

person1.age = 25; // Using . operator


p->age = 25; // Using -> operator with pointer

Y
AR
18. Can structures be assigned directly in C?

D
Answer:
Yes, structures can be assigned to each other directly if they are of the same type. This

AN
copies all members from one structure to the other.

Example:
BH
struct Person person1 = {"Alice", 25};
struct Person person2;
person2 = person1; // Copies all members of person1 to person2
AL

19. Can structures be used with dynamic memory allocation?


TP

Answer:
Yes, you can allocate memory for a structure dynamically using functions like malloc.
O

Example:
IL

struct Person *p = (struct Person*) malloc(sizeof(struct Person));


N

p->age = 25;

20. What are the advantages of using structures in C?

92
A Quick Notes on C Programming 93

Answer:
Structures allow the grouping of different data types into a single unit, making code more
organized, easier to read, and more manageable. They enable representing complex
data and are fundamental in creating data structures such as linked lists, trees, and
records.

Y
1. What is a union in C?

AR
Answer:
A union in C is a user-defined data type similar to a structure, but all members share the
same memory location. This means only one member can hold a value at a time, which

D
allows unions to save memory when only one value is needed at any given time. It is

AN
defined using the union keyword.

Example:
BH
union Data {
int i;
float f;
char str[20];
AL

};
TP

2. How is memory allocated for a union?


O

Answer:
The size of a union is equal to the size of its largest member, as all members share the
IL

same memory location. This shared memory allocation makes unions memory-efficient
when storing only one member’s value at a time.
N

3. How do you declare and initialize a union?

93
A Quick Notes on C Programming 94

Answer:
A union is declared similarly to a structure, using the union keyword. It can be initialized
by assigning a value to one of its members.

Example:

union Data data;


data.i = 10; // Initializes the integer member

Y
Or directly upon declaration:

AR
union Data data = {10}; // Initializes the integer member i

D
AN
4. How do you access members of a union?

Answer:
Union members are accessed using the dot (.) operator, similar to structures. However,
BH
only one member should be accessed at a time, as assigning a value to one member can
overwrite the values of others.

Example:
AL

union Data data;


data.i = 10;
TP

printf("Integer: %d\n", data.i);


data.f = 5.5;
printf("Float: %.1f\n", data.f);
O
IL

5. What happens when you assign values to multiple union members?


N

Answer:
When you assign a value to one union member, it overwrites any previously assigned
value. Since all members share the same memory, only the last assigned member will
have a valid value.

94
A Quick Notes on C Programming 95

6. How do unions differ from structures?

Answer:
- Memory Allocation: In a union, all members share the same memory, so the size of a
union is determined by its largest member. In a structure, each member has its own
memory, and the total size is the sum of all members’ sizes. - Value Holding: In a union,
only one member can hold a valid value at a time. In a structure, all members can hold

Y
values simultaneously.

AR
7. Can unions be nested within structures?

D
Answer:

AN
Yes, a union can be a member of a structure. This allows a structure to contain a union
alongside other members, providing flexible data representation.

Example:
BH
struct Employee {
char name[50];
union {
AL

int id;
char passport[10];
TP

} idInfo;
};
O

8. Can a union contain an array?


IL

Answer:
N

Yes, a union can contain an array as a member. The array will occupy the memory
allocated for the union.

Example:

union Data {
int i;

95
A Quick Notes on C Programming 96

char str[20];
};

9. What is the purpose of using unions in C?

Answer:
Unions are used to save memory when different types of data are needed at different

Y
times. They are particularly useful in low-level programming, embedded systems, and

AR
when handling data that can have multiple interpretations, such as data packets in
network programming.

D
AN
10. Can unions be passed to functions?

Answer:
Yes, unions can be passed to functions either by value (copying the data) or by reference
BH
(using a pointer).

Example:
AL

void printData(union Data d) {


printf("Integer: %d\n", d.i);
}
TP

void printDataPtr(union Data *d) {


printf("Float: %f\n", d->f);
O

}
IL
N

11. How do you use pointers with unions?

Answer:
Pointers can be used with unions to dynamically allocate memory or pass unions to
functions by reference. The arrow (->) operator is used to access union members through
a pointer.

96
A Quick Notes on C Programming 97

Example:

union Data *dataPtr;


dataPtr = (union Data*) malloc(sizeof(union Data));
dataPtr->i = 10;
printf("Integer: %d\n", dataPtr->i);

Y
12. Can you initialize a union with multiple values?

AR
Answer:
No, only one union member can be initialized at a time because all members share the
same memory. Initializing multiple members at once would lead to ambiguity.

D
AN
13. What is a bit field, and can it be used with unions?
BH
Answer:
A bit field allows a structure member to use a specific number of bits, which can save
memory. However, bit fields are typically used with structures, not unions, as unions
require all members to share the same memory.
AL
TP

14. How do unions affect memory usage?

Answer:
O

Unions can significantly reduce memory usage because only one member occupies
memory at any time. This is beneficial in memory-constrained applications where only
IL

one of several types of data needs to be stored at once.


N

15. Can you compare two unions directly?

Answer:
No, unions cannot be compared directly with == or !=. To compare two unions, you must

97
A Quick Notes on C Programming 98

compare each member individually or use a memory comparison function like memcmp
from <string.h>.

16. What is a self-referential union?

Answer:
A self-referential union is a union that contains a pointer to another instance of the same

Y
union type. This is rare but can be useful in certain data structures where alternate types

AR
are needed within the same linked structure.

Example:

D
union Node {

AN
int data;
union Node *next; // Points to another Node of the same union type
};
BH
17. How do you define and use an anonymous union?
AL

Answer:
An anonymous union is a union that does not have a name. It is often declared within
structures to allow direct access to its members.
TP

Example:
O

struct Employee {
char name[50];
IL

union { // Anonymous union


int id;
N

char passport[10];
};
};

struct Employee emp;


emp.id = 12345; // Access directly

98
A Quick Notes on C Programming 99

18. What are some applications of unions?

Answer:
Unions are useful for: - Memory Optimization: In low-level programming where memory
efficiency is critical. - Embedded Systems: For representing hardware registers where
each bit or group of bits may have a different interpretation. - Data Interpretation: When

Y
data can be of multiple types, such as network packets or sensor data. - Tagged Unions:
In cases where the type of data stored changes at runtime, unions can be combined with

AR
enums to create tagged unions, identifying the active data type.

D
19. Can unions be initialized with typedef?

Answer:
AN
Yes, unions can be used with typedef to simplify their usage, just like structures.
BH
Example:

typedef union {
int i;
AL

float f;
} Data;
TP

Data data1;
data1.i = 10;
O
IL

20. How do unions compare to structures in terms of performance?


N

Answer:
Unions can sometimes be faster due to reduced memory usage, especially in cases
where only one member is needed at a time. However, the choice between structures
and unions should be based on design needs rather than performance alone, as both
structures and unions are efficient for their intended purposes.

99
A Quick Notes on C Programming 100

12. Pointers
Introduction to Pointers in C

Pointers are a fundamental feature of C programming that allow for powerful memory
management and manipulation. For beginners, pointers can be tricky to understand at
first, but once you grasp their basics, they become a valuable tool in C programming.

Y
AR
1. What is a Pointer?

A pointer is a variable that stores the memory address of another variable. Instead of

D
holding a specific value (like an integer or character), a pointer “points” to the location

AN
where a value is stored in memory.

Example:
BH
int x = 10;
int *p = &x; // p is a pointer to the address of x

In this example: - x is an integer variable with a value of 10. - p is a pointer variable that
AL

stores the address of x.


TP
O
IL
N

100
A Quick Notes on C Programming 101

2. Why Use Pointers?

Pointers are useful for: - Dynamic Memory Allocation: Managing memory manually (with
malloc and free). - Arrays and Strings: Efficiently handling arrays and strings. - Function
Arguments: Passing variables by reference to functions. - Data Structures: Implementing
complex data structures (like linked lists).

Y
AR
3. Basic Pointer Syntax

1. Declaring a Pointer: Use the * symbol to declare a pointer. c int *ptr;

D
2. Assigning an Address: Use the & (address-of) operator to get the memory
address of a variable. c int x = 5; int *ptr = &x;

AN
3. Dereferencing a Pointer: Use the * operator to access or modify the value at
the memory location the pointer is pointing to. c printf("%d", *ptr); // Outputs
BH
the value of x, which is 5
AL

4. Declaring and Initializing Pointers

To declare a pointer, specify the data type followed by an asterisk (*), and then the pointer
TP

name.

Example:
O

int x = 100;
IL

int *p = &x; // p now holds the address of x

• int *p declares a pointer p of type int.


N

• &x assigns the address of x to p.

5. Dereferencing a Pointer

101
A Quick Notes on C Programming 102

Dereferencing a pointer means accessing the value at the memory address the pointer
holds. This is done using the * symbol before the pointer variable.

Example:

int x = 10;
int *p = &x;
printf("%d", *p); // Outputs 10, the value of x

Y
AR
6. Pointer Arithmetic

Pointers allow you to perform arithmetic operations, mainly useful with arrays: -

D
Increment (p++): Moves the pointer to the next memory location. - Decrement (p--):

AN
Moves the pointer to the previous memory location.

Example:
BH
int arr[3] = {1, 2, 3};
int *p = arr;
printf("%d", *(p + 1)); // Accesses the second element, 2
AL

7. Pointers and Arrays


TP

Pointers are closely linked with arrays: - The name of an array is a pointer to its first
element. - You can access array elements using pointers and pointer arithmetic.
O

Example:
IL

int arr[3] = {10, 20, 30};


N

int *p = arr;
printf("%d", *(p + 2)); // Accesses the third element, 30

8. Pointers and Functions

102
A Quick Notes on C Programming 103

You can pass pointers to functions, allowing functions to modify the original variable’s
value directly.

Example:

void updateValue(int *p) {


*p = 20; // Changes the value of the variable to which p points
}

Y
int main() {

AR
int x = 10;
updateValue(&x);
printf("%d", x); // Outputs 20

D
}

9. Dynamic Memory Allocation AN


BH
C provides functions like malloc and free to dynamically allocate and free memory, which
is essential for creating variables at runtime.

Example:
AL

int *p = (int*) malloc(sizeof(int)); // Allocates memory for an integer


*p = 10;
TP

printf("%d", *p); // Outputs 10


free(p); // Frees the allocated memory
O
IL

10. Null Pointer


N

A null pointer is a pointer that points to nothing (address 0). It’s often used to indicate that
the pointer is not assigned to any variable.

Example:

int *p = NULL;
if (p == NULL) {

103
A Quick Notes on C Programming 104

printf("Pointer is not assigned.");


}

11. Common Errors with Pointers

1. Uninitialized Pointers: Always initialize pointers, either by assigning an address


or setting them to NULL.

Y
2. Dangling Pointers: A pointer that still points to memory that has been freed.

AR
3. Pointer Arithmetic Mistakes: Ensure pointers point to valid memory locations
before accessing or modifying them.

D
AN
Here are some examples of pointer code with explanations to help beginners understand
how pointers work.
BH

Example 1: Simple Pointer Declaration and Dereferencing


AL

Code:

#include <stdio.h>
TP

int main() {
int x = 5;
O

int *p = &x; // Pointer p holds the address of x


IL

printf("Value of x: %d\n", x);


printf("Address of x: %p\n", &x);
N

printf("Value of p (address of x): %p\n", p);


printf("Value at address stored in p: %d\n", *p); // Dereferencing p to get value of x

return 0;
}

104
A Quick Notes on C Programming 105

Question: What is the value of *p, and why?

Explanation:
- *p dereferences the pointer p to get the value stored at the memory address p points to
(which is the address of x). - Since x = 5, the output of *p is 5. - This example demonstrates
how pointers store addresses and how dereferencing retrieves the value at that address.

Y
Example 2: Changing Variable Value Through a Pointer

AR
Code:

#include <stdio.h>

D
void changeValue(int *p) {

}
AN
*p = 20; // Modify the value at the address p points to
BH
int main() {
int x = 10;
printf("Value of x before: %d\n", x);
changeValue(&x); // Pass address of x to function
AL

printf("Value of x after: %d\n", x);

return 0;
TP

Question: How does changeValue modify the value of x in main?


O

Explanation:
IL

- The function changeValue takes a pointer to an int as a parameter. - When &x is passed
to changeValue, p points to x’s address. - Inside changeValue, *p = 20 changes the value of
N

x to 20 because p points directly to x. - This example shows how pointers allow functions
to modify variables outside their local scope.

105
A Quick Notes on C Programming 106

Example 3: Array Access with Pointers

Code:

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40};

Y
int *p = arr; // p points to the first element of the array

AR
for (int i = 0; i < 4; i++) {
printf("arr[%d] = %d\n", i, *(p + i)); // Access array elements using pointer arithmetic
}

D
return 0;

AN
}

Question: How does the code access elements of the array using the pointer p?
BH
Explanation:
- p points to the first element of the array (arr[0]). - *(p + i) accesses each element in the
array by moving p through the array using pointer arithmetic. - *(p + i) is equivalent to arr[i],
AL

showing how pointers and arrays are closely related.


TP

Example 4: Pointer Arithmetic

Code:
O

#include <stdio.h>
IL

int main() {
N

int arr[] = {5, 10, 15};


int *p = arr;

printf("Value at p: %d\n", *p); // Output: 5


printf("Value at p+1: %d\n", *(p+1)); // Output: 10
printf("Value at p+2: %d\n", *(p+2)); // Output: 15

106
A Quick Notes on C Programming 107

return 0;
}

Question: Why does *(p+1) give the value 10?

Explanation:
- p points to the first element of arr, which is 5. - Adding 1 to p moves it to the next integer
in memory, which is arr[1], with a value of 10. - This example illustrates how pointer

Y
arithmetic works, especially useful in handling arrays.

AR
Example 5: Dynamic Memory Allocation Using malloc

D
Code:

#include <stdio.h>
#include <stdlib.h> AN
BH
int main() {
int *p = (int*) malloc(3 * sizeof(int)); // Allocate memory for 3 integers
if (p == NULL) {
AL

printf("Memory allocation failed.\n");


return 1;
}
TP

p[0] = 5;
p[1] = 10;
O

p[2] = 15;
IL

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


printf("p[%d] = %d\n", i, p[i]);
N

free(p); // Free the allocated memory


return 0;
}

107
A Quick Notes on C Programming 108

Question: What does malloc do in this example, and why do we need free?

Explanation:
- malloc allocates a block of memory large enough to hold three integers and returns a
pointer to this memory. - p[i] accesses each allocated memory element like an array. -
free(p) deallocates the memory after use, which is essential to prevent memory leaks.

Y
Example 6: Null Pointer Check

AR
Code:

#include <stdio.h>

D
int main() {
int *p = NULL;

if (p == NULL) {
AN
BH
printf("p is a null pointer.\n");
} else {
printf("p is not a null pointer.\n");
}
AL

return 0;
}
TP

Question: Why is it important to check if a pointer is null?


O

Explanation:
- A null pointer indicates that the pointer does not point to any valid memory location. -
IL

Checking for NULL prevents dereferencing a null pointer, which would lead to a runtime
error. - This example highlights good practices when working with pointers.
N

Example 7: Pointer to Pointer

Code:

108
A Quick Notes on C Programming 109

#include <stdio.h>

int main() {
int x = 10;
int *p = &x;
int **pp = &p; // Pointer to pointer

printf("Value of x: %d\n", x);

Y
printf("Value of *p (value of x): %d\n", *p);
printf("Value of **pp (value of x): %d\n", **pp);

AR
return 0;
}

D
Question: What does **pp represent in this code?

Explanation:

AN
- p is a pointer to x, so *p gives the value of x. - pp is a pointer to p, making it a pointer to a
pointer. - **pp dereferences pp twice to get the value of x, demonstrating how pointers to
BH
pointers work.
AL

Example 8: Function Returning a Pointer

Code:
TP

#include <stdio.h>
O

int* findMax(int *a, int *b) {


return (*a > *b) ? a : b; // Returns pointer to the larger value
IL

}
N

int main() {
int x = 20, y = 10;
int *max = findMax(&x, &y);

printf("The larger value is: %d\n", *max);

109
A Quick Notes on C Programming 110

return 0;
}

Question: How does the function findMax return the larger value?

Explanation:
- findMax compares the values of *a and *b, returning a pointer to the larger one. - In main,
*max gives the larger value. - This example shows how pointers can be used to return
variable addresses from functions.

Y
AR
D
AN
BH
AL
TP
O
IL
N

110
A Quick Notes on C Programming 111

13. Dynamic Memory Allocation in C


Dynamic Memory Allocation in C

Dynamic memory allocation in C allows programs to request memory at runtime, rather


than at compile-time. This is especially useful when the exact amount of memory
required cannot be determined beforehand, such as when working with data structures

Y
like arrays, linked lists, or other variable-sized collections.

AR
1. Why Use Dynamic Memory Allocation?

D
Dynamic memory allocation is necessary when: - The memory requirements change

AN
during execution. - Data structures need flexible, scalable memory space. - You want to
allocate or deallocate memory while the program is running.
BH
2. Functions for Dynamic Memory Allocation

In C, the standard library provides four key functions for managing dynamic memory in
stdlib.h:
AL

1. malloc (Memory Allocation)


TP

2. calloc (Contiguous Allocation)

3. realloc (Reallocation)
O

4. free (Free Allocated Memory)


IL
N

3. Using malloc

The malloc (memory allocation) function allocates a specified number of bytes and returns
a pointer to the beginning of the allocated memory. The allocated memory contains
garbage values.

111
A Quick Notes on C Programming 112

Syntax:

ptr = (type*) malloc(size_in_bytes);

Example:

int *p = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers

Explanation: - Here, malloc reserves space for 5 integers, and p points to the start of this

Y
block. - The sizeof(int) helps determine the exact byte size for an integer on the system.

AR
4. Using calloc

The calloc (contiguous allocation) function also allocates memory, but it initializes all

D
elements to zero. It requires two arguments: the number of elements and the size of
each element.

Syntax:
AN
ptr = (type*) calloc(number_of_elements, size_of_each_element);
BH
Example:

int *p = (int*) calloc(5, sizeof(int)); // Allocates memory for 5 integers, initializes to 0


AL

Explanation: - calloc allocates a block of memory for 5 integers, initializing each to zero.
TP

5. Using realloc

The realloc (reallocation) function resizes an existing block of memory. It is useful when
O

the allocated memory needs to expand or contract. realloc can move the allocated
memory block to a new location if necessary.
IL

Syntax:
N

ptr = (type*) realloc(ptr, new_size_in_bytes);

Example:

int *p = (int*) malloc(3 * sizeof(int)); // Initial allocation for 3 integers


p = (int*) realloc(p, 5 * sizeof(int)); // Resize to hold 5 integers

112
A Quick Notes on C Programming 113

Explanation: - The first malloc allocates space for 3 integers. - realloc resizes the memory
to hold 5 integers. It keeps the original values and may reallocate to a new location if
necessary.

6. Using free

The free function deallocates previously allocated memory, making it available for future
use. Always free dynamically allocated memory to avoid memory leaks.

Y
Syntax:

AR
free(ptr);

Example:

D
int *p = (int*) malloc(5 * sizeof(int));

AN
free(p); // Deallocates the memory allocated to p
p = NULL; // Good practice to set pointer to NULL after freeing
BH
Explanation: - After using free(p), the pointer p no longer points to valid memory. - Setting
p = NULL helps prevent accidental use of a freed pointer.
AL

7. Example Program Using malloc and free


TP

Here is a simple example showing how to dynamically allocate and free memory for an
integer array.

#include <stdio.h>
O

#include <stdlib.h>
IL

int main() {
N

int n;
printf("Enter the number of elements: ");
scanf("%d", &n);

// Dynamically allocate memory for n integers


int *arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {

113
A Quick Notes on C Programming 114

printf("Memory allocation failed\n");


return 1;
}

// Input values
for (int i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);

Y
}

AR
// Display values
printf("You entered: ");
for (int i = 0; i < n; i++) {

D
printf("%d ", arr[i]);
}

// Free the allocated memory


free(arr); AN
BH
arr = NULL; // Avoid dangling pointer

return 0;
}
AL

Explanation: 1. malloc is used to allocate memory for n integers. 2. We check if memory


allocation was successful (if (arr == NULL)). 3. After using the memory, free(arr) releases the
TP

memory back to the system.


O

8. Common Errors in Dynamic Memory Allocation


IL

1. Memory Leaks: Failing to free allocated memory leads to memory leaks.


N

2. Dangling Pointers: Using a pointer after freeing the memory it points to.

3. Double Freeing: Calling free on the same memory address more than once.

4. Using Uninitialized Memory: Accessing memory before initialization (e.g., using


malloc without checking if allocation was successful).

114
A Quick Notes on C Programming 115

Y
AR
D
AN
BH
AL
TP
O
IL
N

115
A Quick Notes on C Programming 116

14. File Management in C


File Management in C

File management in C allows programs to read from and write data to external files,
enabling data storage beyond the program’s runtime. This is essential for creating
programs that persist data across executions, like databases, logs, configuration files,

Y
and more. The C Standard Library provides functions for handling file operations,

AR
primarily located in the stdio.h library.

D
1. Types of File Operations

AN
The primary operations on files in C include: - Creating a File: Open a file for writing, and
if it doesn’t exist, create it. - Opening a File: Accessing an existing file for reading, writing,
or appending. - Reading from a File: Extracting data from a file. - Writing to a File:
BH
Inserting or modifying data in a file. - Closing a File: Properly ending the interaction with
a file.
AL

2. File Pointers and FILE Structure


TP

In C, files are accessed through pointers of type FILE. A FILE pointer provides access to a
file’s contents and keeps track of the current position in the file.
O

Example:
IL

FILE *filePtr; // Declaration of a file pointer


N

The filePtr pointer can then be used to open, read, write, and close files.

3. Opening a File with fopen

116
A Quick Notes on C Programming 117

To perform file operations, you need to open the file using fopen, which takes two
arguments: the filename and the mode of operation.

Syntax:

FILE *fopen(const char *filename, const char *mode);

File Modes: - "r": Open a file for reading. - "w": Open a file for writing. Creates a new file if

Y
it doesn’t exist or truncates the file if it does. - "a": Open a file for appending. - "r+": Open a
file for both reading and writing. - "w+": Open a file for reading and writing, creates a new

AR
file or truncates an existing file. - "a+": Open a file for reading and appending.

Example:

D
FILE *filePtr = fopen("data.txt", "w");

AN
if (filePtr == NULL) {
printf("Error opening file.\n");
return 1;
BH
}

Explanation: - The above code opens data.txt in write mode. If it fails (e.g., file system
permissions issue), filePtr will be NULL.
AL

4. Closing a File with fclose


TP

Closing a file after operations is essential to save changes and free up system resources.
O

Syntax:
IL

int fclose(FILE *filePtr);


N

Example:

fclose(filePtr);

• Closing the file with fclose ensures the file is saved properly and any resources
are released.

117
A Quick Notes on C Programming 118

5. Writing to a File with fprintf and fputc

You can write to a file using: - fprintf: Similar to printf, but writes formatted data to a file. -
fputc: Writes a single character to a file.

Example using fprintf:

FILE *filePtr = fopen("data.txt", "w");

Y
if (filePtr != NULL) {

AR
fprintf(filePtr, "Hello, World!\n"); // Writes formatted text to the file
fclose(filePtr);
}

D
Example using fputc:

AN
FILE *filePtr = fopen("data.txt", "a");
if (filePtr != NULL) {
fputc('A', filePtr); // Appends 'A' to the file
BH
fclose(filePtr);
}
AL

6. Reading from a File with fscanf and fgetc

You can read from a file using: - fscanf: Reads formatted input from a file. - fgetc: Reads a
TP

single character from a file.

Example using fscanf:


O

FILE *filePtr = fopen("data.txt", "r");


IL

if (filePtr != NULL) {
char str[50];
N

int num;
fscanf(filePtr, "%s %d", str, &num); // Reads a string and an integer
printf("Read from file: %s %d\n", str, num);
fclose(filePtr);
}

118
A Quick Notes on C Programming 119

Example using fgetc:

FILE *filePtr = fopen("data.txt", "r");


if (filePtr != NULL) {
char ch;
while ((ch = fgetc(filePtr)) != EOF) { // Reads until End of File (EOF)
putchar(ch); // Prints each character
}
fclose(filePtr);

Y
}

AR
7. Other Useful File Functions

D
• fgets and fputs: For handling strings more effectively.

AN
– fgets reads a line from a file into a string.
BH
– fputs writes a string to a file.

Example with fgets and fputs:

FILE *filePtr = fopen("data.txt", "r+");


AL

if (filePtr != NULL) {
char line[100];
TP

fgets(line, 100, filePtr); // Reads a line from the file


printf("Read line: %s", line);

fputs("This is a new line.\n", filePtr); // Adds a new line to the file


O

fclose(filePtr);
IL

8. Checking the End of a File with feof


N

feof is used to check if the End of File (EOF) has been reached.

Example:

FILE *filePtr = fopen("data.txt", "r");


if (filePtr != NULL) {

119
A Quick Notes on C Programming 120

while (!feof(filePtr)) {
char ch = fgetc(filePtr);
if (ch != EOF) {
putchar(ch);
}
}
fclose(filePtr);
}

Y
AR
9. Binary File I/O with fread and fwrite

Binary files store data in binary format rather than plain text. fread and fwrite are used for

D
reading and writing binary files.

Writing to a Binary File:

FILE *filePtr = fopen("data.bin", "wb"); AN


BH
int arr[] = {10, 20, 30, 40};
fwrite(arr, sizeof(int), 4, filePtr); // Writes the array to the binary file
fclose(filePtr);
AL

Reading from a Binary File:

FILE *filePtr = fopen("data.bin", "rb");


TP

int arr[4];
fread(arr, sizeof(int), 4, filePtr); // Reads 4 integers from the binary file
fclose(filePtr);
O
IL

Here’s a simple C program to copy the contents of one file to another file. This program
reads the source file byte by byte and writes each byte to the destination file.
N

#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *sourceFile, *destFile;
char sourcePath[100], destPath[100];

120
A Quick Notes on C Programming 121

char ch;

// Input file paths


printf("Enter source file path: ");
scanf("%s", sourcePath);

printf("Enter destination file path: ");


scanf("%s", destPath);

Y
// Open source file in read mode

AR
sourceFile = fopen(sourcePath, "r");
if (sourceFile == NULL) {
printf("Cannot open source file.\n");

D
exit(1);
}

// Open destination file in write mode


destFile = fopen(destPath, "w"); AN
BH
if (destFile == NULL) {
printf("Cannot open destination file.\n");
fclose(sourceFile);
exit(1);
AL

// Copy content from source file to destination file


TP

while ((ch = fgetc(sourceFile)) != EOF) {


fputc(ch, destFile);
}
O

printf("File copied successfully.\n");


IL

// Close files
N

fclose(sourceFile);
fclose(destFile);

return 0;
}

Explanation:

121
A Quick Notes on C Programming 122

1. File Paths: The program takes the paths of the source and destination files as
inputs.

2. Opening Files:

– Opens the source file in "r" (read) mode.

– Opens the destination file in "w" (write) mode.

Y
3. Copying Data:

AR
– Reads each character from the source file using fgetc until EOF
(end-of-file) is reached.

D
– Writes each character to the destination file using fputc.

AN
4. Closing Files: Both files are closed to ensure all data is saved and resources
are released.
BH
This program will create a copy of the source file at the specified destination path.
AL
TP
O
IL
N

122
A Quick Notes on C Programming 123

15. ASCII values


Here’s a table showing ASCII values for characters from 0 to 127. Each character is
represented by a unique decimal, hexadecimal, and octal ASCII code.

ASCII (Dec) ASCII (Hex) ASCII (Oct) Character Description

Y
0 00 000 NUL Null

AR
1 01 001 SOH Start of Header

2 02 002 STX Start of Text

D
3 03 003 ETX End of Text

5
04

05
004

005 AN EOT

ENQ
End of Transmission

Enquiry
BH
6 06 006 ACK Acknowledgment

7 07 007 BEL Bell


AL

8 08 010 BS Backspace
TP

9 09 011 TAB Horizontal Tab

10 0A 012 LF Line Feed


O

11 0B 013 VT Vertical Tab


IL

12 0C 014 FF Form Feed


N

13 0D 015 CR Carriage Return

14 0E 016 SO Shift Out

15 0F 017 SI Shift In

123
A Quick Notes on C Programming 124

16 10 020 DLE Data Link Escape

17 11 021 DC1 Device Control 1

18 12 022 DC2 Device Control 2

19 13 023 DC3 Device Control 3

20 14 024 DC4 Device Control 4

Y
21 15 025 NAK Negative Acknowledgment

AR
22 16 026 SYN Synchronous Idle

D
23 17 027 ETB End of Block

AN
24 18 030 CAN Cancel

25 19 031 EM End of Medium


BH
26 1A 032 SUB Substitute

27 1B 033 ESC Escape


AL

28 1C 034 FS File Separator

29 1D 035 GS Group Separator


TP

30 1E 036 RS Record Separator


O

31 1F 037 US Unit Separator


IL

32 20 040 (space) Space


N

33 21 041 ! Exclamation mark

34 22 042 ” Double quotes

35 23 043 # Hash symbol

36 24 044 $ Dollar sign

124
A Quick Notes on C Programming 125

37 25 045 % Percent sign

38 26 046 & Ampersand

39 27 047 ’ Single quote

40 28 050 ( Open parenthesis

41 29 051 ) Close parenthesis

Y
42 2A 052 * Asterisk

AR
43 2B 053 + Plus sign

D
44 2C 054 , Comma

AN
45 2D 055 - Hyphen

46 2E 056 . Period
BH
47 2F 057 / Slash

48-57 30-39 060-071 0-9 Digits 0 to 9


AL

58 3A 072 : Colon

59 3B 073 ; Semicolon
TP

60 3C 074 < Less-than


O

61 3D 075 = Equal sign


IL

62 3E 076 > Greater-than


N

63 3F 077 ? Question mark

64 40 100 @ At symbol

65-90 41-5A 101-132 A-Z Uppercase letters A to Z

91 5B 133 [ Open bracket

125
A Quick Notes on C Programming 126

92 5C 134 \ Backslash

93 5D 135 ] Close bracket

94 5E 136 ^ Caret

95 5F 137 _ Underscore

96 60 140 ` Backtick

Y
97-122 61-7A 141-172 a-z Lowercase letters a to z

AR
123 7B 173 { Open curly brace

D
124 7C 174

AN
125 7D 175 } Close curly brace

126 7E 176 ~ Tilde


BH
127 7F 177 DEL Delete

This ASCII table includes control characters (0-31 and 127) and printable characters
(32-126). The ASCII values from 65 to 90 represent uppercase letters, while values from
AL

97 to 122 represent lowercase letters.


TP
O
IL
N

126
A Quick Notes on C Programming 127

16. C Libraries
Here’s an extended list of C libraries, their commonly used functions, a brief description,
and an example for each function:

Library Function Description Example

stdio.h printf Outputs formatted text printf("Hello, World!\n");

Y
to the console.

AR
scanf Reads formatted input int x; scanf("%d", &x);
from the console.

D
fopen Opens a file and returns FILE *file = fopen("file.txt", "r");
a file pointer.

fclose
AN
Closes an open file. fclose(file);
BH
fgetc Reads a single char c = fgetc(file);
character from a file.

fputc Writes a character to a fputc('A', file);


AL

file.

fgets Reads a string from a char buffer[100]; fgets(buffer, 100,


TP

file (up to a specified file);


length).
O

fputs Writes a string to a file. fputs("Hello, File!", file);


IL

fprintf Writes formatted text to fprintf(file, "Age: %d\n", age);


a file.
N

stdlib.h malloc Allocates a block of int *arr = malloc(10 * sizeof(int));


memory dynamically.

127
A Quick Notes on C Programming 128

calloc Allocates and zeroes a int *arr = calloc(10, sizeof(int));


block of memory
dynamically.

realloc Resizes a previously arr = realloc(arr, 20 * sizeof(int));


allocated memory
block.

Y
free Frees dynamically free(arr);
allocated memory.

AR
rand Generates a int r = rand();
pseudo-random integer.

D
srand Seeds the random srand(time(NULL));

AN
number generator with
a starting value.
BH
string.h strcpy Copies a string from strcpy(dest, source);
source to destination.

strncpy Copies a specified strncpy(dest, source, 5);


AL

number of characters
from source to
destination.
TP

strcat Concatenates two strcat(dest, source);


strings.
O

strncat Concatenates a strncat(dest, source, 3);


IL

specified number of
characters from one
N

string to another.

strlen Returns the length of a int len = strlen("Hello");


string.

128
A Quick Notes on C Programming 129

strcmp Compares two strings int result = strcmp(str1, str2);


lexicographically.

strncmp Compares up to a int result = strncmp(str1, str2, 5);


specified number of
characters of two
strings.

Y
strstr Finds the first char *ptr = strstr(str, "sub");
occurrence of a

AR
substring in a string.

strchr Finds the first char *ptr = strchr(str, 'a');

D
occurrence of a
character in a string.

strrchr Finds the last


AN
occurrence of a
char *ptr = strrchr(str, 'a');
BH
character in a string.

math.h pow Computes the power of double result = pow(2, 3);


a number.
AL

sqrt Computes the square double result = sqrt(16);


root of a number.
TP

ceil Rounds a number up to double result = ceil(3.14);


the nearest integer.
O

floor Rounds a number down double result = floor(3.14);


IL

to the nearest integer.


N

fabs Returns the absolute double result = fabs(-5.7);


value of a floating-point
number.

log Computes the natural double result = log(10);


logarithm of a number.

129
A Quick Notes on C Programming 130

exp Computes the double result = exp(2);


exponential (e^x) of a
number.

sin Computes the sine of double result = sin(3.14159 / 2);


an angle in radians.

cos Computes the cosine of double result = cos(3.14159);

Y
an angle in radians.

AR
tan Computes the tangent double result = tan(3.14159 / 4);
of an angle in radians.

D
ctype.h isalpha Checks if a character is int result = isalpha('A');
alphabetic.

isdigit
AN
Checks if a character is
a digit.
int result = isdigit('9');
BH
isalnum Checks if a character is int result = isalnum('1');
alphanumeric.
AL

isupper Checks if a character is int result = isupper('A');


uppercase.
TP

islower Checks if a character is int result = islower('a');


lowercase.
O

toupper Converts a character to char upper = toupper('a');


uppercase.
IL

tolower Converts a character to char lower = tolower('A');


N

lowercase.

time.h time Returns the current time_t t = time(NULL);


calendar time as a
time_t value.

130
A Quick Notes on C Programming 131

difftime Computes the double diff = difftime(time1,


difference in seconds time2);
between two time_t
values.

clock Returns the processor clock_t start = clock();


time consumed by the
program.

Y
asctime Converts struct tm to a char *str = asctime(local_time);

AR
human-readable string.

localtime Converts time_t to struct struct tm *local_time =

D
tm as local time. localtime(&t);

AN
gmtime Converts time_t to struct struct tm *utc_time = gmtime(&t);
tm as UTC.
BH
mktime Converts struct tm to time_t new_time = mktime(&tm);
time_t.

strftime Formats struct tm into a strftime(buffer, 100, "%Y-%m-%d


AL

string. %H:%M:%S", &tm);

assert.h assert Adds a diagnostic test assert(x > 0);


TP

to a program. If the
condition fails, the
program terminates.
O

errno.h errno Contains error codes if (fopen("nonexistent.txt", "r") ==


IL

returned by system NULL) perror("Error");


calls and library
N

functions.

perror Prints a descriptive perror("Error opening file");


error message based
on errno.

131
A Quick Notes on C Programming 132

strerror Returns a string that printf("Error: %s\n",


describes the error strerror(errno));
corresponding to errno.

conio.h getch Reads a character from char c = getch();


the keyboard, without
echoing it to the screen.

Y
getche Reads a character from char c = getche();
the keyboard and

AR
echoes it to the screen.

clrscr Clears the console clrscr();

D
screen.

AN
BH
AL
TP
O
IL
N

132

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy