[Go to site: main page, start]

100% found this document useful (1 vote)
52 views34 pages

Problem Solving Using C Study Notes

The document provides comprehensive study notes on Problem Solving using C, covering essential programming concepts such as algorithms, control structures, data types, and loops. It includes detailed explanations of C language fundamentals, including syntax, operators, and memory management. Additionally, it offers examples and code snippets to illustrate key programming techniques and problem-solving strategies.
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
100% found this document useful (1 vote)
52 views34 pages

Problem Solving Using C Study Notes

The document provides comprehensive study notes on Problem Solving using C, covering essential programming concepts such as algorithms, control structures, data types, and loops. It includes detailed explanations of C language fundamentals, including syntax, operators, and memory management. Additionally, it offers examples and code snippets to illustrate key programming techniques and problem-solving strategies.
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

Problem Solving Using C: Comprehensive

Study Notes
MCA 1st Year | Subject Code: BMC102/KCA102

Table of Contents
1. Basics of Programming & Problem Solving
2. Fundamentals of C Language
3. Data Types & Variables
4. Operators & Expressions
5. Control Structures: Conditional Statements
6. Loops & Iteration
7. Functions & Recursion
8. Arrays
9. Pointers
10. Strings
11. Structures & Unions
12. Dynamic Memory Allocation
13. File Handling
14. Graphics in C

1. Basics of Programming & Problem Solving


1.1 What is Problem Solving?
Problem solving is a systematic approach to analyzing a problem and developing a
solution. It involves breaking down complex problems into manageable steps and
implementing them using a programming language.

Steps in Problem Solving:


1. Problem Analysis – Understand what needs to be solved
2. Algorithm Design – Write step-by-step solution logic
3. Flowchart Creation – Visual representation of algorithm
4. Code Implementation – Write the program
5. Testing & Debugging – Verify correctness and fix errors

1.2 Algorithm
An algorithm is a step-by-step procedure to solve a problem. It is independent of any
programming language.

Characteristics of a Good Algorithm:


Clarity – Clear, unambiguous instructions
Finiteness – Must terminate after finite steps
Input – Should accept zero or more inputs
Output – Must produce at least one output
Effectiveness – Steps must be simple and executable
Efficiency – Should use minimum resources
Example: Algorithm to find the largest of three numbers

1. Start
2. Read three numbers A, B, C
3. If A > B, then go to step 4; else go to step 5
4. If A > C, then largest = A; else largest = C
5. If B > C, then largest = B; else largest = C
6. Print largest
7. End

1.3 Flowchart
A flowchart is a graphical representation of an algorithm using standardized symbols.
Flowchart Symbols:

Symbol Name Purpose


Oval/Ellipse Terminal Start/End point
Rectangle Process Processing/Computation
Diamond Decision Conditional branching (if-else)
Input/Outpu
Parallelogram Read/Write operations
t
Arrow Flow Direction of flow
Rectangle Connection between distant
Connector
(dashed) points

Flowchart: Find Largest of Three Numbers

START

READ A, B, C

A > B?
/
YES NO
||
A > C? B > C?
/\/
YNYN
||||
L=A L=C L=B L=C
||||
└──┴──┴──┘

PRINT L

END

1.4 Structured Programming


Structured programming is a programming paradigm that emphasizes logical flow using:
Sequence – Execute statements one after another
Selection – Make decisions using if-else, switch
Iteration – Repeat using loops (for, while, do-while)

Benefits:
Easier to understand and maintain
Reduced complexity
Better documentation
Fewer errors

2. Fundamentals of C Language
2.1 History & Features of C
History:
Developed by Dennis Ritchie in 1972 at Bell Labs
Based on B language
Official standard: ANSI C (1989)

Salient Features of C:
Simple & Efficient – Minimal keywords, straightforward syntax
Portable – Code runs on different platforms
Compact – Small memory footprint
Fast Execution – Close to assembly language
Powerful – Supports pointers, dynamic memory allocation
Flexible – Supports both high-level and low-level programming
Extensible – Can be combined with assembly language
2.2 Structure of a C Program
#include <stdio.h> // Header file (preprocessor directive)
#include <conio.h>
int main() // Main function (entry point)
{
int x = 10; // Variable declaration & initialization
printf("Value: %d\n", x); // Output statement
return 0; // Return statement
}
Components:

1. Header Files – #include <stdio.h> (standard I/O library)


2. Main Function – Entry point of program
3. Variable Declaration – Define data types
4. Statements – Instructions to execute
5. Return Statement – Exit program with status

2.3 Compilation & Execution Process


Steps to Compile and Run:
1. Preprocessing – Remove comments, include header files
2. Compilation – Convert to machine code (.obj file)
3. Linking – Link with library functions (.exe file)
4. Execution – Run the executable program

Command Line:
gcc program.c -o program // Compile
./program // Execute (Linux/Mac)
program // Execute (Windows)

2.4 Character Set, Tokens & Keywords


Character Set in C:
Letters – A-Z, a-z
Digits – 0-9
Special Characters – +, -, *, /, =, (, ), [, ], {, }, etc.
White Space – Space, tab, newline
Tokens – Smallest units of a program:

Keywords – Reserved words (int, if, while, etc.)


Identifiers – User-defined names (variables, functions)
Constants – Fixed values (10, 3.14, 'A')
Strings – Sequence of characters ("Hello")
Operators – Symbols for operations (+, -, *, /)
Punctuation – ; , ( ) [ ] { }
Keywords in C (32 total):
auto break case char const continue default do
double else enum extern float for goto if
inline int long register return short signed sizeof
static struct switch typedef union unsigned void volatile
while
Identifiers – Rules:

Start with letter or underscore (_)


Can contain letters, digits, underscores
Case-sensitive (x ≠ X)
Cannot be a keyword
Maximum length varies (typically 31+ characters)

2.5 Constants & Variables


Constants – Values that cannot be changed:
Integer Constants – 10, -5, 0x1A (hexadecimal)
Floating-Point Constants – 3.14, 2.5e-3 (exponential)
Character Constants – 'A', 'b', '\n' (escape sequence)
String Constants – "Hello World"
Variables – Named memory locations to store data:
int age; // Declaration
age = 25; // Initialization
int x = 10; // Declaration + Initialization

3. Data Types & Variables


3.1 Primary Data Types

Data Type Size (bytes) Range Format


char 1 -128 to 127 %c
int 2-4 -32,768 to 32,767 %d
float 4 3.4e-38 to 3.4e+38 %f
double 8 1.7e-308 to 1.7e+308 %lf

Size Modifiers:

short – Reduces size


long – Increases size
unsigned – Only positive values
Example:
unsigned int count = 50000;
long long bignum = 9223372036854775807LL;
float pi = 3.14f;
double precise = 3.141592653589793;

3.2 Variable Declaration & Initialization


int x; // Declaration (uninitialized)
int y = 20; // Declaration + Initialization
int a, b, c = 30; // Multiple declaration
Storage Classes:

Class Storage Scope Lifetime


auto Memory (stack) Local Function duration
register CPU register Local Function duration
static Memory Local/Global Program duration
extern Memory Global Program duration

4. Operators & Expressions


4.1 Types of Operators
1. Arithmetic Operators

Addition a + b
Subtraction a - b
Multiplication a * b
/ Division a / b
% Modulus a % b (remainder)

2. Relational Operators
== Equal to a == b
!= Not equal to a != b
Greater than a > b
< Less than a < b
= Greater or equal a >= b
<= Less or equal a <= b
3. Logical Operators
&& AND (both conditions true)
|| OR (at least one true)
! NOT (reverse condition)

4. Assignment Operators
= Simple assignment x = 5
+= Add and assign x += 3 → x = x + 3
-= Subtract and assign x -= 2 → x = x - 2
*= Multiply and assign x *= 4 → x = x * 4
/= Divide and assign x /= 2 → x = x / 2
%= Modulus and assign x %= 3 → x = x % 3
5. Increment & Decrement Operators
++ Pre-increment x (increment, then use)
++ Post-increment x (use, then increment)
-- Pre-decrement --x (decrement, then use)
-- Post-decrement x-- (use, then decrement)

6. Bitwise Operators
& AND a & b
| OR a | b
^ XOR a ^ b
~ NOT ~a
<< Left shift a << 2
Right shift a >> 2

4.2 Operator Precedence

Precedence Operator Associativity


1 () [] → . Left to Right
2 ! ~ ++ -- + - * & sizeof Right to Left
3 */% Left to Right
4 +- Left to Right
5 << >> Left to Right
6 < <= > >= Left to Right
7 == != Left to Right
8 & Left to Right
9 ^ Left to Right
10 | Left to Right
11 && Left to Right
12 || Left to Right
13 ?: Right to Left
14 = += -= *= /= %= &= ^= |= <<= >>= Right to Left
5. Control Structures: Conditional Statements
5.1 Simple if Statement
Syntax:
if (condition) {
// Code executes if condition is TRUE
}

Example:
#include <stdio.h>
int main() {
int age = 18;
if (age >= 18) {
printf("You are an adult\n");
}
return 0;
}

5.2 if-else Statement


Syntax:
if (condition) {
// Code if TRUE
} else {
// Code if FALSE
}

Example:
#include <stdio.h>
int main() {
int num = 7;
if (num % 2 == 0) {
printf("Even number\n");
} else {
printf("Odd number\n");
}
return 0;
}

5.3 Nested if-else


Syntax:
if (condition1) {
if (condition2) {
// Code if both TRUE
} else {
// Code if 1 TRUE, 2 FALSE
}
} else {
// Code if 1 FALSE
}
Example:
#include <stdio.h>

int main() {
int x = 15;
if (x > 0) {
if (x > 10) {
printf("x is positive and greater than 10\n");
} else {
printf("x is positive but <= 10\n");
}
} else if (x < 0) {
printf("x is negative\n");
} else {
printf("x is zero\n");
}
return 0;
}

5.4 else-if Ladder


Syntax:
if (condition1) {
// Code 1
} else if (condition2) {
// Code 2
} else if (condition3) {
// Code 3
} else {
// Code 4 (default)
}
Example: Grade Calculation
#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);

if (marks >= 90) {


printf("Grade: A\n");
} else if (marks >= 80) {
printf("Grade: B\n");
} else if (marks >= 70) {
printf("Grade: C\n");
} else if (marks >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}
return 0;

5.5 switch Statement


Syntax:
switch (expression) {
case value1:
// Code 1
break;
case value2:
// Code 2
break;
default:
// Default code
}

Example: Simple Calculator


#include <stdio.h>
int main() {
char op;
float a, b;

printf("Enter operator (+, -, *, /): ");


scanf("%c", &op);
printf("Enter two numbers: ");
scanf("%f %f", &a, &b);

switch (op) {
case '+':
printf("Result: %.2f\n", a + b);
break;
case '-':
printf("Result: %.2f\n", a - b);
break;
case '*':
printf("Result: %.2f\n", a * b);
break;
case '/':
if (b != 0)
printf("Result: %.2f\n", a / b);
else
printf("Error: Division by zero\n");
break;
default:
printf("Invalid operator\n");
}
return 0;

Differences between switch and if-else:

Aspect switch if-else


Condition Type Only equality (==) Any relational/logical
Multiple Conditions Not possible Possible
Execution Faster Slower
Readability Better for many cases Better for ranges
Default Optional Not needed

6. Loops & Iteration


6.1 for Loop
Syntax:
for (initialization; condition; increment) {
// Loop body
}

Execution Flow:
1. Initialize counter variable
2. Check condition
3. If TRUE, execute body
4. Execute increment/decrement
5. Repeat from step 2
Example: Print numbers 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}

Example: Sum of n numbers


#include <stdio.h>
int main() {
int n, sum = 0, i;
printf("Enter n: ");
scanf("%d", &n);

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


sum += i; // sum = sum + i
}
printf("Sum: %d\n", sum);
return 0;

6.2 while Loop


Syntax:
while (condition) {
// Loop body
// Increment/Decrement
}
Characteristics:
Condition checked BEFORE execution (entry-controlled)
Body may not execute if condition is false
Used when number of iterations is unknown

Example: Print numbers while condition is true


#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}

6.3 do-while Loop


Syntax:
do {
// Loop body
// Increment/Decrement
} while (condition);
Characteristics:

Condition checked AFTER execution (exit-controlled)


Body executes AT LEAST ONCE
Useful for menus, input validation
Example: User input validation
#include <stdio.h>
int main() {
int age;
do {
printf("Enter age (0-100): ");
scanf("%d", &age);
if (age < 0 || age > 100)
printf("Invalid! Try again.\n");
} while (age < 0 || age > 100);

printf("Age accepted: %d\n", age);


return 0;

}
Differences:
Aspect for while do-while
Before
Initialization Inside loop Before loop
loop
Condition Check Before body Before body After body
In loop
Increment In body In body
statement
Minimum
0 0 1
Execution
Known Unknown At least
Best For
iterations iterations once

6.4 Nested Loops


Loops inside loops used for multi-dimensional iterations.
Example: Multiplication Table
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
printf("%d ", i * j);
}
printf("\n");
}
return 0;
}

Output:
123
246
369

6.5 break & continue Statements


break – Exits the loop immediately
for (i = 1; i <= 10; i++) {
if (i == 5)
break; // Exit when i = 5
printf("%d ", i);
}
// Output: 1 2 3 4
continue – Skips current iteration, continues to next
for (i = 1; i <= 5; i++) {
if (i == 3)
continue; // Skip i = 3
printf("%d ", i);
}
// Output: 1 2 4 5

7. Functions & Recursion


7.1 Introduction to Functions
A function is a reusable block of code that performs a specific task.
Advantages:
Code reusability
Modular code
Easier debugging
Better organization

7.2 Function Declaration, Definition & Call


Syntax:
return_type function_name(parameter_list); // Declaration (Prototype)
return_type function_name(parameter_list) { // Definition
// Function body
return value;
}
function_name(arguments); // Function call

Example: Function to add two numbers


#include <stdio.h>
// Function prototype (declaration)
int add(int a, int b);
int main() {
int x = 10, y = 20;
int sum = add(x, y); // Function call
printf("Sum: %d\n", sum);
return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}
7.3 Passing Arguments: Call by Value vs Call by Reference
Call by Value – Passes copy of variable
#include <stdio.h>
void change(int x) {
x = 100; // Changes only the copy
}
int main() {
int a = 5;
change(a);
printf("a = %d\n", a); // Output: 5 (unchanged)
return 0;
}

Call by Reference – Passes address of variable (using pointers)


#include <stdio.h>
void change(int *x) {
*x = 100; // Changes original variable
}
int main() {
int a = 5;
change(&a); // Pass address
printf("a = %d\n", a); // Output: 100 (changed)
return 0;
}

7.4 Recursive Functions


A recursive function calls itself to solve smaller instances of the same problem.
Components:
Base Case – Condition to stop recursion
Recursive Case – Function calls itself with different parameters

Example: Factorial using recursion


#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive case
}
int main() {
printf("Factorial of 5: %d\n", factorial(5)); // 120
return 0;
}
Example: Fibonacci Series
#include <stdio.h>
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int i;
for (i = 0; i < 7; i++) {
printf("%d ", fibonacci(i));
}
// Output: 0 1 1 2 3 5 8
return 0;
}

8. Arrays
8.1 One-Dimensional Arrays
Declaration & Initialization:
int arr[5]; // Array of 5 integers (uninitialized)
int arr[5] = {1, 2, 3, 4, 5}; // With initialization
int arr[] = {10, 20, 30}; // Size determined by elements

Accessing Array Elements:


arr[0] = 10; // Access using index (0-indexed)
printf("%d\n", arr[2]);
Example: Sum of array elements
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int sum = 0, i;

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


sum += arr[i];
}
printf("Sum: %d\n", sum); // Output: 150
return 0;

}
8.2 Two-Dimensional Arrays
Declaration & Initialization:
int matrix[3][3]; // 3x3 matrix
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
Accessing Elements:
matrix[0][1] = 5; // Access row 0, column 1
Example: Matrix Addition
#include <stdio.h>

int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int c[2][2];
int i, j;

// Add matrices
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}

// Print result
printf("Sum Matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;

8.3 Multidimensional Arrays


Arrays with more than 2 dimensions.
int cube[3][3][3]; // 3D array
int arr[2][3][4]; // 2x3x4 array
9. Pointers
9.1 Introduction to Pointers
A pointer is a variable that stores the memory address of another variable.
Declaration:
int *ptr; // Pointer to integer
char *cptr; // Pointer to character
float *fptr; // Pointer to float

9.2 Address (&) and Dereference (*) Operators


& Operator – Gets address of variable
int x = 10;
int *ptr = &x; // ptr contains address of x

* Operator – Gets value at address


printf("%d\n", *ptr); // Prints 10 (value of x)
Example:
#include <stdio.h>
int main() {
int x = 20;
int *ptr = &x;

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


printf("Address of x: %p\n", &x); // 0x7ffc...
printf("Value at ptr: %d\n", *ptr); // 20
printf("Address in ptr: %p\n", ptr); // 0x7ffc...
return 0;

9.3 Pointer Arithmetic


Pointers support arithmetic operations.
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // Points to first element

ptr++; // Points to next element


ptr--; // Points to previous element
ptr += 2; // Points 2 elements ahead
printf("%d\n", *ptr); // Value at current address
printf("%d\n", *(ptr + 1)); // Value at next address
9.4 Pointers to Arrays and Functions
Pointer to Array:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // Points to first element
// Access elements
printf("%d\n", *(ptr + 0)); // 1
printf("%d\n", *(ptr + 2)); // 3
Pointer to Function:
int add(int a, int b) {
return a + b;
}

int main() {
int (*fptr)(int, int) = add; // Pointer to function
printf("%d\n", fptr(5, 3)); // Calls add() through pointer
return 0;
}

9.5 Pointer to Pointer


A pointer that points to another pointer.
int x = 10;
int *ptr = &x; // Pointer to x
int **pptr = &ptr; // Pointer to pointer

printf("%d\n", x); // 10
printf("%d\n", *ptr); // 10
printf("%d\n", **pptr); // 10
Example:
#include <stdio.h>
int main() {
int a = 5;
int *p1 = &a;
int **p2 = &p1;

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


printf("*p1 = %d\n", *p1); // 5
printf("**p2 = %d\n", **p2); // 5

**p2 = 20;
printf("After change: a = %d\n", a); // 20
return 0;
}

10. Strings
10.1 Introduction to Strings
A string is an array of characters terminated by a null character '\0'.
Declaration & Initialization:
char str[20]; // String array (uninitialized)
char str[5] = "Hello"; // With initialization
char *str = "Hello"; // Pointer to string constant

10.2 String Input/Output


Reading Strings:
scanf("%s", str); // Read single word
fgets(str, 20, stdin); // Read line with spaces

Printing Strings:
printf("%s\n", str); // Print string
puts(str); // Print with newline

10.3 String Functions


Common String Functions:

Function Purpose
strlen(str) Length of string
strcpy(dest, src) Copy string
strcat(str1, str2) Concatenate strings
strcmp(str1, str2) Compare strings
strchr(str, char) Find character
strstr(str1, str2) Find substring

Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char str3[40];
// Length
printf("Length: %lu\n", strlen(str1)); // 5

// Copy
strcpy(str3, str1);
printf("Copy: %s\n", str3); // Hello

// Concatenate
strcat(str3, str2);
printf("Concatenate: %s\n", str3); // HelloWorld

// Compare
if (strcmp(str1, str2) == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");

return 0;

10.4 Array of Strings


char names[3][20] = {"Alice", "Bob", "Charlie"};

printf("%s\n", names[0]); // Alice


printf("%s\n", names[1]); // Bob
printf("%s\n", names[2]); // Charlie

11. Structures & Unions


11.1 Structures
A structure is a collection of different data types grouped together.
Declaration & Definition:
struct Student {
int rollNo;
char name[30];
float cgpa;
};
// OR in single step
struct Student {
int rollNo;
char name[30];
float cgpa;
} s1, s2;
Creating Structure Variable:
struct Student s1;
[Link] = 1;
strcpy([Link], "John");
[Link] = 8.5;

Example: Employee Record


#include <stdio.h>
#include <string.h>
struct Employee {
int empID;
char empName[30];
float salary;
char dept[20];
};
int main() {
struct Employee emp1;
[Link] = 101;
strcpy([Link], "Alice");
[Link] = 50000.00;
strcpy([Link], "IT");

printf("ID: %d\n", [Link]);


printf("Name: %s\n", [Link]);
printf("Salary: %.2f\n", [Link]);
printf("Dept: %s\n", [Link]);

return 0;

11.2 Array of Structures


Store multiple structure records.
#include <stdio.h>
#include <string.h>

struct Student {
int rollNo;
char name[30];
float marks;
};
int main() {
struct Student students[3];
int i;

// Input
for (i = 0; i < 3; i++) {
printf("Enter roll no: ");
scanf("%d", &students[i].rollNo);
printf("Enter name: ");
scanf("%s", students[i].name);
printf("Enter marks: ");
scanf("%f", &students[i].marks);
}

// Output
printf("\nStudent Records:\n");
for (i = 0; i < 3; i++) {
printf("%d\t%s\t%.2f\n",
students[i].rollNo,
students[i].name,
students[i].marks);
}

return 0;

11.3 Pointers to Structures


Access structure members using pointer.
struct Student *ptr = &s1;

// Access using -> operator


ptr->rollNo = 1;
printf("%s\n", ptr->name);
// OR using dereference
(*ptr).rollNo = 1;
printf("%s\n", (*ptr).name);
11.4 Nested Structures
Structure within structure.
struct Address {
char city[20];
char state[20];
int zipcode;
};
struct Person {
char name[30];
struct Address addr;
};

struct Person p1;


strcpy([Link], "Delhi");
[Link] = 110001;

11.5 Unions
Union is similar to structure but members share same memory.
Declaration:
union Data {
int x;
float y;
char z;
};

Differences between Structure and Union:

Aspect Structure Union


Memory Each member has own space All share same space
Size Sum of all members Size of largest member
Access Multiple members at once One member at a time
Usage Store different types together Overlay different types

Example:
#include <stdio.h>
union Data {
int a;
float b;
char c;
};
int main() {
union Data d;

printf("Size of union: %lu bytes\n", sizeof(d)); // 4

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

d.b = 3.14; // Overwrites d.a


printf("d.a = %d\n", d.a); // Garbage value
printf("d.b = %.2f\n", d.b);

return 0;

12. Dynamic Memory Allocation


12.1 Introduction
Dynamic memory allocation allows memory to be allocated at runtime.

Advantages:
Flexible memory usage
Efficient use of resources
Create arrays of unknown size

12.2 malloc()
Allocates memory and returns void pointer.

Syntax:
ptr = (datatype *)malloc(size);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n, i;

printf("Enter size: ");


scanf("%d", &n);
// Allocate memory
arr = (int *)malloc(n * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

// Use array
for (i = 0; i < n; i++) {
arr[i] = i * 10;
}

// Print
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

// Free memory
free(arr);
return 0;

12.3 calloc()
Allocates memory and initializes to zero.

Syntax:
ptr = (datatype *)calloc(count, size);
Example:
int *arr = (int *)calloc(5, sizeof(int));
// All elements initialized to 0
Comparison: malloc vs calloc
Feature malloc calloc
Initialization Uninitialized Initialized to 0
Parameters One (total size) Two (count, element size)
Speed Faster Slower
Memory Same Same

12.4 realloc()
Changes the size of previously allocated memory.
Syntax:
ptr = (datatype *)realloc(ptr, new_size);
Example:
#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr = (int *)malloc(5 * sizeof(int));

// Use array...

// Resize to 10 elements
arr = (int *)realloc(arr, 10 * sizeof(int));

free(arr);
return 0;

12.5 free()
Deallocates memory previously allocated.
Syntax:
free(ptr);
ptr = NULL; // Good practice
Important Notes:

Always free allocated memory


Free only once
Don't use pointer after freeing
Set pointer to NULL after freeing
13. File Handling
13.1 Introduction to Files
File handling allows reading from and writing to files on disk.
File Types:
Text Files – Human-readable (.txt, .c)
Binary Files – Machine-readable (.exe, .obj)

13.2 File Operations


Opening a File:
FILE *fptr = fopen("filename", "mode");
if (fptr == NULL) {
printf("Cannot open file\n");
return 1;
}
File Modes:

Mode Purpose
"r" Read (file must exist)
"w" Write (creates/overwrites)
"a" Append (add to end)
"r+" Read & Write
"w+" Create new file for read/write
"a+" Read & Append

13.3 File Functions


Character I/O:
fgetc(fptr); // Read single character
fputc(ch, fptr); // Write single character

String I/O:
fgets(str, 20, fptr); // Read line
fputs(str, fptr); // Write line
Block I/O:
fread(buffer, size, count, fptr); // Read block
fwrite(buffer, size, count, fptr); // Write block
Formatted I/O:
fscanf(fptr, "%d %s", &var, str); // Read formatted
fprintf(fptr, "%d %s\n", var, str); // Write formatted

13.4 File Positioning


fseek(fptr, offset, origin); // Seek to position
ftell(fptr); // Current position
rewind(fptr); // Go to beginning
feof(fptr); // Check end of file
Origin Constants:

SEEK_SET (0) – Beginning of file


SEEK_CUR (1) – Current position
SEEK_END (2) – End of file

13.5 File Handling Example


Write to File:
#include <stdio.h>
int main() {
FILE *fptr = fopen("[Link]", "w");

if (fptr == NULL) {
printf("Cannot create file\n");
return 1;
}

fprintf(fptr, "Hello, World!\n");


fprintf(fptr, "File Handling in C\n");

fclose(fptr);
printf("Data written successfully\n");

return 0;

}
Read from File:
#include <stdio.h>

int main() {
FILE *fptr = fopen("[Link]", "r");
char str[100];
if (fptr == NULL) {
printf("Cannot open file\n");
return 1;
}

while (fgets(str, 100, fptr) != NULL) {


printf("%s", str);
}

fclose(fptr);
return 0;

Copy File:
#include <stdio.h>
int main() {
FILE *source = fopen("[Link]", "r");
FILE *dest = fopen("[Link]", "w");
char ch;

if (source == NULL || dest == NULL) {


printf("Error opening file\n");
return 1;
}

while ((ch = fgetc(source)) != EOF) {


fputc(ch, dest);
}

fclose(source);
fclose(dest);
printf("File copied successfully\n");

return 0;

}
14. Graphics in C
14.1 Introduction to Graphics
Graphics library (like BGI – Borland Graphics Interface) provides functions to draw
graphics.
Include Header:
#include <graphics.h>
#include <conio.h>

14.2 Common Graphics Functions


Initialization:
initgraph(&gd, &gm, ""); // Initialize graphics

Drawing Functions:
putpixel(x, y, color); // Draw pixel
line(x1, y1, x2, y2); // Draw line
rectangle(x1, y1, x2, y2); // Draw rectangle
circle(x, y, radius); // Draw circle
ellipse(x, y, 0, 360, xr, yr); // Draw ellipse
Filling Functions:
floodfill(x, y, color); // Fill closed shape
bar(x1, y1, x2, y2); // Draw filled rectangle
Text Output:
outtext("Message"); // Output text
settextstyle(font, direction, size); // Set text style

Color Functions:
setcolor(color); // Set drawing color
setbkcolor(color); // Set background color
Graphics Example:
#include <stdio.h>
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

// Draw line
line(100, 100, 300, 100);

// Draw rectangle
setcolor(RED);
rectangle(150, 150, 350, 250);
// Draw circle
setcolor(BLUE);
circle(200, 200, 50);

// Fill circle
setfillstyle(SOLID_FILL, GREEN);
floodfill(200, 200, BLUE);

getch();
closegraph();
return 0;

Summary Table
Topic Key Concepts
Problem
Algorithm, Flowchart, Structured Programming
Solving
C Basics History, Features, Structure, Data Types
Arithmetic, Logical, Relational, Bitwise,
Operators
Assignment
Control Flow if-else, switch, for, while, do-while
Functions Declaration, Parameters, Return Values, Recursion
Arrays 1D, 2D, Initialization, Access
Pointers Declaration, &, *, Arithmetic, Functions
Strings Input/Output, Functions, Arrays of Strings
Structures Declaration, Members, Nested, Unions
Memory malloc, calloc, realloc, free
Files Opening, Reading, Writing, Modes, Functions
Graphics Drawing, Filling, Colors, Shapes
Important Programs to Practice
1. Find largest of three numbers (if-else, flowchart)
2. Calculator (switch, operators)
3. Factorial (loops, recursion)
4. Fibonacci series (loops, recursion)
5. Sum of array elements (arrays, loops)
6. Matrix operations (2D arrays, nested loops)
7. String manipulation (string functions, pointers)
8. File copy (file handling)
9. Structure with array (structures, loops)
10. Dynamic memory allocation (malloc, free)

Quick Reference: Common Mistakes to Avoid


1. Forgetting return statement in functions
2. Array index out of bounds
3. Not initializing variables
4. Confusing = (assignment) with == (comparison)
5. Forgetting \n in printf for newline
6. Not freeing allocated memory
7. Comparing strings with == (use strcmp)
8. Off-by-one errors in loops
9. Not checking for NULL after file operations
10. Returning address of local variable from function

Last Updated: December 2025


For: MCA 1st Year | Problem Solving Using C (BMC102/KCA102)
Institute: Kamla Nehru Institute of Technology, Sultanpur

Common questions

Powered by AI

In C, 'for' loops control execution through initialization, condition checking, and increment within the loop structure, making them suitable for known iterations . 'While' loops check the condition before executing the loop body, thus may not execute at all if the condition is false initially, which is ideal for scenarios with an unknown number of iterations . 'Do-while' loops, however, execute the loop body at least once before checking the condition, ensuring the loop runs at least a single time, often used for menus or input validations to guarantee the user has made at least one entry attempt .

In C, text files are human-readable and typically contain characters; operations like reading and writing use functions such as fgets and fputs. Conversely, binary files are machine-readable and handle data in a binary format where fread and fwrite are commonly used for block I/O operations. Text files interpret new line characters whereas binary files do not, maintaining data in its original shape as specified by data type sizes, which makes them faster and more efficient for transferring large data .

Storage classes in C define the scope, visibility, and lifetime of variables. 'Auto' variables, the default for all local variables, reside in stack memory with a local scope and limited lifespan tied to a function call. 'Register' class suggests storing variables in CPU registers for faster access, though the actual implementation is compiler-dependent. 'Static' variables preserve their value across multiple function calls and can exist globally or locally within a program. Lastly, 'extern' is employed for global variables allowing them to be accessed across multiple files or functions throughout the program's duration .

Logical operators in C, such as AND (&&), OR (||), and NOT (!), are crucial for decision-making by allowing the evaluation of multiple conditions. The AND operator checks if both conditions are true, the OR operator verifies if at least one condition is true, and NOT inverses the truth value of a condition. These operators are often used in control flow statements like if-else and loops to determine the logical path a program will take, enabling more nuanced and complex decision-making processes .

Nested loops are often utilized in scenarios involving multi-dimensional data processing, such as matrix operations, where each cell or element requires iteration over rows and columns. They are also essential in implementing algorithms where cascading sequences are involved, such as generating multiplication tables or conducting complex graphical rendering tasks where multiple coordinate systems are in play .

Functions enhance code maintainability and debugging by promoting modularity and reusability. They encapsulate specific tasks within defined boundaries, allowing programmers to break down complex algorithms into more manageable parts. This structured approach simplifies understanding and updating code without affecting other components of the program. Additionally, debugging becomes more straightforward as issues can often be isolated to specific functions, reducing the scope of error searching .

Dynamic memory allocation in C allows for flexible memory usage and efficient use of resources at runtime. It enables the creation of arrays of an unknown size during the compile time, which can be advantageous when dealing with variable data sizes. Additionally, this approach allows programs to allocate more or less memory as needed and can help in optimizing resource usage .

A 'switch' statement is preferable over 'if-else' in scenarios where a single variable needs to be compared against several constant values due to its readability and potential performance benefits. 'Switch' statements are limited to equality checks, making them efficient for large, straightforward conditional branches and reducing the complexity of code when managing multiple discrete cases. In contrast, 'if-else' provides greater flexibility with relational/logical expressions but can be less readable with numerous conditions .

Structures and unions handle memory differently in C. A structure allocates separate memory for each of its members, enabling the storage of varied data types together without overlapping. This can lead to larger size requirements depending on the sum of all members' data sizes . Meanwhile, a union uses shared memory space for all its members corresponding to the size of the largest member, which allows only one member to have a valid value at any given time. This facilitates an efficient overlay of different types but restricts simultaneous access to multiple members .

Function prototypes in C serve as forward declarations of functions, specifying their name, return type, and parameters before actual implementation. This practice allows the programmer to inform the compiler about the function existence ahead of its use, thereby avoiding errors related to implicit declarations. Prototypes ensure type compatibility between function declarations and calls, facilitating modular programming by organizing code into declarations and definitions, which improves the setup of collaborative projects and streamlines the development process .

You might also like