KEMBAR78
C All Notes | PDF | Pointer (Computer Programming) | C (Programming Language)
0% found this document useful (0 votes)
8 views44 pages

C All Notes

c programming notes

Uploaded by

kiranyerolkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views44 pages

C All Notes

c programming notes

Uploaded by

kiranyerolkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

C

🟢 HISTORY OF C LANGUAGE

C was developed in the early 1970s by Dennis Ritchie at Bell Labs.

 Originally created to develop the UNIX operating system.

 Evolved from earlier languages: B, BCPL, and ALGOL.

 C became the foundation for many modern languages: C++, Java, C#, Objective-C, and
more.

 Standardized by ANSI in 1989 as ANSI C (also called C89), later ISO C (C90, C99, C11,
C17).

Fun Facts:

 The UNIX OS, Git, Linux Kernel, and Python Interpreter are written in C.

 It is still one of the most used languages in embedded systems and operating systems.

🟢 BASICS OF C

The C programming language is a general-purpose, powerful procedural language


developed for system-level programming. Below are the core fundamentals of C:

1. Structure of a C Program

structure:

#include <stdio.h> // Preprocessor directive

int main() { // Main function - entry point

// Your code here

return 0; // Return value to OS

2. main() Function and Header Files

 main() is where execution starts.

 Standard header files include:

1
o <stdio.h>: standard input/output

o <stdlib.h>: memory allocation, process control

o <string.h>: string functions

3. Compilation & Execution Process


C code goes through several steps before execution:

1. Preprocessing: Handles directives like #include and #define

2. Compilation: Converts source code into object code

3. Assembly: Converts object code into assembly

4. Linking: Links multiple object files and libraries

5. Execution: Generates the executable file

4. Variables, Constants, Identifiers

 Variable: Storage container for data

 int x = 10;

 Constant: Fixed value that cannot change

 const float PI = 3.14;

 #define SIZE 100

 Identifier: Name used for variables, functions, arrays, etc.

5. Keywords in C
These are reserved words with special meaning:
Examples: int, return, if, else, void, for, while, break, continue

6. printf() and scanf() for Input/Output

 printf(): Prints output to the screen

 scanf(): Takes input from the user

int a;

printf("Enter a number: ");

scanf("%d", &a);

printf("You entered: %d", a);

2
🔶 1. Bitwise Operations

Bitwise operators work on binary (bit) level to manipulate bits directly.

Examples:

1. 5 & 3 (AND) → 101 & 011 = 001 → Result = 1

2. 5 | 3 (OR) → 101 | 011 = 111 → Result = 7

3. 5 ^ 3 (XOR) → 101 ^ 011 = 110 → Result = 6

Extra Examples:

 ~5 → Bitwise NOT = -6

 5 << 1 → Left Shift → 10

 5 >> 1 → Right Shift → 2

Used in: Encryption, compression, hardware control

🔶 2. Command-line Arguments

Used to pass inputs from terminal while running the program.

Syntax:

int main(int argc, char *argv[])

 argc: number of arguments

 argv[]: array of arguments

Examples:

1. Print name from CLI:

./program Akash

printf("%s", argv[1]); // Output: Akash

2. Add numbers:

int a = atoi(argv[1]);

int b = atoi(argv[2]);

printf("%d", a + b);

3. Loop through all arguments:

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

printf("%s\n", argv[i]);

🔶 3. Creating and Including Header Files

Used for separating declarations and improving modularity.

Steps:

1. Create myfunc.h

void greet();

2. Create myfunc.c

#include <stdio.h>

void greet() {

printf("Hi\n");

3. Use in main.c

#include "myfunc.h"

Examples:

 Custom math library

 String utilities

 Constants declaration

🔶 4. Modular Programming

Organize program into separate modules (files).

Why? Easy debugging, scalability, reusability.

Examples:

1. Calculator app:

o main.c, add.c, sub.c

2. Student record:

o input.c, display.c, main.c

3. E-commerce logic:

o cart.c, order.c, main.c

Compile:

gcc main.c add.c sub.c -o calc

4
🔶 5. Linked Lists

Dynamic data structure with nodes connected by pointers.

Structure:

struct Node {

int data;

struct Node *next;

};

Examples:

1. Insert at beginning

2. Delete a node by value

3. Traverse and print list

Use case: When dynamic size is required.

🔶 6. Stack & Queue using Arrays/Linked List

Stack (LIFO)

 push(), pop(), peek()

Example: Using Array

int stack[100], top = -1;

stack[++top] = val; // push

val = stack[top--]; // pop

Queue (FIFO)

 enqueue(), dequeue()

Example: Using Array

queue[rear++] = val; // enqueue

val = queue[front++]; // dequeue

Using Linked List:

struct Node {

int data;

struct Node *next;

};

 Stack: Insert/delete from head

 Queue: Insert at end, delete from front

5
DATA TYPES & OPERATORS

🧩 Data Types in C/C++

Data
Description Example
Type

Stores integers (whole numbers). Typically 4


int int age = 25;
bytes.

char Stores a single character. 1 byte. char grade = 'A';

Stores single-precision decimal numbers. 4


float float price = 12.99;
bytes.

Stores double-precision decimal numbers. 8 double pi =


double
bytes. 3.141592;

🔧 Type Modifiers

Type modifiers are used to alter the range and storage of data types.

Modifier Description

short Reduces the size of int (typically 2 bytes).

long Increases the size of int or double.

6
Modifier Description

Allows both positive and negative values. (Default for


signed
int)

Allows only positive values (doubles the positive


unsigned
range).

Example:

Copy code

unsigned int u = 30000;

long double d = 123.456789;

Operators in C/C++

1️⃣ Arithmetic Operators

Used for basic mathematical operations:

Operato Exampl
Meaning
r e

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

Modulus
% a%b
(remainder)

2️⃣ Relational Operators

Used for comparisons (returns true or false):

Operato Exampl
Meaning
r e

== Equal to a == b

!= Not equal to a != b

7
Operato Exampl
Meaning
r e

> Greater than a>b

< Less than a<b

Greater or
>= a >= b
equal

<= Less or equal a <= b

3️⃣ Logical Operators

Used to combine multiple conditions:

Operato
Meaning Example
r

a > 5 && b <


&& Logical AND
10

` `

! Logical NOT !(a == b)

4️⃣ Bitwise Operators

Operate on bits (binary level):

Operato
Meaning Example
r

& Bitwise AND a & b

` ` Bitwise OR

^ Bitwise XOR a ^ b

~ Bitwise NOT ~a

<< Left shift a << 2

>> Right shift a >> 2

5️⃣ Assignment Operators

Assign values to variables:

Operato
Meaning Example
r

= Assign x = 10

8
Operato
Meaning Example
r

x += 5 (same as x = x
+= Add and assign
+ 5)

Subtract and
-= x -= 3
assign

*= Multiply and assign x *= 2

/= Divide and assign x /= 4

Modulus and
%= x %= 3
assign

6️⃣ Increment/Decrement Operators

Operato
Meaning Example
r

x++ or +
++ Increment by 1
+x

Decrement by
-- x-- or --x
1

🔁 Type Conversion

1. Implicit Conversion (Type Promotion):

 Automatically done by compiler.

 Smaller data type is promoted to larger one.

Example:

Copy code

int a = 5;

float b = a; // int promoted to float

2. Explicit Conversion (Type Casting):

 Manually convert one type to another.

Syntax:

Copy code

float b = 5.67;

int a = (int)b; // result is 5

9
CONTROL FLOW

Control flow determines the order of execution of statements in a program.

🔹 1. Conditional Statements

Used to perform different actions based on different conditions.

Statement Description

if Executes a block if condition is true.

if-else Executes one block if condition is true, otherwise another block.

nested if if statement inside another if. Used for multiple levels of condition.

else-if ladder Tests multiple conditions in sequence.

Selects one of many blocks of code to execute based on the value of a


switch
variable.

🔸 Syntax Examples:

Copy code

// if

if (a > 0) {

printf("Positive");

// if-else

if (a % 2 == 0)

printf("Even");

else

printf("Odd");

// nested if

if (a > 0) {

10
if (a < 100)

printf("Positive and less than 100");

// else-if ladder

if (marks >= 90)

printf("A+");

else if (marks >= 80)

printf("A");

else

printf("Below A");

// switch

switch(choice) {

case 1: printf("Option 1"); break;

case 2: printf("Option 2"); break;

default: printf("Invalid");

🔹 2. Looping Statements

Used to repeat a block of code multiple times.

Loop
Description
Type

for Loop with counter. Pre-defined iterations.

Entry-controlled loop. Checks condition before


while
execution.

do-while Exit-controlled loop. Executes at least once.

🔸 Syntax Examples:

Copy code

// for loop

11
for (int i = 1; i <= 5; i++) {

printf("%d ", i);

// while loop

int i = 1;

while (i <= 5) {

printf("%d ", i);

i++;

// do-while loop

int i = 1;

do {

printf("%d ", i);

i++;

} while (i <= 5);

🔹 3. Jump Statements

Used to alter the normal flow of execution.

Stateme
Description
nt

break Exits from the loop or switch case immediately.

continue Skips current iteration and jumps to the next one.

goto Transfers control to a labeled statement.

Exits from the current function and returns control to the


return
caller.

🔸 Syntax Examples:

Copy code

// break

12
for (int i = 0; i < 5; i++) {

if (i == 3) break;

printf("%d ", i);

// continue

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

if (i == 2) continue;

printf("%d ", i);

// goto

goto label;

printf("This won't print");

label:

printf("Jumped here!");

// return

int add(int a, int b) {

return a + b;

ARRAYS & STRINGS

🧩 1. Arrays

✅ Types of Arrays:

Type Description

1D A linear collection of elements of the same


Array type.

2D A matrix (table) of rows and columns of


Array elements.

13
🔹 1D Array – Declaration & Initialization

Copy code

int arr[5]; // Declaration

int arr[5] = {10, 20, 30, 40, 50}; // Initialization

🔹 Accessing 1D Array Elements

Copy code

printf("%d", arr[2]); // Outputs 30

🔹 2D Array – Declaration & Initialization

Copy code

int mat[2][3]; // 2 rows, 3 columns

int mat[2][3] = {

{1, 2, 3},

{4, 5, 6}

};

🔹 Accessing 2D Array Elements

Copy code

printf("%d", mat[1][2]); // Outputs 6

🧩 2. Strings

Strings are arrays of characters ending with a null character ('\0').

🔹 Declaration of Strings

Copy code

char str1[20]; // Declaration

char str2[] = "Hello"; // Initialization

char str3[6] = {'H','e','l','l','o','\0'}; // Manual initialization

🔹 String Input/Output

14
c

Copy code

char name[50];

scanf("%s", name); // Reads single word (no spaces)

gets(name); // Reads full line (use with caution)

printf("%s", name); // Prints string

puts(name); // Prints string with newline

3. String Functions (in <string.h>)

Functio
Description Example
n

Returns the length of string (excluding '\ strlen("Akash") →


strlen()
0) 5

strcpy() Copies one string into another strcpy(dest, src);

strcat() Concatenates (joins) two strings strcat(str1, str2);

Compares two strings (returns 0 if


strcmp() strcmp(str1, str2);
equal)

🔸 Example:

Copy code

#include <stdio.h>

#include <string.h>

int main() {

char name[20] = "Akash";

char greet[20];

strcpy(greet, "Hello ");

strcat(greet, name);

printf("%s\n", greet); // Output: Hello Akash

printf("Length: %d", strlen(greet)); // Output: Length: 11

return 0;

15
}

FUNCTIONS

Functions allow you to divide a program into smaller, manageable sections that perform
specific tasks.

🔹 1. Function Declaration and Definition

Term Description

Declaratio Tells the compiler about the function name, return type, and parameters (also
n called prototype).

Definition Contains the actual code or body of the function.

✅ Example:

Copy code

// Declaration

int add(int a, int b);

// Definition

int add(int a, int b) {

return a + b;

🔹 2. Function Calling

To execute a function, you "call" it from the main() or another function.

✅ Example:

Copy code

int result = add(10, 5);

printf("Sum = %d", result);

🔹 3. Call by Value

 A copy of the actual arguments is passed.

 Changes made in the function do not affect the original values.

✅ Example:

16
c

Copy code

void change(int x) {

x = 50;

int main() {

int a = 10;

change(a);

printf("%d", a); // Output: 10

🔹 4. Recursion

A function calling itself is called recursion.

✅ Example: Factorial

Copy code

int factorial(int n) {

if (n == 0) return 1;

else return n * factorial(n - 1);

 Must have a base condition to avoid infinite loop.

🔹 5. Storage Classes

Storage classes define scope, visibility, and lifetime of variables.

Class Description

auto Default for local variables. Lifetime: inside the block.

extern Refers to a global variable defined elsewhere.

Retains value between function calls. Limited to


static
file/block.

Requests to store variable in CPU register (faster


register
access).

✅ Example:

17
Copy code

void example() {

static int x = 0; // retains value

x++;

printf("%d ", x);

If you call example() multiple times, output will be:

Copy code

1 2 3 ...

POINTERS

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

🔹 1. Basics of Pointers

Concept Description

Declaration A pointer is declared using * symbol.

Assigning the address of a variable using


Initialization
&.

Accessing the value at the address using


Dereferencing
*.

✅ Example:

Copy code

int a = 10;

int *ptr = &a; // pointer to int

printf("%d", *ptr); // Output: 10 (value of a)

🔹 2. Pointer Arithmetic

Operatio
Meaning
n

Moves to next memory location (based on data type


ptr + 1
size).

ptr - 1 Moves to previous memory location.

✅ Example:

18
Copy code

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

int *p = arr;

printf("%d", *(p + 1)); // Output: 20

🔹 3. Pointers with Arrays

 Array name is a pointer to the first element.

✅ Example:

Copy code

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

int *ptr = arr;

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

printf("%d ", *(ptr + i));

🔹 4. Pointers with Functions

You can pass:

 By value (copy of value),

 By pointer (original address).

✅ Call by Reference using Pointer:

Copy code

void update(int *x) {

*x = *x + 5;

int main() {

int a = 10;

update(&a);

printf("%d", a); // Output: 15

19
🔹 5. NULL Pointer

 A pointer that points to nothing (0).

 Safe to initialize pointers with NULL.

✅ Example:

Copy code

int *ptr = NULL;

🔹 6. const Pointer

Type Description

const int *p You can’t modify the value pointed to.

int *const p You can’t change the address stored.

const int *const You can’t change either value or


p address.

✅ Example:

Copy code

const int a = 10;

const int *p = &a; // *p = 20; ❌ Not allowed

🔹 7. Double Pointer (**ptr)

 A pointer to another pointer (used in dynamic memory, arrays of strings, etc.)

✅ Example:

Copy code

int a = 5;

int *p = &a;

int **pp = &p;

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

STRUCTURES & UNIONS

20
🔹 1. Declaring and Using Structures

A structure is a user-defined data type that groups related variables of different types
under one name.

✅ Declaration:

Copy code

struct Student {

int roll;

char name[20];

float marks;

};

✅ Creating & Accessing:

Copy code

struct Student s1;

s1.roll = 1;

strcpy(s1.name, "Akash");

s1.marks = 89.5;

printf("%d %s %.2f", s1.roll, s1.name, s1.marks);

🔹 2. Array of Structures

Used to store information of multiple records.

✅ Example:

Copy code

struct Student s[3];

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

scanf("%d %s %f", &s[i].roll, s[i].name, &s[i].marks);

🔹 3. Nested Structures

A structure inside another structure.

✅ Example:

21
c

Copy code

struct Date {

int day, month, year;

};

struct Student {

int roll;

struct Date dob;

};

🔹 4. Pointer to Structure

Use arrow operator (->) to access members with a pointer.

✅ Example:

Copy code

struct Student s1 = {1, "Akash", 91.5};

struct Student *ptr = &s1;

printf("%d %s %.2f", ptr->roll, ptr->name, ptr->marks);

🔹 5. Union: Definition and Use

A union is like a structure but all members share the same memory location.

✅ Declaration:

Copy code

union Data {

int i;

float f;

char str[20];

};

union Data d;

✅ Usage:

22
c

Copy code

d.i = 10;

d.f = 5.5; // Overwrites d.i

strcpy(d.str, "Hello"); // Overwrites d.f

printf("%s", d.str); // Only last value is valid

🔹 6. Difference Between Structure and Union

Featur
Structure Union
e

Each member has separate


Memory All members share same space
space

Size Sum of all members' sizes Size of largest member

Use Store multiple values at once Store one value at a time

All members can be used Only one member holds value at a


Access
together time

DYNAMIC MEMORY ALLOCATION

Dynamic Memory Allocation (DMA) allows memory to be allocated during runtime, using
functions from the <stdlib.h> header.

🔹 1. malloc() — Memory Allocation

 Allocates a single block of memory.

 Memory contains garbage values.

Copy code

int *ptr;

ptr = (int*) malloc(5 * sizeof(int)); // allocates memory for 5 integers

🔹 2. calloc() — Contiguous Allocation

 Allocates multiple blocks and initializes them to 0.

Copy code

int *ptr;

23
ptr = (int*) calloc(5, sizeof(int)); // allocates and sets 5 integers to 0

🔹 3. realloc() — Reallocation

 Changes the size of previously allocated memory using malloc() or calloc().

Copy code

ptr = (int*) realloc(ptr, 10 * sizeof(int)); // increases size to hold 10 integers

🔹 4. free() — Freeing Memory

 Releases dynamically allocated memory back to the system.

Copy code

free(ptr);

🔸 Always use free() after use to avoid memory leaks.

⚠️Memory Leak

 Occurs when allocated memory is not freed, causing wastage of memory.

❌ Example:

Copy code

int *ptr = malloc(100); // allocated

ptr = malloc(200); // previous memory lost → memory leak

⚠️Dangling Pointer

 A pointer that points to a freed memory location.

❌ Example:

Copy code

int *ptr = malloc(10);

free(ptr); // memory freed

printf("%d", *ptr); // dangling pointer → unsafe!

✅ Summary Table:

24
Functio
Purpose Initialization Can Resize Must Free
n

malloc() Allocates memory ❌ No (garbage) ✅ With realloc() ✅

Allocates +
calloc() ✅ (to 0) ✅ ✅
initializes

Resize memory
realloc() ❌ ✅ ✅
block

free() Deallocates memory ❌ ❌ ❌ (used to free)

FILE HANDLING in C

File handling allows you to store and access data permanently in files instead of
temporary memory (RAM).

🔹 1. File Opening and Closing

Functio
Description
n

Opens a file in the specified


fopen()
mode.

fclose() Closes an opened file.

✅ Example:

Copy code

FILE *fp;

fp = fopen("data.txt", "r"); // Open file in read mode

fclose(fp); // Close the file

🔹 2. File Modes

Mode Description

r Open file for reading (file must exist).

Open file for writing (creates file or erases


w
existing).

a Open file to append at end.

r+ Open file for reading and writing.

w+ Open file for reading and writing (overwrites).

a+ Open for reading and appending.

25
Mode Description

rb, wb,
Same as above but in binary mode.
ab

🔹 3. File Reading/Writing Functions

📥 Reading from File

Functio
Description
n

fscanf() Reads formatted input from a file.

fgets() Reads a string (line) from a file.

Reads a single character from a


getc()
file.

✅ Examples:

Copy code

fscanf(fp, "%d", &num); // Read integer

fgets(str, 100, fp); // Read a line

char ch = getc(fp); // Read a character

📤 Writing to File

Functio
Description
n

Writes formatted output to a


fprintf()
file.

fputs() Writes a string to a file.

Writes a single character to a


putc()
file.

✅ Examples:

Copy code

fprintf(fp, "Roll: %d", roll); // Write integer

fputs("Hello World", fp); // Write string

putc('A', fp); // Write character

🔹 4. File Pointer (FILE *fp)

26
 FILE is a special structure that stores information about the file.

 FILE *fp is a pointer used to manage file operations.

✅ Example:

Copy code

FILE *fp;

fp = fopen("data.txt", "w");

if (fp == NULL) {

printf("File cannot be opened!");

} else {

fprintf(fp, "Hello File!");

fclose(fp);

✅ Summary Table:

Concept Function Purpose

File Open fopen() Open/create a file

File Close fclose() Close an opened file

fprintf(), fputs(),
Write Data Write to file
putc()

fscanf(), fgets(),
Read Data Read from file
getc()

Pointer to file
File Pointer FILE *fp
structure

PREPROCESSOR DIRECTIVES

Preprocessor directives are instructions that are processed before compilation


begins. They start with a # symbol.

🔹 1. #include — Header File Inclusion

 Used to include standard or user-defined files in a program.

Syntax Meaning

#include<stdio.h Includes standard input-output


> functions

27
Syntax Meaning

#include
Includes a user-defined header file
"myfile.h"

🔹 2. #define — Macros and Constants

 Used to define macros or constant values.

✅ Constant Example:

Copy code

#define PI 3.14159

printf("%.2f", PI);

✅ Macro Example:

Copy code

#define SQUARE(x) ((x)*(x))

printf("%d", SQUARE(5)); // Output: 25

⚠️Use parentheses () in macros to avoid precedence issues.

🔹 3. Macros vs Constants

Feature #define Macro const Variable

Type checking ❌ No type checking ✅ Yes

Memory ❌ No memory used ✅ Uses memory

Scope Global Local/global

const float PI =
Syntax #define PI 3.14
3.14;

🔹 4. Conditional Compilation

Used to compile code conditionally depending on whether a macro is defined.

Directive Description

#if Checks if condition is true

#ifdef Checks if macro is defined

Checks if macro is not


#ifndef
defined

#else / Else or else-if alternative

28
Directive Description

#elif

#endif Ends conditional block

✅ Example:

Copy code

#define DEBUG

#ifdef DEBUG

printf("Debug mode ON\n");

#endif

✅ Another Example:

Copy code

#define VALUE 10

#if VALUE > 5

printf("High value\n");

#else

printf("Low value\n");

#endif

✅ Summary Table:

Directive Purpose

#include Include header files

#define Define constants/macros

#if / Conditional compilation


#endif blocks

#ifdef Compile if macro is defined

Compile if macro is not


#ifndef
defined

1. Bitwise Operations in Depth

Bitwise operators work on individual bits of integers.

29
Operato Example (a=5, Resul
Name
r b=3) t

& AND a&b→5&3→1

` ` OR `a

^ XOR a^b→5^3→6

~ NOT ~a → ~5 → -6

<< Left Shift a << 1 → 10

Right
>> a >> 1 → 2
Shift

✅ Usage:

Copy code

int a = 5, b = 3;

printf("%d", a & b); // Output: 1

🔹 2. Command-Line Arguments

Used to pass arguments to main() via terminal.

Copy code

int main(int argc, char *argv[])

Ter
Meaning
m

argc Argument count (number of arguments)

Argument vector (array of arguments as


argv
strings)

✅ Example:

Copy code

int main(int argc, char *argv[]) {

printf("Program Name: %s\n", argv[0]);

if (argc > 1)

printf("Argument 1: %s\n", argv[1]);

return 0;

To run:

30
bash

Copy code

./a.out hello

🔹 3. Creating and Including Header Files

Split your code for modularity and reuse.

✅ Step 1: Create Header File — mathutils.h

Copy code

int add(int, int);

✅ Step 2: Create Source File — mathutils.c

Copy code

#include "mathutils.h"

int add(int a, int b) {

return a + b;

✅ Step 3: Use in Main File

Copy code

#include "mathutils.h"

int main() {

printf("%d", add(10, 5));

🔹 4. Modular Programming

Modular programming means dividing code into separate modules/files.

✅ Benefits:

 Easy to debug

 Reusable

 Organized

Example: Use .c files for logic and .h files for declarations.

31
🔹 5. Linked Lists

Implemented using structures and pointers.

✅ Node Definition:

Copy code

struct Node {

int data;

struct Node* next;

};

✅ Create and Traverse:

Copy code

struct Node *head = NULL;

head = (struct Node*)malloc(sizeof(struct Node));

head->data = 10;

head->next = NULL;

✅ Print List:

Copy code

struct Node* temp = head;

while (temp != NULL) {

printf("%d -> ", temp->data);

temp = temp->next;

🔹 6. Stack & Queue using Arrays and Linked List

✅ Stack Using Array:

Copy code

#define SIZE 100

int stack[SIZE], top = -1;

void push(int val) {

stack[++top] = val;

32
}

int pop() {

return stack[top--];

✅ Stack Using Linked List:

Copy code

struct Node {

int data;

struct Node* next;

};

void push(struct Node** top, int val) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data = val;

newNode->next = *top;

*top = newNode;

✅ Queue Using Array:

Copy code

int queue[SIZE], front = -1, rear = -1;

void enqueue(int val) {

queue[++rear] = val;

int dequeue() {

return queue[++front];

✅ Queue Using Linked List:

Copy code

struct Node {

int data;

33
struct Node* next;

};

struct Node *front = NULL, *rear = NULL;

✅ 1. Student Record System (with File Handling)

34
c

Copy code

#include <stdio.h>

#include <stdlib.h>

struct Student {

int roll;

char name[50];

float marks;

};

int main() {

struct Student s;

FILE *fp = fopen("students.txt", "a");

if (!fp) {

printf("Error opening file!");

return 1;

printf("Enter Roll: ");

scanf("%d", &s.roll);

printf("Enter Name: ");

scanf("%s", s.name);

printf("Enter Marks: ");

scanf("%f", &s.marks);

fprintf(fp, "%d %s %.2f\n", s.roll, s.name, s.marks);

fclose(fp);

printf("Record saved to file.\n");

return 0;

Output:

35
mathematica

Copy code

Enter Roll: 101

Enter Name: Akash

Enter Marks: 88.5

Record saved to file.

✅ 2. Simple Calculator Using Function Pointers

Copy code

#include <stdio.h>

float add(float a, float b) { return a + b; }

float sub(float a, float b) { return a - b; }

float mul(float a, float b) { return a * b; }

float divi(float a, float b) { return b != 0 ? a / b : 0; }

int main() {

float a, b;

char op;

float (*func[])(float, float) = { add, sub, mul, divi };

printf("Enter expression (e.g. 4 + 5): ");

scanf("%f %c %f", &a, &op, &b);

switch (op) {

case '+': printf("Result = %.2f\n", func[0](a, b)); break;

case '-': printf("Result = %.2f\n", func[1](a, b)); break;

case '*': printf("Result = %.2f\n", func[2](a, b)); break;

case '/': printf("Result = %.2f\n", func[3](a, b)); break;

default: printf("Invalid operator\n");

return 0;

36
}

Output:

cpp

Copy code

Enter expression (e.g. 4 + 5): 10 * 4

Result = 40.00

✅ 3. Singly Linked List: Insertion and Display

Copy code

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node *next;

};

void insert(struct Node **head, int val) {

struct Node *newNode = (struct Node*) malloc(sizeof(struct Node));

newNode->data = val;

newNode->next = *head;

*head = newNode;

void display(struct Node *head) {

while (head) {

printf("%d -> ", head->data);

head = head->next;

printf("NULL\n");

int main() {

37
struct Node *head = NULL;

insert(&head, 10);

insert(&head, 20);

insert(&head, 30);

display(head);

return 0;

Output:

rust

Copy code

30 -> 20 -> 10 -> NULL

✅ 4. Dynamic Array (DMA) with Sum

Copy code

#include <stdio.h>

#include <stdlib.h>

int main() {

int *arr, n, sum = 0;

printf("Enter number of elements: ");

scanf("%d", &n);

arr = (int*) malloc(n * sizeof(int));

if (!arr) {

printf("Memory allocation failed.");

return 1;

printf("Enter %d elements:\n", n);

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

scanf("%d", &arr[i]);

sum += arr[i];

38
}

printf("Sum = %d\n", sum);

free(arr);

return 0;

Output:

mathematica

Copy code

Enter number of elements: 4

Enter 4 elements:

2468

Sum = 20

1. Print 'Hello, World!'

Copy code

#include <stdio.h>

int main() {

printf("Hello, World!\n");

return 0;

✅ 2. Add Two Numbers

Copy code

#include <stdio.h>

int main() {

int a = 5, b = 3;

printf("Sum = %d\n", a + b);

return 0;

✅ 3. Swap Two Numbers Using a Temporary Variable

39
Copy code

#include <stdio.h>

int main() {

int a = 5, b = 10, temp;

temp = a;

a = b;

b = temp;

printf("a = %d, b = %d\n", a, b);

return 0;

✅ 4. Swap Two Numbers Without a Temporary Variable

Copy code

#include <stdio.h>

int main() {

int a = 5, b = 10;

a = a + b;

b = a - b;

a = a - b;

printf("a = %d, b = %d\n", a, b);

return 0;

5. Find Maximum of Two Numbers Using if-else

Copy code

#include <stdio.h>

int main() {

int a = 5, b = 10;

if (a > b)

printf("Max = %d\n", a);

else

printf("Max = %d\n", b);

return 0;

40
}

✅ 6. Check if Number is Even or Odd

Copy code

#include <stdio.h>

int main() {

int num = 7;

if (num % 2 == 0)

printf("Even\n");

else

printf("Odd\n");

return 0;

✅ 7. Print Numbers from 1 to 10 Using For Loop

Copy code

#include <stdio.h>

int main() {

for (int i = 1; i <= 10; i++)

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

return 0;

✅ 8. Print Multiplication Table of a Number

Copy code

#include <stdio.h>

int main() {

int n = 5;

for (int i = 1; i <= 10; i++)

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

return 0;

41
}

✅ 9. Calculate Factorial Using For Loop

Copy code

#include <stdio.h>

int main() {

int n = 5, fact = 1;

for (int i = 1; i <= n; i++)

fact *= i;

printf("Factorial = %d\n", fact);

return 0;

✅ 10. Calculate Factorial Using Recursion

Copy code

#include <stdio.h>

int factorial(int n) {

if (n == 0)

return 1;

return n * factorial(n - 1);

int main() {

printf("Factorial = %d\n", factorial(5));

return 0;

✅ 11. Check if a Number is Prime

Copy code

#include <stdio.h>

int main() {

int n = 7, flag = 1;

42
for (int i = 2; i < n; i++) {

if (n % i == 0) {

flag = 0;

break;

if (flag)

printf("Prime\n");

else

printf("Not Prime\n");

return 0;

✅ 12. Generate Fibonacci Series

Copy code

#include <stdio.h>

int main() {

int a = 0, b = 1, n = 10;

printf("%d %d ", a, b);

for (int i = 2; i < n; i++) {

int c = a + b;

printf("%d ", c);

a = b;

b = c;

return 0;

✅ 13. Reverse a Number

Copy code

#include <stdio.h>

int main() {

43
int num = 1234, rev = 0;

while (num != 0) {

rev = rev * 10 + num % 10;

num /= 10;

printf("Reverse = %d\n", rev);

return 0;

✅ 14. Check if a Number is Palindrome

Copy code

#include <stdio.h>

int main() {

int num = 121, orig = num, rev = 0;

while (num != 0) {

rev = rev * 10 + num % 10;

num /= 10;

if (rev == orig)

printf("Palindrome\n");

else

printf("Not Palindrome\n");

return 0;

44

You might also like