Content for Week 1 - Basics and Syntax
Variables are named locations in memory that are used to hold a value that may be modified by the program.
The syntax for declaring a variable is:
Data_type variableName;
int age = 21;
float salary = 4564.50;
int marks;
int acc_type;
char ch = 'y';
char name[20] = "apollo";
int 5marks;
int @host;
int acc no$;
#include <stdio.h> // Preprocessor directive
// main function - entry point of the program
int main() {
// Print output to the screen
printf("Hello, World!\\n");
return 0; // Exit the program
}
Hello, World!
#include <stdio.h>
#define ADD(a, b) ((a) + (b))
int main() { printf("%d\\n", ADD(5, 7)); return 0; }
12
Using macros like ADD can be useful for simple calculations, but be cautious when using complex macros, as they can lead to unexpected behavior.
Functions are blocks of code designed to perform specific tasks. They enhance modularity, code reuse, and readability.
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 7);
printf("Sum: %d\\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Sum: 12
Fun Fact: In C, functions must be declared before they are used, unless included in header files.
Content for Week 2 - Control Structures
Control structures allow you to change the flow of program execution based on conditions.
Conditional statements are used to make decisions in a program. Based on whether a condition is true or false, different blocks of code will be executed.
Used when you want to execute a block of code only if a condition is true.
if (condition) {
//code to execute if condition is true
}
Used when you want to choose between two blocks of code.
if (condition) {
//code to execute if condition is true
}
else {
//code if false
}
Used when you have multiple conditions to check in sequence.
if (condition) {
//code to execute if condition is true
}
else if (condition) {
//code
}
else if (condition n) {
//code
}
else {
//default code
}
Used to replace multiple else if blocks when comparing a single variable against many values.
switch (expression) {
case value1:
//code
break;
case value2:
//code
break;
default:
//code
break;
}
if (condition) {
//Code to execute if condition is true
}
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number > 0) {
printf("%d is a positive number.\n", number);
}
return 0;
}
Enter a number:
8
The number is positive.
typedef enum {
RED,
GREEN,
BLUE
} Color;
void printColor(Color c) {
switch(c){
case RED:
printf("Red\n");
break;
//..
}
}
Red
outer:
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
if (i == 3) break outer;
printf("%d %d\n",i,j);
}
}
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
2 4
for ( int i = 0; i < 5; i++) {
if (i == 3)
continue; //Skips 3
if (i == 4)
break; //Stop at 4
printf("%d\n",i);
}
0
1
2
int x=5;
int result = (x>10) ? 1 : 0; //result = 0
printf("%d\n",result);
0
Executes a block of code at least once, and then continues to repeat the block as long as a specified condition remains true.
do {
// Code to execute
} while (condition);
#include <stdio.h>
int main() {
int x = 5;
do {
printf("Value: %d\n",x); // Corrected printf format string
x--;
} while (x > 0);
return 0;
}
Value: 5
Value: 4
Value: 3
Value: 2
Value: 1
C doesn't have a direct for-each, but arrays can be traversed using a for loop.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40};
int size = sizeof(numbers) / sizeof(numbers[0]);
for(int i = 0; i < size; i++) {
printf("Value: %d\n", numbers[i]);
}
return 0;
}
Value: 10
Value: 20
Value: 30
Value: 40
#include <stdio.h>
int main() {
int a = 5, b = 10;
if (a < b)
if (a != 5)
printf("A is not five\n");
else
printf("A is five\n");
else
printf("A is not greater than B\n");
return 0;
}
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number > 0) {
printf("%d is a positive number.\n", number);
}
return 0;
}
Content for Week 3 - Functions and Arrays Control Structure
A function is a block of code that performs a specific task. It improves modularity and reusability.
return_type function_name(parameters) {
// code
}
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int sum = add(5, 10); // Function call
printf("Sum is: %d", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Sum is: 15
An array in C is a collection of elements, all of the same type, stored in contiguous memory locations.
data_type array_name[size];
// Example: int myArray[10];
Type: The data type of the array elements (e.g., int, float).
Size: The number of elements the array can store.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5}; // Declaration and initialization
printf("Element at index 2: %d\n", arr[2]);
return 0;
}
Element at index 2: 3
Control structures like loops are used to traverse and manipulate arrays in C.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
// Loop through array and print each element
for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, arr[i]);
}
return 0;
}
This code prints all the elements of the array arr.
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5
A pointer is a variable that stores the address of another variable. Pointers are powerful tools that enable efficient memory access, dynamic memory management, and are essential in data structures like linked lists and trees.
#include <stdio.h>
int main() {
int a = 10; // Declare an integer variable
int *ptr; // Declare a pointer to int
ptr = &a; // Store address of variable 'a' in pointer 'ptr'
// Print the value and address
printf("Value of a: %d\n", a);
printf("Address of a: %p\n", &a);
printf("Value stored in ptr (address of a): %p\n", ptr);
printf("Value pointed to by ptr (value of a): %d\n", *ptr);
return 0;
}
Value of a: 10
Address of a: 0x7ffee0b01234 (This will be a hexadecimal address)
Value stored in ptr (address of a): 0x7ffee0b01234 (This will be the same as Address of a)
Value pointed to by ptr (value of a): 10
One lesser-known aspect is how arrays are passed to functions in C. When an array is passed to a function, it decays into a pointer to the first element. This means the function receives a pointer, not the entire array.
#include <stdio.h>
// Function to print array elements
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
printArray(numbers, 5);
return 0;
}
In this example, arr in the printArray function is essentially a pointer to the first element of the numbers array. The size parameter is necessary because the function doesn't know the size of the array otherwise.
1 2 3 4 5
A function pointer stores the address of a function and allows dynamic invocation.
// Function pointer declaration
void (*funcPtr)();
// Assign function address to pointer
funcPtr = &greet;
// Call function using pointer
funcPtr();
#include <stdio.h>
// Function to display a message
void greet() {
printf("Hello, Function Pointers!\n");
}
int main() {
void (*funcPtr)(); // Declare function pointer
funcPtr = &greet; // Assign function address
funcPtr(); // Call function using pointer
return 0;
}
Hello, Function Pointers!
Unlike fixed-size arrays, VLAs allow defining arrays with dynamic sizes at runtime (supported in modern C versions).
int n;
scanf("%d", &n); // Get array size from user
int arr[n]; // Declare a variable-length array
int main() {
int n;
printf("Enter array size: ");
scanf("%d", &n);
int arr[n]; // Variable-length array
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
printf("Array contents:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Enter array size: 5
Array contents:
1 2 3 4 5
---
Enter array size: 3
Array contents:
1 2 3
---
Enter array size: 10
Array contents:
1 2 3 4 5 6 7 8 9 10
A function in C is a block of code that performs a specific task. It promotes modularity and code reuse, making programs easier to debug, read, and maintain by breaking complex problems into smaller parts.
#include <stdio.h>
int main() {
int a = 10;
int *ptr;
ptr = &a;
printf("Value of a: %d\n", a);
printf("Address of a: %p\n", &a);
printf("Value stored in ptr (address of a): %p\n", ptr);
printf("Value pointed to by ptr (value of a): %d\n", *ptr);
return 0;
}
#include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
printArray(numbers, 5);
return 0;
}
Content for Week 4 - Pointers and Strings
A pointer is a variable that stores the memory address of another variable.
data_type *pointer_name;
int *ptr; // pointer to an int
float *fptr; // pointer to a float
char *cptr; // pointer to a char
double *dptr; // pointer to a double
Note: Even though * is used in the declaration, the pointer itself just stores an address.
int a = 10;
int *ptr = &a; // ptr now holds the address of a
A string is a sequence of characters terminated by a null character '\0'. In C, strings are represented as arrays of characters. Think of a string as a sentence or word stored in memory.
#include <stdio.h>
int main() {
char name[] = "Welcome";
printf("Hello, %s!\n", name);
return 0;
}
Hello, Welcome!
"Welcome" is a string stored in a character array.
A pointer to a string is a pointer that stores the address of the first character of the string. It’s a more memory-efficient and flexible way to handle strings than using character arrays.
#include <stdio.h>
int main() {
char *greet = "Welcome!";
printf("%s\n", greet);
return 0;
}
Welcome!
Explanation:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str); // Note: gets() is unsafe, use fgets() in real programs
int length = strlen(str); // Using string function
printf("Length of the string is: %d\n", length);
return 0;
}
Hello, Welcome!Enter a string: Hello
Length of the string is: 5
---
Enter a string: C Programming
Length of the string is: 13
---
Enter a string:
Length of the string is: 0
Explanation: strlen() is a string function that returns the length of the string.
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
char *ptr = str;
printf("String using pointer:\n");
while (*ptr != '\0') {
printf("%c", *ptr);
ptr++;
}
return 0;
}
String using pointer:
Hello, World!
Explanation:
You can use pointer arithmetic to traverse strings.
char str[] = "Hello";
char *ptr = str;
while (*ptr != '\0') {
printf("%c", *ptr);
ptr++;
}
Hello
This concept is powerful, but it requires careful handling to avoid buffer overflows and other issues.
In C, string literals and character arrays are not exactly the same.
char *str1 = "Hello"; // string literal (read-only)
char str2[] = "Hello"; // character array (modifiable)
// str1[0] = 'h'; // would cause a segmentation fault
str2[0] = 'h'; // okay
str1: Hello
str2: hello
This distinction is important to understand when working with strings in C.
This program shows how to write a simple function to search for a character in a string using pointers.
#include <stdio.h>
int findChar(char *text, char target) {
int index = 0;
while (*text != '\0') {
if (*text == target) {
return index; // Found it!
}
text++;
index++;
}
return -1; // Not found
}
int main() {
char myWord[] = "apple";
char charToFind = 'p';
int position = findChar(myWord, charToFind);
if (position != -1) {
printf("'%c' is at index %d\n", charToFind, position);
} else {
printf("'%c' not found\n", charToFind);
}
return 0;
}
'p' is at index 1
This program demonstrates using the built-in strchr() function for the same task, showing its simplicity.
#include <stdio.h>
#include <string.h>
int main() {
char mySentence[] = "orange";
char searchFor = 'a';
// strchr returns a pointer to the char if found, or NULL
char *found = strchr(mySentence, searchFor);
if (found != NULL) {
// Calculate index by subtracting pointers
int index = found - mySentence;
printf("'%c' is at index %d\n", searchFor, index);
} else {
printf("'%c' not found\n", searchFor);
}
return 0;
}
'a' is at index 3
int a = 10;
int *p = &a;
printf("%d", *p);
#include <stdio.h>
int main() {
char str1[] = "Hello";
char *str2 = "Hello";
str1[0] = 'H';
str2[0] = 'H';
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
return 0;
}
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
char *ptr = str;
printf("String using pointer:\n");
while (*ptr != '\0') {
printf("%c", *ptr);
ptr++;
}
return 0;
}
Content for Week 5 - Structures and File Handling
A structure in C is a user-defined data type that allows you to combine variables of different types under one name.
struct Student {
int id;
char name[50];
float marks;
};
struct Student s1;
s1.id = 101;
strcpy(s1.name, "John");
s1.marks = 89.5;
printf("%d %s %.2f", s1.id, s1.name, s1.marks);
101 John 89.50
File handling in C allows you to create, open, read, write, and close files — making your programs more powerful by storing and retrieving data from files instead of just using memory!
#include <stdio.h>
This must be included to use file functions like fopen(), fclose(), fprintf(), fscanf(), etc.
Operation | Function |
---|---|
Create/Open | fopen() |
Close | fclose() |
Read | fscanf(), fgets() |
Write | fprintf(), fputs() |
Move cursor | fseek(), ftell() |
Mode | Description |
---|---|
"r" | Read |
"w" | Write (overwrite) |
"a" | Append (add at end) |
"r+" | Read & Write |
"w+" | Write & Read (overwrite) |
"a+" | Append & Read |
#include <stdio.h>
int main() {
FILE *fptr;
char data[100];
// Writing to the file
fptr = fopen("myfile.txt", "w"); // open in write mode
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("Enter some text to write into the file: ");
fgets(data, sizeof(data), stdin);
fprintf(fptr, "%s", data);
fclose(fptr);
printf("Data written to file successfully.\n");
// Reading from the file
fptr = fopen("myfile.txt", "r"); // open in read mode
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("Reading from the file:\n");
while (fgets(data, sizeof(data), fptr) != NULL) {
printf("%s", data);
}
fclose(fptr);
return 0;
}
Enter some text to write into the file: Hello, C programming!
Data written to file successfully.
Reading from the file:
Hello, C programming!
Hello, C programming!
Imagine you have a collection of data that you want to store together, like a person's details. You can create a struct to hold this data:
struct Person {
int age;
char name[20];
};
For example:
struct Example {
char a; // 1 byte
int b; // 4 bytes
}; // The total size might be 8 bytes due to padding
struct PackedData {
unsigned int flag: 1;
unsigned int mode: 2;
};
struct Address {
char street[20];
char city[10];
};
struct Person {
int age;
char name[20];
struct Address address;
};
File handling allows you to read and write data to files. Here are some key functions:
FILE *file = fopen("example.txt", "w");
if (file != NULL) {
fprintf(file, "Hello, world!");
fclose(file);
}
Hello, world!
This program helps you save a student's info—like their name, ID, and marks—into a file. Then it opens the file and shows you what was saved, kind of like writing something down and reading it later.
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
// Function to get user input and write to file
void writeStudentToFile() {
struct Student s;
printf("Enter Student ID: ");
scanf("%d", &s.id);
printf("Enter Student Name: ");
scanf(" %[^\n]", s.name); // reads string with spaces
printf("Enter Marks: ");
scanf("%f", &s.marks);
FILE *fp = fopen("student.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return;
}
fprintf(fp, "%d\n%s\n%.2f\n", s.id, s.name, s.marks);
fclose(fp);
printf("Student data saved successfully.\n\n");
}
// Function to read from file and display
void readStudentFromFile() {
struct Student s;
FILE *fp = fopen("student.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return;
}
fscanf(fp, "%d\n", &s.id);
fgets(s.name, sizeof(s.name), fp);
fscanf(fp, "%f", &s.marks);
// Remove trailing newline from name (if any)
if (s.name[strlen(s.name) - 1] == '\n') {
s.name[strlen(s.name) - 1] = '\0';
}
fclose(fp);
printf("Student Data from File:\n");
printf("ID: %d\n", s.id);
printf("Name: %s\n", s.name);
printf("Marks: %.2f\n", s.marks);
}
int main() {
writeStudentToFile();
readStudentFromFile();
return 0;
}
Enter Student ID: 105
Enter Student Name: Dave
Enter Marks: 92.5
Student data saved successfully.
Student Data from File:
ID: 105
Name: Dave
Marks: 92.50