A Quick Notes On C Programming
A Quick Notes On C Programming
A Quick Notes on
C Programming
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. String 71
1. What is a string in C? 71
IL
3
A Quick Notes on C Programming 4
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
1. What is a structure in C? 87
2. How do you declare and define a structure? 87
IL
4
A Quick Notes on C Programming 5
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
5
A Quick Notes on C Programming 6
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
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
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
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
8
A Quick Notes on C Programming 9
Y
AR
D
AN
BH
AL
TP
O
3. Structure of a C Program
IL
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
2. Defining Macros:
○ Macros allow you to define expressions or code fragments
N
#define SQUARE(x) (x * x)
10
A Quick Notes on C Programming 11
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.
● return 0;
● }
IL
In this example:
N
11
A Quick Notes on C Programming 12
Benefits of #define:
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
12
A Quick Notes on C Programming 13
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
Example:
N
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
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.
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
● return 0;
● }
●
O
● 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
Y
a step-by-step guide on how to set up and use Dev-C++ to write, compile, and run
AR
C programs.
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
○ 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
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.
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
Hello, World!
18
A Quick Notes on C Programming 19
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
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.
19
A Quick Notes on C Programming 20
● #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
● 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
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
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:
● 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):
D
○ Example: int x = 10;
○ Example:
float temp = 36.5;
double pi = 3.14159;
TP
Character (char):
O
Void (void):
Represents the absence of a value. Typically used for functions that return no
value.
23
A Quick Notes on C Programming 24
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;
24
A Quick Notes on C Programming 25
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
unsigned 4 0 to 4,294,967,295
int
AL
TP
1. #include <stdio.h>
IL
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:
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:
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
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() {
Y
count += i;
AR
}
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
● 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
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.
#include <stdio.h>
void counter() {
28
A Quick Notes on C Programming 29
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
#include <stdio.h>
int main() {
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.
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.
#include <stdio.h>
int main() {
return 0;
IL
}
N
File 2 (global.c):
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.
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
extern extern
O
31
A Quick Notes on C Programming 32
5. Operators
Operators in C Programming
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
+ 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;
2. Relational Operators
IL
== Equal to a == b
33
A Quick Notes on C Programming 34
!= Not equal to a != b
Y
>= Greater than or equal to a >= b
AR
<= Less than or equal to a <= b
D
Example:
int result;
AN
BH
result = (a > b); // result = 0 (false)
3. Logical Operators
N
Logical operators are used to perform logical operations in expressions and return a
boolean result.
34
A Quick Notes on C Programming 35
|| Logical OR (a || b)
! Logical !(a)
Y
NOT
AR
Example:
int a = 1, b = 0;
D
int result;
4. Bitwise Operators
O
Bitwise operators are used to perform operations at the bit level (binary digits).
IL
or e
| Bitwise OR a | b
35
A Quick Notes on C Programming 36
~ Bitwise NOT ~a
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)
5. Assignment Operators
36
A Quick Notes on C Programming 37
= Assigns value a = 10
Y
AR
-= Subtract and a -= 5
assign
D
*= Multiply and a *= 5
AN
assign
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
-- 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;
○
N
38
A Quick Notes on C Programming 39
○
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;
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
Example:
float x = 5.5;
int y = (int)x; // y = 5
39
A Quick Notes on C Programming 40
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
// Logical Operators
// Bitwise Operators
result = a & b;
40
A Quick Notes on C Programming 41
// Assignment Operators
a += 5;
// 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
Example:
IL
int a = 10, b = 5;
N
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;
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;
int a = 5, b;
43
A Quick Notes on C Programming 44
Syntax:
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
Example:
O
int a = 5;
IL
7. Bitwise Expressions
Bitwise expressions perform operations on binary representations of integers using
bitwise operators (&, |, ^, ~, <<, >>).
44
A Quick Notes on C Programming 45
Example:
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):
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:
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
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:
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.
This process of converting a smaller data type (like int) to a larger data type (like double)
is called type promotion.
TP
#include <stdio.h>
O
int main() {
IL
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() {
before division
IL
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
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.
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;
49
A Quick Notes on C Programming 50
return 0;
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
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
Example:
#include <stdio.h>
Y
AR
void display(int x) {
D
}
int main() { AN
BH
char ch = 'A';
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
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) {
}
N
Example:
#include <stdio.h>
52
A Quick Notes on C Programming 53
int main() {
if (number > 0) {
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
} else {
53
A Quick Notes on C Programming 54
Example:
#include <stdio.h>
int main() {
if (number > 0) {
Y
printf("The number is positive.\n");
AR
} else {
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
} else if (condition2) {
} else if (condition3) {
54
A Quick Notes on C Programming 55
} else {
Y
Example:
AR
#include <stdio.h>
D
int main() {
int number = 0;
AN
BH
if (number > 0) {
} else {
}
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) {
} else {
IL
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:
break;
AL
default:
TP
}
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
58
A Quick Notes on C Programming 59
Syntax:
Example:
#include <stdio.h>
Y
int main() {
AR
int number = 10;
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
5. The switch statement is useful for selecting one out of many possible actions
based on the value of an expression.
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
1. The goto statement causes the program to jump to the part of the code marked by
O
a label.
IL
int main() {
60
A Quick Notes on C Programming 61
if (number > 0) {
goto positive;
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
Answer:
TP
data_type array_name[size];
O
62
A Quick Notes on C Programming 63
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
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:
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.
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
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
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
Answer:
IL
Example:
N
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
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
Example:
N
66
A Quick Notes on C Programming 67
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
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
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
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
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
#include <stdio.h>
68
A Quick Notes on C Programming 69
Y
int main() {
int arr[5] = {5, 3, 8, 1, 2};
AR
bubbleSort(arr, 5);
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:
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
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
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
#include <stdio.h>
IL
int main() {
71
A Quick Notes on C Programming 72
return 0;
#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
Answer:
You can find the length of a string using the strlen function from <string.h>, which counts
N
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
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
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
}
IL
N
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
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
}
}
TP
Answer:
Some common string functions are:
IL
75
A Quick Notes on C Programming 76
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
Answer:
Use toupper and tolower functions from <ctype.h> to convert each character.
O
#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;
}
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
The strcmp function in C, defined in the <string.h> library, is used to compare two strings
IL
• 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.
1. strcmp starts comparing the two strings from the first character of each string.
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
if (result1 == 0) {
O
printf("str1 and str2 are equal.\n"); // Output: str1 and str2 are equal.
} else {
IL
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.
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
3. "Cat123" comes before "Cat2" because 1 (ASCII 49) is less than 2 (ASCII 50).
79
A Quick Notes on C Programming 80
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
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:
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
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
Example:
N
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
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
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:
Y
printf("%d ", arr[i]);
}
AR
}
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
Example:
IL
int factorial(int n) {
if (n == 0) return 1; // Base case
N
83
A Quick Notes on C Programming 84
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:
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 main() {
int result = add(3, 4); // 3 and 4 are actual parameters
}
84
A Quick Notes on C Programming 85
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
}
O
IL
N
85
A Quick Notes on C Programming 86
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;
86
A Quick Notes on C Programming 87
Answer:
You can access members of a structure using the dot (.) operator.
Example:
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
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
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:
Answer:
Yes, you can include arrays within a structure. This is commonly used for storing
IL
Example:
struct Student {
char name[50];
int grades[5];
};
88
A Quick Notes on C Programming 89
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
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:
89
A Quick Notes on C Programming 90
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
Answer:
No, structures in C cannot contain functions directly. However, they can contain pointers
IL
Example:
struct Operation {
int (*operation)(int, int); // Function pointer
};
90
A Quick Notes on C Programming 91
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
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
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:
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
Answer:
Yes, you can allocate memory for a structure dynamically using functions like malloc.
O
Example:
IL
p->age = 25;
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
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
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:
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
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
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
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];
};
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
}
IL
N
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:
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
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
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>.
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
char passport[10];
};
};
98
A Quick Notes on C Programming 99
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
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
100
A Quick Notes on C Programming 101
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
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
To declare a pointer, specify the data type followed by an asterisk (*), and then the pointer
TP
name.
Example:
O
int x = 100;
IL
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
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 *p = arr;
printf("%d", *(p + 2)); // Accesses the third element, 30
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:
Y
int main() {
AR
int x = 10;
updateValue(&x);
printf("%d", x); // Outputs 20
D
}
Example:
AL
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
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
Code:
#include <stdio.h>
TP
int main() {
int x = 5;
O
return 0;
}
104
A Quick Notes on C Programming 105
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
return 0;
TP
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
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
Code:
O
#include <stdio.h>
IL
int main() {
N
106
A Quick Notes on C Programming 107
return 0;
}
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
p[0] = 5;
p[1] = 10;
O
p[2] = 15;
IL
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
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
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
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
Code:
TP
#include <stdio.h>
O
}
N
int main() {
int x = 20, y = 10;
int *max = findMax(&x, &y);
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
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
3. realloc (Reallocation)
O
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:
Example:
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:
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
Example:
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
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);
113
A Quick Notes on C Programming 114
// 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]);
}
return 0;
}
AL
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.
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
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
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
The filePtr pointer can then be used to open, read, write, and close files.
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 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
Closing a file after operations is essential to save changes and free up system resources.
O
Syntax:
IL
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
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.
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
You can read from a file using: - fscanf: Reads formatted input from a file. - fgetc: Reads a
TP
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
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.
if (filePtr != NULL) {
char line[100];
TP
fclose(filePtr);
IL
feof is used to check if the End of File (EOF) has been reached.
Example:
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.
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;
Y
// Open source file in read mode
AR
sourceFile = fopen(sourcePath, "r");
if (sourceFile == NULL) {
printf("Cannot open source file.\n");
D
exit(1);
}
// 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:
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
Y
0 00 000 NUL Null
AR
1 01 001 SOH Start of Header
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
8 08 010 BS Backspace
TP
15 0F 017 SI Shift In
123
A Quick Notes on C Programming 124
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
124
A Quick Notes on C Programming 125
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
58 3A 072 : Colon
59 3B 073 ; Semicolon
TP
64 40 100 @ At symbol
125
A Quick Notes on C Programming 126
92 5C 134 \ Backslash
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
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
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:
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.
file.
127
A Quick Notes on C Programming 128
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.
number of characters
from source to
destination.
TP
specified number of
characters from one
N
string to another.
128
A Quick Notes on C Programming 129
Y
strstr Finds the first char *ptr = strstr(str, "sub");
occurrence of a
AR
substring in a string.
D
occurrence of a
character in a string.
129
A Quick Notes on C Programming 130
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
lowercase.
130
A Quick Notes on C Programming 131
Y
asctime Converts struct tm to a char *str = asctime(local_time);
AR
human-readable string.
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.
to a program. If the
condition fails, the
program terminates.
O
functions.
131
A Quick Notes on C Programming 132
Y
getche Reads a character from char c = getche();
the keyboard and
AR
echoes it to the screen.
D
screen.
AN
BH
AL
TP
O
IL
N
132