Idea of Algorithm - Steps To Solve Logical and Numerical Problems Algorithm
Idea of Algorithm - Steps To Solve Logical and Numerical Problems Algorithm
Example:
Ensure that your algorithm does not run infinitely and gives the
result in finite time.
✅ Example:
1. Read A, B, C
2. If A > B and A > C → A is largest
3. Else if B > A and B > C → B is largest
4. Else → C is largest
5. Print result
🔍 Flowchart Representation
✅ 2. Process Symbol
✅ 3. Input/Output Symbol
✅ 4. Decision Symbol
A diamond shape is used for decision-making (if/else).
✅ 5. Flow Lines
✅ Example Flowchart:
Start
Input A, B
Sum = A + B
Output Sum
End
🔍 Pseudocode Representation
Pseudocode is plain English-like instructions that describe the
steps without worrying about syntax of a programming
language.
✅ 2. No Syntax Rules
✅ 3. Use Indentation
✅ Example Pseudocode:
Problem: Find the sum of first N numbers
Start
Input N
Sum ← 0
FOR i ← 1 TO N
Sum ← Sum + i
END FOR
Output Sum
End
Property Description
Reserved You can’t use them as variable names
Predefined Meaning Each has a fixed function in code
Case-sensitive Yes, in C (e.g., int ≠ Int)
Total Count 32 (in ANSI C)
datatype variable_name;
int age=20;
float price;
char grade;
🧾 Types of Variables in C:
Type Description
Declared inside a function/block; accessible
Local
only within that scope
Declared outside all functions; accessible
Global
throughout the program
Static Retains value between function calls
Automatic
Default for local variables
(auto)
External
Declared in another file or scope
(extern)
Stored in CPU register for fast access (compiler
Register
may ignore)
✨ Definition:
In C programming, a data type defines the type of data a
variable can store. It tells the compiler what kind of value (such
as integer, float, character, etc.) the variable will hold and how
much memory to allocate.
➤ a) int (Integer):
c
CopyEdit
int age = 21;
➤ b) float:
c
CopyEdit
float temperature = 36.5;
➤ c) char:
c
CopyEdit
char grade = 'A';
Memory: 1 byte
Stores ASCII value behind the character
➤ d) double:
c
CopyEdit
double pi = 3.14159265359;
Memory: 8 bytes
Higher precision than float
Examples:
c
CopyEdit
unsigned int count = 10;
long int population = 1000000;
➤ a) Arrays:
c
CopyEdit
int marks[5] = {90, 80, 70, 60, 50};
Useful for storing list of items, e.g., scores, names
Index starts from 0
➤ b) Pointers:
c
CopyEdit
int x = 10;
int *ptr = &x;
➤ c) Functions:
c
CopyEdit
char name[] = "Nitin";
➤ a) struct (Structure):
➤ b) union:
c
CopyEdit
union data {
int i;
float f;
};
➤ c) enum (Enumeration):
➤ d) typedef:
c
CopyEdit
typedef int marks;
marks m1 = 90;
📚 Type Conversions in C
✨ Definition:
cpp
CopyEdit
char → int → float → double
💡 Example:
int a = 10;
float b = 5.5;
float result = a + b; // a is converted to float automatically
🖊️Syntax:
(data_type) expression;
💡 Example:
float result;
int a = 7, b = 2;
📘 Header Files in C
✨ Definition:
📌 Syntax:
✅ Examples:
✅ Example:
#include "myfunctions.h"
void greet() {
printf("Hello, Nitin!\n");
}
📘 Compilation in C Programming
✨ What is Compilation?
2️⃣ Compilation
3️⃣ Assembly
4️⃣ Linking
📌 Key Points:
📂 Example:
You write:
#include <stdio.h>
int main() {
printf("Hello");
return 0;
}
After compilation:
You get an object file, like main.o — it contains binary code for
the part you wrote, but not for printf().
📌 Key Points:
🔹 1. Syntax Errors
int main() {
printf("Hello World") // Missing semicolon → Syntax error
return 0
}
❌ Common Causes:
Missing semicolon ;
Unmatched brackets {}, ()
Misspelled keywords (pritnf instead of printf)
Incorrect use of data types
🔹 2. Logical Errors
🧾 Example:
int a = 5, b = 10;
printf("Sum = %d", a - b); // Logical error: should be a + b
🔹 3. Runtime Errors
These happen while the program is running, often due to
illegal operations (like division by zero or invalid memory
access).
🧾 Example:
int a = 10, b = 0;
printf("%d", a / b); // Runtime Error: Division by zero
🔹 4. Linker Errors
🧾 Example:
🔹 Definition:
An arithmetic expression in C is a combination of variables,
constants, and operators that results in a numerical value.
These expressions are used to perform basic mathematical
operations such as addition, subtraction, multiplication,
division, and modulus.
c
CopyEdit
int a = 10, b = 5, c = 2;
int result = a + b * c; // result = 10 + (5 * 2) = 20
Precedence and Associativity of Operators
🔹 What is Precedence?
🔹 What is Associativity?
int result = 10 + 20 * 2;
// According to precedence: 20 * 2 = 40, then 10 + 40 = 50
c
int result = (10 + 20) * 2;
// Parentheses change the order: 30 * 2 = 60
🌟 What is a Preprocessor?
1. #define
#define PI 3.14159
#define SQUARE(x) ((x)*(x))
2. #include
Undefines a macro.
#undef PI
#define DEBUG
#ifdef DEBUG
printf("Debugging is ON\n");
#endif
Before compiling:
It replaces macros.
It includes files.
It removes comments.
It conditionally compiles code based on defined macros.
#include <stdio.h>
#define PI 3.14
#define AREA(r) (PI * r * r)
int main() {
float area = AREA(5);
printf("Area is: %f\n", area);
return 0;
}
#include <stdio.h>
int main() {
float area = (3.14 * 5 * 5);
printf("Area is: %f\n", area);
return 0;
}
📌 In simple words:
“If something is true, do this. Otherwise, do something else.”
1. if Statement
✅ Syntax:
c
CopyEdit
if (condition) {
// code to execute if condition is true
}
✅ Example:
c
CopyEdit
int age = 20;
if (age >= 18) {
printf("You are eligible to vote.\n");
}
2. if-else Statement
✅ Syntax:
c
CopyEdit
if (condition) {
// executes if condition is true
} else {
// executes if condition is false
}
✅ Example:
c
int age = 15;
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are NOT eligible to vote.\n");
}
✅ Syntax:
if (condition1) {
// code
} else if (condition2) {
// code
} else {
// code
}
✅ Example:
int marks = 75;
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else {
printf("Grade: C\n");
}
4. Nested if Statement
✅ Example:
int age = 25;
int hasID = 1;
5. switch Statement
✅ Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
✅ Example:
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
default: printf("Invalid day\n");
}
🧠 Key Points
📌 In simple words:
1. goto Statement
2. break Statement
3. continue Statement
4. return Statement
🔸 2. break Statement
✅ Example:
c
CopyEdit
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
printf("%d ", i);
}
// Output: 1 2
It jumps out of the loop when i == 3.
🔸 3. continue Statement
Skips the current iteration of a loop and jumps to the next one.
✅ Example:
c
CopyEdit
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
printf("%d ", i);
}
// Output: 1 2 4 5
🔸 4. return Statement
✅ Example:
c
CopyEdit
#include <stdio.h>
int sum(int a, int b) {
return a + b;
}
int main() {
int result = sum(5, 10);
printf("Sum = %d\n", result);
return 0;
}
Conditional Unconditional
Feature
Statement Statement
Based on a
Yes (if, switch) No
test
Controls flow Based on logic Direct jump
Use Case Decisions Loops exit, function exit
🌟 What is an Array?
📌 In simple words:
c
CopyEdit
data_type array_name[size];
✅ Example:
c
CopyEdit
int numbers[5]; // stores 5 integers
✅ Initialization:
c
CopyEdit
int numbers[5] = {10, 20, 30, 40, 50};
🔁 Accessing Elements:
c
CopyEdit
printf("%d", numbers[2]); // Output: 30 (index starts at 0)
c
CopyEdit
for(int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
🔸 Memory Representation of 1-D Array
Let’s say:
c
CopyEdit
int a[3] = {5, 10, 15};
Index Value
0 5
1 10
2 15
✅ Declaration:
c
CopyEdit
data_type array_name[row][column];
✅ Example:
c
CopyEdit
int matrix[2][3]; // 2 rows, 3 columns
✅ Initialization:
c
CopyEdit
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
c
CopyEdit
printf("%d", matrix[1][2]); // Output: 6
c
CopyEdit
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
c
CopyEdit
int a[2][2] = {
{1, 2},
{3, 4}
};
Operation Description
Traversal Access each element using a loop
Insertion Add value at specific index
Deletion Remove value (by shifting elements)
Search Find element by value or index
Update Change element’s value at a specific index
🔍 Real-Life Examples
c
CopyEdit
int timetable[7][5]; // 7 days, 5 lectures
✍️Summary Table
Let’s say:
c
CopyEdit
int a[5] = {10, 20, 30, 40, 50};
✅ Example:
Assume:
🧠 Output:
a[0] → 1000
a[1] → 1004
a[2] → 1008
a[3] → 1012
a[4] → 1016
✅ Declaration:
c
CopyEdit
int b[3][4]; // 3 rows and 4 columns
txt
CopyEdit
LOC(b[i][j]) = Base_Address + [i × Number_of_Columns + j] ×
Size_of_Data_Type
✅ Example:
Let:
txt
CopyEdit
LOC(b[2][1]) = 2000 + [(2 × 4) + 1] × 4
= 2000 + [8 + 1] × 4
= 2000 + 9 × 4
= 2000 + 36
= 2036
txt
CopyEdit
LOC(b[i][j]) = Base_Address + [j × Number_of_Rows + i] × Size
📌 Summary Table
c
CopyEdit
char name[6] = {'N', 'i', 't', 'i', 'n', '\0'};
The last character '\0' is null character, used to indicate the end
of the string.
🌟 What is a String in C?
c
CopyEdit
char name[] = "Nitin";
arduino
CopyEdit
'N' 'i' 't' 'i' 'n' '\0'
c
CopyEdit
char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
✅ Method 2: String Literal (Preferred)
c
CopyEdit
char name[] = "Hello";
c
CopyEdit
char str[20];
scanf("%s", str);
c
CopyEdit
char str[50];
gets(str); // Not recommended in modern C
c
CopyEdit
fgets(str, sizeof(str), stdin);
📤 Printing Strings
✅ Using printf():
c
CopyEdit
printf("%s", str);
c
CopyEdit
char str[] = "Hi";
Index Value
0 'H'
1 'i'
2 '\0'
📘 Real-life Example
c
CopyEdit
#include <stdio.h>
#include <string.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}
📌 Summary Table
Feature Character Array String
Data Type char char + '\0'
scanf, gets,
Input Same
fgets
Ends With Any character Always ends with '\0'
Use with Fully supported (strlen,
Limited
Functions etc.)
🔶 Q: What happens if malloc(), calloc(), or realloc() fails to
allocate memory? How can you handle such situations?
In C programming, dynamic memory allocation allows a program to request memory from the heap at
runtime using functions like:
c
CopyEdit
#include <stdlib.h>
When malloc(), calloc(), or realloc() fails to allocate memory (usually due to insufficient
memory available in the heap), they return a NULL pointer.
🔸 Syntax Example:
c
CopyEdit
int *ptr;
ptr = (int*) malloc(100 * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!\n");
// Handle error
}
🔸 Similar for calloc():
c
CopyEdit
ptr = (int*) calloc(100, sizeof(int));
🔸 And realloc():
c
CopyEdit
int *new_ptr = realloc(ptr, 200 * sizeof(int));
if (new_ptr == NULL) {
// realloc failed
}
c
CopyEdit
int *ptr = (int*) malloc(50 * sizeof(int));
if (ptr == NULL) {
printf("Allocation failed. Exiting safely...\n");
exit(1); // Or return an error
}
✅ 2. Use exit() or Return Gracefully
If memory fails, do not continue using the pointer. Exit or return from the function safely.
c
CopyEdit
free(ptr);
✅ 4. Use realloc() with Temporary Pointer
Never assign realloc() result directly to the original pointer—use a temporary pointer.
c
CopyEdit
int *temp = realloc(ptr, new_size);
if (temp != NULL) {
ptr = temp;
} else {
// Handle reallocation failure
}
✅ 5. Log or Notify the User
int main() {
int *arr = (int*) malloc(1000000000 * sizeof(int)); // Large allocation
if (arr == NULL) {
printf("Error: Memory allocation failed!\n");
return 1; // Exit safely
}
// Free memory
free(arr);
return 0;
}
✅ Conclusion
Handling such scenarios carefully is crucial in system-level and embedded programming, where memory
is limited and program stability is critical.