0% found this document useful (0 votes)
16 views30 pages

Introduction to C Programming Basics

This document serves as an introduction to programming using the C language, covering fundamental concepts such as programming languages, program structure, syntax, and the reasons for using C. It also outlines the setup and installation procedures for various platforms, data types, variables, constants, storage classes, operators, type casting, and control structures. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

T God
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)
16 views30 pages

Introduction to C Programming Basics

This document serves as an introduction to programming using the C language, covering fundamental concepts such as programming languages, program structure, syntax, and the reasons for using C. It also outlines the setup and installation procedures for various platforms, data types, variables, constants, storage classes, operators, type casting, and control structures. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

T God
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

INTRODUCTION TO

PROGRAMMING
USING C LANGUAGE
COM 121

BY: KHADIJAH KABIR


KADUNA POLYTECHNIC
Module 1: Basics of Programming and Introduction to C Language

1.1 PROGRAMMING LANGUAGE


A programming language is a formal language comprising a set of instructions that
produce various kinds of output. It is used to implement algorithms and control the
behavior of a machine, especially a computer. Programming languages are used to
create programs that perform specific tasks such as data processing, calculations, and
decision making.
There are different categories of programming languages:
 Low-level languages (e.g., Assembly Language & Machine Language)
 High-level languages (e.g., C, Python, Java)
High-level languages are more human-readable and easier to learn than low-level
languages.

1.2 PROGRAM
A program is a sequence of instructions written in a programming language to perform
a specific task or solve a particular problem. A program tells a computer exactly what to
do, step by step. When the instructions are executed, they result in the desired outcome.

1.3 PROGRAM STRUCTURE


The structure of a program refers to how the code is organized and how the different
components interact. In C programming, a simple program structure includes:
#include <stdio.h>

// Function declaration
int main() {
// Code body
printf("Hello, World!\n");
return 0;
}

Key components:
 Preprocessor directives: #include <stdio.h> includes standard input-output
library.
 Main function: int main() is the entry point of any C program.
 Statements: Executable instructions within {}.
 Return statement: return 0; ends the program.

1
1.4 PROGRAM SYNTAX
Syntax refers to the rules that define the correct structure of a program written in a
particular programming language. Every programming language has its own syntax.
Syntax rules dictate how keywords, operators, punctuation, and identifiers must be used.
In C language:
 Each statement ends with a semicolon (;)
 Blocks of code are enclosed in curly braces ({})
 Comments are added using // for single-line and /* */ for multi-line
Example:
int a = 10; // Declaration and initialization

1.5 REASONS FOR USING C LANGUAGE


The C programming language is widely used because of the following reasons:
1. Simplicity: C is easy to understand and provides a good foundation for learning
other programming languages.
2. Portability: C programs can be executed on different machines with little or no
modification.
3. Efficiency: C is fast and uses system resources efficiently.
4. Flexibility: C can be used for a wide range of applications, from system software
to game development.
5. Extensibility: C supports function libraries, making code reuse and organization
easier.
6. Foundation for other languages: C has influenced many other programming
languages like C++, Java, and Python.

1.6 LOCAL ENVIRONMENT SETUP AND INSTALLATION PROCEDURE ON VARIOUS


PLATFORMS
To write and run C programs, a local development environment needs to be set up. This
involves installing a text editor, compiler, and optionally an IDE.
Windows:
1. Download and install Code::Blocks or Dev-C++ (includes compiler)
2. Alternatively, install MinGW and configure with a text editor like Notepad++
3. Verify installation by opening Command Prompt and typing gcc --version
macOS:
1. Install Xcode Command Line Tools using the terminal:
xcode-select --install

2
2. Install Homebrew package manager (if needed) and use it to install GCC:
brew install gcc

3. Use Visual Studio Code, Sublime Text, or Xcode to write and compile code
Linux (Ubuntu/Debian):
1. Open Terminal
2. Install GCC:
sudo apt update
sudo apt install build-essential

3. Use Gedit, VS Code, or Geany as the code editor


After installation:
 Create a C file with .c extension
 Compile using: gcc filename.c -o outputname
 Run using: ./outputname

Exercise 1: Write and run your first C program


1. Open your preferred code editor.
2. Type the following code:
#include <stdio.h>
int main() {
printf("My first C program!\n");
return 0;
}

3. Save the file as first_program.c


4. Compile and run the program using your platform-specific commands (as
described above).
Exercise 2: Modify the Program - Change the message printed to your name. - Add a
second printf statement that prints your favorite quote.

3
Module 2: Variables, Data Types, and Constants in C

2.1 DATA TYPES


In C, data types specify the type of data that a variable can hold. They are broadly
classified into the following:
1. Integer Types: Used to store whole numbers. - int: typically 4 bytes - short: usually 2
bytes - long: at least 4 bytes - unsigned: no negative values
2. Floating Point Types: Used for decimal numbers. - float: 4 bytes, single precision -
double: 8 bytes, double precision - long double: higher precision
3. Character Type: - char: stores a single character (1 byte)
4. Void Type: - void: represents no value or no return type in functions

2.2 VARIABLES, CONSTANTS, AND LITERALS


 Variables: Named memory locations that store data which can be changed
during program execution.
int age = 25;

 Constants: Named values that cannot change during execution.


const float PI = 3.14;

 Literals: Fixed values written directly in code.


100, 'A', 3.14

2.3 VARIABLE AND CONSTANT DECLARATION


 Variable Declaration:
int number;
float salary;

 Constant Declaration:
const int DAYS_IN_WEEK = 7;

This prevents accidental changes to values that must remain fixed.

2.4 SYMBOLIC CONSTANT USING #define AND const KEYWORD


 Using #define Preprocessor Directive:

4
#define PI 3.14159

Replaces all occurrences of PI with 3.14159 during preprocessing.

 Using const Keyword:


const int MAX = 100;

Provides type safety and is scoped within the block.

2.5 PROCEDURE FOR CODING AND RUNNING A C PROGRAM


1. Write the Program: Use a text editor or IDE.
2. Save the File: With a .c extension (e.g., example.c)
3. Compile the Program: Use gcc (GNU Compiler Collection)
gcc example.c -o example

4. Run the Program:


./example

Exercise 1: Declare and Use Variables Write a program that declares an integer and a
float, assigns values to them, and prints the result.
#include <stdio.h>
int main() {
int age = 20;
float height = 5.9;
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
return 0;
}

Exercise 2: Use Constants and Literals Write a program using both #define and const to declar
e constants and print their values.

#include <stdio.h>
#define MAX_SCORE 100
int main() {
const float PI = 3.14159;
printf("Max Score: %d\n", MAX_SCORE);
printf("Value of PI: %.5f\n", PI);
return 0;
}

Module 3: Storage Classes, Operators, and Type Casting

5
3.1 STORAGE CLASSES
Storage classes in C determine the scope, visibility, and lifetime of variables and/or
functions. There are four storage classes:
1. auto – Default storage class for local variables
auto int x = 5;

2. register – Suggests storing the variable in a CPU register for faster access
register int speed;

3. static – Keeps the variable value between function calls


static int count = 0;

4. extern – Used to declare a global variable or function defined in another file


extern int globalVar;

3.2 OPERATORS AND OPERATOR PRECEDENCE


Operators are symbols used to perform operations on variables and values. They are
classified as:
1. Arithmetic Operators: +, -, *, /, %
2. Relational Operators: ==, !=, >, <, >=, <=
3. Logical Operators: &&, ||, !
4. Assignment Operators: =, +=, -=, *=, /=, %=
5. Increment/Decrement: ++, --
6. Bitwise Operators: &, |, ^, ~, <<, >>

Operator Precedence determines the order in which operations are performed. For
example:
int result = 10 + 5 * 2; // result = 20, because * has higher precedence than +

Precedence Order (High to Low):

6
1. ()
2. ++, --
3. *, /, %
4. +, -
5. Relational <, >, <=, >=
6. Equality ==, !=
7. Logical &&, ||
8. Assignment =, +=, -= etc.
3.3 TYPE CASTING OPERATION
Type casting is the process of converting one data type into another. In C, this is often
done manually using explicit casting:
int a = 5;
float b = (float)a; // converts int to float

Integer Promotion
Smaller integer types (e.g., char, short) are automatically promoted to int during
arithmetic operations.
char x = 5, y = 10;
int z = x + y; // promoted to int

Arithmetic Conversion
When performing operations on mixed types, C converts them to a common type:
int a = 10;
float b = 4.5;
float result = a + b; // a is converted to float

Exercise 1: Storage Class Demonstration


#include <stdio.h>
void demo() {
static int count = 0;
count++;
printf("Count = %d\n", count);
}
int main() {
demo();
demo();
demo();
return 0;
}

Try running this program and observe how the static variable retains its value across function c
alls.

Exercise 2: Operator Precedence

7
#include <stdio.h>
int main() {
int a = 10, b = 5, c = 2;
int result = a - b * c; // What will be the result?
printf("Result = %d\n", result);
return 0;
}

Try modifying the expression with parentheses to see how it affects the output.
Exercise 3: Type Casting
#include <stdio.h>
int main() {
int x = 10;
float y = 3.5;
float z = x + y;
printf("Result = %.2f\n", z);
return 0;
}

Modify the program to explicitly cast x to float and observe the difference.

8
Module 4: Standard Input and Output in C

4.1 STANDARD INPUTS AND OPERATIONS


Standard input refers to data entered by the user via the keyboard. In C, standard input
is typically handled through functions from the stdio.h library. Input operations allow a
program to receive data during execution.
For example:
int age;
scanf("%d", &age); // takes input and stores it in age

4.2 OUTPUT AND OPERATIONS


Output operations send data from the program to an output device (like a screen). In C,
the most common output function is printf().
Example:
int age = 25;
printf("Age is %d\n", age); // displays output on screen

Output can include text, values, characters, and formatted data.

4.3 INPUT FUNCTIONS: get(), getchar(), putchar(), scanf() this are functions used to
collect data from the user
 ``: Reads a single character from the standard input.
char c;
c = getchar();
 ``: Reads formatted input from the user.
int age;
scanf("%d", &age);

 `: Not a standard C function (often confused with C++). In standard C,


usefgets()orgets()(note:gets()` is unsafe and deprecated).

 ``: Outputs a single character to the screen.


char c = 'A';
putchar(c);

4.4 OUTPUT FUNCTIONS: printf()


`` is the primary function used to print output to the screen. It supports format

9
specifiers to display variables of different types:

Format Specifier Description


%d Integer
%f Floating-point
%c Character
%s String
Example:
int age = 25;
float height = 5.9;
char grade = 'A';
printf("Age: %d, Height: %.1f, Grade: %c\n", age, height, grade);

Exercise 1: Input and Output of Integer


#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("You entered: %d\n", number);
return 0;
}

Exercise 2: Character I/O using ** and **


#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
printf("\n");
return 0;
}

Exercise 3: Mixed Data Input and Output


#include <stdio.h>
int main() {
int age;
float gpa;
char grade;
printf("Enter age, GPA and grade: ");
scanf("%d %f %c", &age, &gpa, &grade);
printf("Age: %d, GPA: %.2f, Grade: %c\n", age, gpa, grade);
return 0;

10
}

Module 5: Control Structures in C

11
5.1 CONTROL STRUCTURE
Control structures determine the flow of execution of statements in a program. They
allow conditional execution, repetition, and branching in the program. There are three
major types: - Sequential - Conditional (Decision-making) - Looping (Iteration)

5.2 TYPES OF CONTROL STRUCTURES: SEQUENTIAL, LOOPING ETC.


 Sequential: Default mode where statements are executed one after the other.
 Selection (Conditional): Decision-making using if, if...else, nested if, switch.
 Iteration (Looping): Repeating blocks of code using while, for, do...while.
 Branching: Alters the flow using goto, break, continue, etc.

5.3 VARIOUS TYPES OF IF STATEMENTS


 Simple if:
if (a > b) {
printf("A is greater\n");
}

 if...else:
if (a > b) {
printf("A is greater\n");
} else {
printf("B is greater\n");
}

 Nested if:
if (a > b) {
if (a > c) {
printf("A is the largest\n");
}
}

5.4 WHILE, FOR, DO...WHILE LOOPS


 while loop: Entry-controlled loop
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}

 for loop: Most commonly used loop


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

12
}

 do...while loop: Exit-controlled loop


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

5.5 EXPLAIN switch and NESTED switch STATEMENTS


 switch Statement:
int choice = 2;
switch (choice) {
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
default:
printf("Other\n");
}

 Nested switch:
int x = 1, y = 2;
switch (x) {
case 1:
switch (y) {
case 2:
printf("Nested switch example\n");
break;
}
break;
}

5.6 goto STATEMENT AND INFINITE LOOP STATEMENT


 goto Statement: Transfers control to a labeled statement
int x = 1;
goto jump;

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

jump:
printf("Jumped here\n");

 Infinite Loop:
while (1) {
// This loop runs forever unless broken
13
printf("Running...\n");
}

Exercise 1: IF-ELSE Example


#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18)
printf("Adult\n");
else
printf("Minor\n");
return 0;
}

Exercise 2: Looping
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}

Exercise 3: Switch Statement


#include <stdio.h>
int main() {
int option;
printf("Enter option (1-3): ");
scanf("%d", &option);
switch (option) {
case 1:
printf("Option 1 selected\n");
break;
case 2:
printf("Option 2 selected\n");
break;
case 3:
printf("Option 3 selected\n");
break;
default:
printf("Invalid option\n");
}
return 0;
}

Module 6: Functions in C

14
6.1 DEFINE FUNCTION
A function is a block of code designed to perform a specific task. Functions improve
code modularity, reusability, and readability. In C, a program must have a main()
function where execution starts.
Example:
void greet() {
printf("Hello!\n");
}

6.2 DIFFERENTIATE BETWEEN USER-DEFINED AND LIBRARY FUNCTIONS


 User-defined Functions: These are functions created by the programmer.
int add(int a, int b) {
return a + b;
}

 Library Functions: Predefined functions in the C standard library (e.g., printf(),


scanf(), sqrt()).
#include <math.h>
double result = sqrt(25.0);

6.3 SCOPE RULES: LOCAL AND GLOBAL VARIABLES


 Local Variables: Declared inside a function or block and accessible only within it.
void test() {
int x = 5; // local to test()
}

 Global Variables: Declared outside all functions and accessible by any function in
the file.
int x = 10;
void test() {
printf("%d", x); // accessible globally
}

6.4 FUNCTION ARGUMENTS


Function arguments are the values passed to a function for processing.
int multiply(int a, int b) {

15
return a * b;
}

Arguments allow passing different data into the function for computation.

6.5 FUNCTION CALLS AND TYPES: CALL BY VALUE, CALL BY REFERENCE


 Call by Value: Passes a copy of the variable. Original value remains unchanged.
void modify(int x) {
x = 10;
}

 Call by Reference: Passes the address of the variable. Allows modification of the
original value. (In C, done using pointers.)
void modify(int *x) {
*x = 10;
}

Exercise 1: Simple Function Call


#include <stdio.h>
void welcome() {
printf("Welcome to C Programming!\n");
}
int main() {
welcome();
return 0;
}

Exercise 2: Function with Parameters


#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 10);
printf("Sum = %d\n", result);
return 0;
}

Exercise 3: Call by Reference


#include <stdio.h>
void update(int *n) {
*n = 20;

16
}
int main() {
int num = 5;
update(&num);
printf("Updated value = %d\n", num);
return 0;
}

Module 7: Arrays and Strings in C

17
7.1 DEFINE ARRAYS
An array is a collection of variables of the same data type, stored at contiguous memory
locations. Each element is accessed using an index.
Example:
int numbers[5];

7.2 TYPES OF ARRAYS: ONE-DIMENSIONAL, TWO-DIMENSIONAL ETC.


 One-dimensional Array:
int arr[5] = {1, 2, 3, 4, 5};

 Two-dimensional Array (Matrix):


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

Arrays of higher dimensions are also possible but less commonly used in introductory
programming.

7.3 ARRAY ELEMENTS AND INITIALIZATION


 Individual Elements: Accessed using the index (starts from 0)
arr[0] = 10;

 Initialization During Declaration:


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

 Default Initialization: If not fully initialized, remaining elements are set to zero.
int arr[5] = {1, 2}; // rest are 0

7.4 ARRAY ACCESS AND OPERATIONS


 Accessing Elements:
printf("%d", arr[2]);

 Traversing Array with Loops:


for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

 Performing Operations: Summation, Searching, Sorting etc.


int sum = 0;
for (int i = 0; i < 5; i++) sum += arr[i];

18
7.5 DEFINE STRINGS
A string is an array of characters terminated by a null character (\0).
Example:
char name[] = "John";

Equivalent to:
char name[] = {'J', 'o', 'h', 'n', '\0'};

7.6 STRING OPERATIONS: CONCATENATION ETC.


To work with strings in C, include <string.h>.
 String Concatenation:
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2); // str1 becomes "Hello World"

 String Copy:
strcpy(dest, src);

 String Length:
strlen(str);

 String Comparison:
strcmp(str1, str2);

Exercise 1: Array Initialization and Access


#include <stdio.h>
int main() {
int scores[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("Score %d: %d\n", i+1, scores[i]);
}
return 0;
}

Exercise 2: String Concatenation


#include <stdio.h>
#include <string.h>
int main() {

19
char a[20] = "Hello ";
char b[] = "C!";
strcat(a, b);
printf("%s\n", a);
return 0;
}

Module 8: Pointers in C

20
8.1 DEFINE POINTER
A pointer is a variable that stores the memory address of another variable. It allows
indirect access and manipulation of variables.
Example:
int a = 10;
int *p = &a; // p stores the address of a

8.2 USES OF POINTERS


 Dynamic memory allocation
 Efficient array handling
 Passing large structures to functions
 Handling strings and arrays
 Implementing data structures like linked lists

8.3 POINTER ARITHMETIC


Pointer arithmetic allows operations such as incrementing or decrementing pointers to
traverse arrays.
int arr[] = {10, 20, 30};
int *ptr = arr;
ptr++; // points to arr[1]

Valid operations: ptr++, ptr--, ptr + n, ptr - n

8.4 POINTER OPERATIONS: INCREMENTING, DECREMENTING, POINTER COMPARISON


 Incrementing:
ptr++;

 Decrementing:
ptr--;

 Comparison:
if (ptr1 == ptr2) {...}

These operations allow iteration over data structures like arrays.


8.5 ARRAY OF POINTERS
An array of pointers is a collection of pointer variables.
char *names[] = {"Alice", "Bob", "Charlie"};

21
Useful for managing arrays of strings or dynamic data.

8.6 PASSING AND RETURNING ARRAYS FROM FUNCTIONS


Passing Arrays to Functions:
void display(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}

Returning Arrays from Functions:


int* createArray() {
static int arr[3] = {1, 2, 3};
return arr;
}

Note: Never return local arrays (non-static) as they go out of scope.

Exercise 1: Basic Pointer Usage


#include <stdio.h>
int main() {
int num = 10;
int *ptr = &num;
printf("Value: %d, Address: %p\n", *ptr, ptr);
return 0;
}

Exercise 2: Pointer Arithmetic


#include <stdio.h>
int main() {
int arr[] = {1, 2, 3};
int *p = arr;
for (int i = 0; i < 3; i++) {
printf("%d ", *(p + i));
}
return 0;
}

Exercise 3: Array of Pointers


#include <stdio.h>
int main() {
char *colors[] = {"Red", "Green", "Blue"};

22
for (int i = 0; i < 3; i++) {
printf("%s\n", colors[i]);
}
return 0;
}

Module 9: Structures and Unions in C

23
9.1 STRUCTURES AND UNIONS TYPES
Structures and unions are user-defined data types in C that allow grouping of variables.
 Structure (struct): Groups related variables of different data types.
 Union (union): Similar to structures, but shares memory among all members.

9.2 STRUCTURES DEFINITION


A structure groups multiple variables into a single type. Each variable inside a structure
is called a member.
struct Student {
int id;
char name[50];
float gpa;
};

Accessing Members:
struct Student s1;
[Link] = 1;
strcpy([Link], "John");
[Link] = 3.5;

9.3 typedef AND #define


 typedef creates an alias for existing data types:
typedef unsigned int uint;
uint age = 25;

 #define creates macros or constants:


#define PI 3.1416

9.4 UNION DEFINITION AND MEMBERS ACCESS


A union shares the same memory space for all its members. Only one member can be
used at a time.
union Data {
int i;
float f;
char str[20];
};

Accessing Members:
union Data d;
d.i = 10;

24
printf("%d\n", d.i);

Note: Writing to one member affects the others due to shared memory.

Exercise 1: Structure Usage


#include <stdio.h>
#include <string.h>
struct Book {
int id;
char title[100];
};

int main() {
struct Book b1;
[Link] = 101;
strcpy([Link], "C Programming");
printf("Book ID: %d\nTitle: %s\n", [Link], [Link]);
return 0;
}

Exercise 2: Using Typedef and Union


#include <stdio.h>
#include <string.h>
typedef struct {
int id;
char name[50];
} Student;

union Info {
int age;
float score;
};

int main() {
Student s = {1, "Alice"};
union Info info;
[Link] = 20;
printf("Name: %s\nAge: %d\n", [Link], [Link]);
return 0;
}

Module 10: File Handling in C

25
10.1 FILE I/O OPERATIONS
File I/O (Input/Output) in C is performed using functions in the stdio.h library. These
operations include: - Reading from a file - Writing to a file - Appending data - Modifying
existing content
Common File I/O functions: - fopen(), fclose() - fprintf(), fscanf() - fgetc(), fputc() -
fread(), fwrite()

10.2 OPENING AND CLOSING FILES


Opening a File:
FILE *fp;
fp = fopen("[Link]", "r"); // Open file for reading

Modes: - “r” – read - “w” – write - “a” – append - “rb” – read binary - “wb” – write binary
Closing a File:
fclose(fp);

Always close a file after use to free system resources.

10.3 WRITING TO/READING FROM FILE


Writing to a File:
FILE *fp = fopen("[Link]", "w");
fprintf(fp, "Hello, file!\n");
fclose(fp);

Reading from a File:


char str[100];
FILE *fp = fopen("[Link]", "r");
fgets(str, 100, fp);
printf("%s", str);
fclose(fp);

10.4 BINARY INPUT AND OUTPUT FUNCTIONS


Binary files store data in binary format for efficient storage.
26
Writing to Binary File:
FILE *fp = fopen("[Link]", "wb");
int n = 100;
fwrite(&n, sizeof(n), 1, fp);
fclose(fp);

Reading from Binary File:


FILE *fp = fopen("[Link]", "rb");
int x;
fread(&x, sizeof(x), 1, fp);
printf("%d", x);
fclose(fp);

Exercise 1: Write and Read Text File


#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]", "w");
fprintf(fp, "C Programming");
fclose(fp);

char buffer[50];
fp = fopen("[Link]", "r");
fgets(buffer, 50, fp);
printf("%s\n", buffer);
fclose(fp);
return 0;
}

Exercise 2: Binary File Operations


#include <stdio.h>
int main() {
FILE *fp;
int n = 25, m;

fp = fopen("[Link]", "wb");
fwrite(&n, sizeof(n), 1, fp);
fclose(fp);

fp = fopen("[Link]", "rb");
fread(&m, sizeof(m), 1, fp);
fclose(fp);

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


return 0;
}

Module 11: Preprocessors and Header Files in C

27
11.1 PREPROCESSORS AND HEADER FILES
Preprocessor directives are lines included in the code preceded by a # symbol. These
lines are processed before compilation.
Header files contain function declarations and macro definitions. Common header files
include: - #include <stdio.h> - #include <stdlib.h> - #include <string.h>
Custom headers can also be created using:
#include "myheader.h"

11.2 PREPROCESSOR OPERATORS


 Macro continuation (\): Allows macros to span multiple lines.
#define MESSAGE \
"This is a message."

 Stringize (#): Converts a macro parameter to a string.


#define TO_STRING(x) #x
printf(TO_STRING(Hello)); // Output: "Hello"

 Token-pasting (##): Joins two tokens together.


#define MERGE(a, b) a##b
int MERGE(num, 1) = 10; // becomes int num1 = 10;

 Defined (defined): Checks if a macro is defined.


#ifdef DEBUG
printf("Debug mode");
#endif

11.3 PARAMETERIZED MACROS


Parameterized macros work like inline functions. They take arguments and replace
them with macro code.
#define SQUARE(x) ((x) * (x))
int result = SQUARE(5); // Result = 25

Use parentheses to avoid ambiguity in complex expressions.

11.4 HEADER FILE PROCESSING


When a program includes a header file: - The preprocessor copies the contents into the
source file. - This allows the compiler to know function prototypes and constants used
in the file.

28
Example of creating and using a header file:
myutils.h
void greet();

main.c
#include "myutils.h"
#include <stdio.h>

void greet() {
printf("Hello from header!\n");
}

int main() {
greet();
return 0;
}

Exercise 1: Using Macros and Header Files


mathutils.h
#define MAX(a, b) ((a) > (b) ? (a) : (b))

main.c
#include <stdio.h>
#include "mathutils.h"

int main() {
int x = 10, y = 20;
printf("Max is %d\n", MAX(x, y));
return 0;
}

29

You might also like