Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Friday, October 3, 2025

Unit 1: Basics, Algorithm & Operators ( Programming in C Language)


1️⃣ Explain Algorithm with Example and Properties.

Definition:
Algorithm is a step-by-step procedure to solve a problem in a finite number of steps.

Example: Add two numbers

  1. Start

  2. Read two numbers, A and B

  3. Calculate Sum = A + B

  4. Print Sum

  5. Stop

Properties of a good algorithm:

  • Input: Accepts zero or more inputs

  • Output: Produces at least one output

  • Definiteness: Steps are clear and unambiguous

  • Finiteness: Algorithm must terminate after finite steps

  • Effectiveness: Steps are basic, feasible, and solvable manually or by machine


2️⃣ Draw Flowchart and Explain Sum of First 10 Numbers

Flowchart:

┌───────┐ │ Start │ └───┬───┘ ↓ i=1, sum=0 ↓ ┌── i ≤ 10 ? ──┐ │ Yes No│ ↓ ↓ sum=sum+i Print sum i=i+1 ↓ │ ┌───────┐ └─────────► Stop │ └─────┘

Explanation:

  • Initialize i=1 and sum=0.

  • Check condition i ≤ 10.

  • Add i to sum and increment i.

  • Repeat until i > 10.

  • Print final sum and stop.


3️⃣ Explain Compilation & Execution Process in C

Steps:

  1. Editing: Write source code in .c file.

  2. Preprocessing: Removes comments, expands macros, includes header files.

  3. Compilation: Converts source code to assembly code.

  4. Assembly: Converts assembly code into object code (.o file).

  5. Linking: Combines object code with libraries to produce executable.

  6. Execution: OS loads and runs the executable file.

Example:

#include <stdio.h> int main() { printf("Hello, World!"); return 0; }

4️⃣ Explain Keywords, Identifiers, and Constants in C

Keywords: Reserved words in C with predefined meaning.
Example: int, float, if, else, return

Identifiers: User-defined names for variables, functions, arrays, etc.
Example: sum, age, myFunction

Constants: Fixed values that do not change.
Example: #define PI 3.14 or const int x = 5;

Difference between Keywords and Identifiers:

KeywordsIdentifiers
Reserved by CUser-defined names
Cannot be used as variable namesCan be used as variable or function names
Example: int, floatExample: sum, age

5️⃣ Explain Operators in C with Examples

Types of operators:

  1. Arithmetic: + - * / %

  2. Unary: ++ --

  3. Relational/Logical: > < == != && || !

  4. Bitwise: & | ^ << >>

  5. Assignment: = += -= *= /= %=

  6. Conditional: ?:

Examples:

int a=5, b=3; int c; c = a + b; // 8 c = a & b; // 1 (bitwise AND) c = a << 1; // 10 (left shift)

Precedence & Associativity:

  • Precedence decides which operator evaluated first

  • Associativity decides order for operators with same precedence

Example:

10 + 20 * 5 // 110, '*' has higher precedence 100 / 10 * 5 // 50, '/' and '*' have same precedence, left-to-right

Unit 2: Control Structures, Functions, Arrays

6️⃣ Explain Control Structures in C with Examples

Definition: Control structures manage the flow of execution in a program.

Types:

  1. Sequential: Statements executed line by line.

  2. Decision Making (Selection): if, if-else, switch-case

  3. Loops (Iteration): for, while, do-while

  4. Jump Statements: break, continue, goto

Examples:

For Loop (Factorial):

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

While Loop (Even Numbers):

int i=2; while(i<=10){ printf("%d ",i); i+=2; }

Switch-Case:

int day=3; switch(day){ case 1: printf("Mon"); break; case 2: printf("Tue"); break; default: printf("Other"); }

7️⃣ Explain Functions in C with Types and Examples

Definition: Block of code that performs a specific task and can be reused.

Advantages: Code reusability, easy debugging, modularity

Types:

  • Library functions: printf(), scanf()

  • User-defined functions

Categories based on arguments & return type:

  1. No arguments, no return:

void hello(){ printf("Hi"); }
  1. Arguments, no return:

void sum(int a,int b){ printf("%d",a+b); }
  1. No arguments, return value:

int getNum(){ return 10; }
  1. Arguments & return:

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

Call by value vs Call by reference:

  • Call by value → function gets a copy, original variable not changed

  • Call by reference → function gets address, original variable can be changed


8️⃣ Explain Arrays in C with Examples

Definition: Array = collection of elements of same type in contiguous memory.

Types:

  • 1D Array: int arr[5]={1,2,3,4,5};

  • 2D Array: int mat[2][2]={{1,2},{3,4}};

  • Multidimensional Array

Example Programs:

Sum of 1D Array:

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

Matrix Addition (2D Array):

int a[2][2], b[2][2], sum[2][2], i,j; for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&a[i][j]); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&b[i][j]); for(i=0;i<2;i++) for(j=0;j<2;j++) sum[i][j]=a[i][j]+b[i][j]; for(i=0;i<2;i++){ for(j=0;j<2;j++) printf("%d ",sum[i][j]); printf("\n"); }

9️⃣ Program Based Long Questions

  1. Factorial using recursion:

int fact(int n){ if(n<=1) return 1; else return n*fact(n-1);}
  1. Sum of first 10 numbers using loop & function:

int sum10(){ int i, sum=0; for(i=1;i<=10;i++) sum+=i; return sum; }
  1. Matrix addition program → See 2D array example above.

  2. Demonstrate Bitwise Operators:

int a=5,b=3; printf("%d %d %d %d %d", a&b, a|b, a^b, a<<1, a>>1);

Unit 1 (Programming in C with Data Structures) – Short Notes (6 Marks Type)

 Q1. Define Algorithm and its properties.

Answer:
An algorithm is a step-by-step finite process to solve a specific problem.

Properties:

  1. Definiteness → Steps must be clear.

  2. Finiteness → Algorithm must end after finite steps.

  3. Input → Zero or more inputs accepted.

  4. Output → At least one output produced.

  5. Effectiveness → Steps must be simple and feasible.


Q2. What is a Flowchart? List its advantages.

Answer:
A flowchart is a graphical representation of an algorithm using symbols like oval (Start/End), rectangle (Process), diamond (Decision), parallelogram (I/O).

Advantages:

  • Easy to understand.

  • Helps in debugging before coding.

  • Improves communication between developers.


Q3. Explain the structure of a C program.

Answer:
Basic structure:

  1. Preprocessor directives (#include <stdio.h>)

  2. Main function (int main() { ... })

  3. Declarations (variables)

  4. Statements (logic/code)

  5. Return statement (return 0;)


Q4. Explain Compilation & Execution of a C program.

Answer:
Steps:

  1. Writing → Save program as .c file.

  2. CompilationCompiler converts C code → machine code.

  3. LinkingConnects with libraries.

  4. Execution → Run the program → output is shown.


Q5. What are Data Types in C?

Answer:
Data types define the kind of data stored in variables.


Q6. What are Identifiers and Keywords in C?

Answer:

  • Identifiers: Names given to variables, functions, etc. (e.g., marks, sum).

  • Keywords: Reserved words with special meaning, cannot be used as identifiers (e.g., int, while, return).

Friday, July 4, 2025

✅ Day 5 Solution - DSA with C

 

✅ 1. Implement your own strlen()


#include <stdio.h> int my_strlen(char str[]) { int i = 0; while (str[i] != '\0') { i++; } return i; } int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); printf("Length of string = %d\n", my_strlen(str)); return 0; }

✅ 2. Implement your own strcpy()


#include <stdio.h> void my_strcpy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; // Null-terminate } int main() { char src[100], dest[100]; printf("Enter a string to copy: "); scanf("%s", src); my_strcpy(dest, src); printf("Copied string: %s\n", dest); return 0; }

✅ 3. Implement your own strcmp()


#include <stdio.h> int my_strcmp(char str1[], char str2[]) { int i = 0; while (str1[i] != '\0' && str2[i] != '\0') { if (str1[i] != str2[i]) return str1[i] - str2[i]; i++; } return str1[i] - str2[i]; // Also handles different lengths } int main() { char str1[100], str2[100]; printf("Enter two strings:\n"); scanf("%s %s", str1, str2); int result = my_strcmp(str1, str2); if (result == 0) printf("Strings are equal.\n"); else if (result < 0) printf("First string is smaller.\n"); else printf("First string is greater.\n"); return 0; }

✅ 4. LeetCode Problem: Valid Anagram

Two strings are anagrams if they contain the same characters in any order.

✨ Custom C Solution:


#include <stdio.h> #include <string.h> int isAnagram(char s[], char t[]) { int count[26] = {0}; if (strlen(s) != strlen(t)) return 0; for (int i = 0; s[i] != '\0'; i++) { count[s[i] - 'a']++; count[t[i] - 'a']--; } for (int i = 0; i < 26; i++) { if (count[i] != 0) return 0; } return 1; } int main() { char s[100], t[100]; printf("Enter first string: "); scanf("%s", s); printf("Enter second string: "); scanf("%s", t); if (isAnagram(s, t)) printf("Valid Anagram\n"); else printf("Not an Anagram\n"); return 0; }

✅ This C code solves the Valid Anagram LeetCode problem without using libraries like sort.

๐Ÿš€ DSA with C – Day 5: Strings in C


๐ŸŽฏ Goal:


๐Ÿง  What is a String in C?

A string is a character array ending with a null character (\0).

๐Ÿ”ง Declaration


char str[100]; // Character array

๐Ÿ“ฅ Input


scanf("%s", str); // No spaces fgets(str, sizeof(str), stdin); // With spaces

๐Ÿ‘จ‍๐Ÿ’ป 1. Reverse a String


#include <stdio.h> #include <string.h> int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); // Use fgets if you want spaces int len = strlen(str); for (int i = 0; i < len / 2; i++) { char temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; } printf("Reversed string: %s\n", str); return 0; }

๐Ÿ‘จ‍๐Ÿ’ป 2. Check if a String is a Palindrome


#include <stdio.h> #include <string.h> int main() { char str[100]; int flag = 1; printf("Enter a string: "); scanf("%s", str); int len = strlen(str); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - i - 1]) { flag = 0; break; } } if (flag) printf("Palindrome\n"); else printf("Not a palindrome\n"); return 0; }

๐Ÿ‘จ‍๐Ÿ’ป 3. Character Frequency Count


#include <stdio.h> #include <string.h> int main() { char str[100]; int freq[256] = {0}; // ASCII chars printf("Enter a string: "); scanf("%s", str); for (int i = 0; str[i] != '\0'; i++) { freq[(int)str[i]]++; } printf("Character frequencies:\n"); for (int i = 0; i < 256; i++) { if (freq[i] > 0) printf("%c: %d\n", i, freq[i]); } return 0; }

๐Ÿ‘จ‍๐Ÿ’ป 4. Check if Two Strings Are Anagrams

Two strings are anagrams if they contain the same characters in any order.


#include <stdio.h> #include <string.h> int isAnagram(char str1[], char str2[]) { int count[256] = {0}; if (strlen(str1) != strlen(str2)) return 0; for (int i = 0; str1[i]; i++) { count[(int)str1[i]]++; count[(int)str2[i]]--; } for (int i = 0; i < 256; i++) { if (count[i] != 0) return 0; } return 1; } int main() { char str1[100], str2[100]; printf("Enter two strings: "); scanf("%s %s", str1, str2); if (isAnagram(str1, str2)) printf("Anagram\n"); else printf("Not anagram\n"); return 0; }

๐Ÿงช Practice Problems:

  1. Count vowels and consonants in a string.

  2. Convert lowercase letters to uppercase.

  3. Remove duplicate characters from a string.

  4. Check if two strings are rotations of each other (e.g., abc and cab).


๐Ÿ“˜ Homework for Day 5:

  • Implement your own versions of:

    • strlen()

    • strcpy()

    • strcmp()

  • Try a string problem from LeetCode: Valid Anagram

✅ Day 4 solution - DSA with C

 Find the GCD of Two Numbers Using Recursion

GCD (Greatest Common Divisor) using Euclidean Algorithm:


#include <stdio.h> int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int num1, num2; printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); printf("GCD of %d and %d is %d\n", num1, num2, gcd(num1, num2)); return 0; }

✅ 2. Recursive Function to Calculate Power (xโฟ)


#include <stdio.h> int power(int x, int n) { if (n == 0) return 1; return x * power(x, n - 1); } int main() { int base, exponent; printf("Enter base and exponent: "); scanf("%d %d", &base, &exponent); printf("%d^%d = %d\n", base, exponent, power(base, exponent)); return 0; }

✅ 3. Reverse an Array Using Recursion


#include <stdio.h> void reverse(int arr[], int start, int end) { if (start >= end) return; // Swap int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; reverse(arr, start + 1, end - 1); } int main() { int arr[100], n; printf("Enter number of elements: "); scanf("%d", &n); printf("Enter %d elements:\n", n); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); reverse(arr, 0, n - 1); printf("Reversed array:\n"); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0; }

Tuesday, July 1, 2025

๐Ÿš€ DSA with C – Day 4: Recursion + Factorial + Fibonacci + Array Sum

 

๐ŸŽฏ Goal:

  • Understand the concept of Recursion

  • Write recursive functions for:

    • Factorial

    • Fibonacci series

    • Sum of array elements

  • Compare recursion with iteration


๐Ÿง  What is Recursion?

A function calling itself to solve a smaller version of the same problem.

๐Ÿ”„ Recursion Structure:

return_type function_name(parameters) {
if (base_condition) return result; else return function_name(smaller_problem); }

๐Ÿ‘จ‍๐Ÿ’ป 1. Factorial Using Recursion

#include <stdio.h>
int factorial(int n) { if (n == 0 || n == 1) return 1; else return n * factorial(n - 1); } int main() { int num; printf("Enter a number: "); scanf("%d", &num); printf("Factorial of %d is %d\n", num, factorial(num)); return 0; }

๐Ÿ‘จ‍๐Ÿ’ป 2. Fibonacci Series Using Recursion


#include <stdio.h> int fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } int main() { int terms; printf("Enter number of terms: "); scanf("%d", &terms); printf("Fibonacci Series: "); for (int i = 0; i < terms; i++) { printf("%d ", fibonacci(i)); } return 0; }

⚠️ Note: Recursive Fibonacci is inefficient for large n – we’ll optimize it later with memoization or iteration.


๐Ÿ‘จ‍๐Ÿ’ป 3. Sum of Array Using Recursion


#include <stdio.h> int sumArray(int arr[], int n) { if (n == 0) return 0; return arr[n - 1] + sumArray(arr, n - 1); } int main() { int arr[100], n; printf("Enter number of elements: "); scanf("%d", &n); printf("Enter %d elements:\n", n); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); printf("Sum of array = %d\n", sumArray(arr, n)); return 0; }

๐Ÿงช Practice Problems:

  1. Find the GCD of two numbers using recursion.

  2. Write a recursive function to calculate the power (xโฟ).

  3. Reverse an array using recursion.


๐Ÿ“˜ Homework for Day 4:

  • Compare iteration vs recursion by writing factorial using loops.

  • Try writing Fibonacci with memoization or using a loop.

  • LeetCode problem suggestion: Climbing Stairs – this is basically Fibonacci!


๐Ÿ“… Day 4 Summary:

  • ✅ Understood recursion

  • ✅ Implemented factorial, Fibonacci, and sum via recursion

  • ✅ Practiced recursive thinking




Saturday, June 28, 2025

๐Ÿš€ DSA with C – Day 3: Bubble Sort & Binary Search

 

๐ŸŽฏ Goal:

  • Learn Bubble Sort and sort arrays.

  • Understand how Binary Search works.

  • Compare Linear vs Binary Search.

  • Practice problems on sorted arrays.


๐Ÿง  Theory

✅ Bubble Sort:

  • Repeatedly compares adjacent elements and swaps them if they’re in the wrong order.

  • Worst-case time complexity: O(n²)

  • Best-case (already sorted): O(n) with optimization


๐Ÿ‘จ‍๐Ÿ’ป Bubble Sort in C


#include <stdio.h> int main() { int arr[100], n, i, j, temp; printf("Enter number of elements: "); scanf("%d", &n); printf("Enter %d elements:\n", n); for (i = 0; i < n; i++) scanf("%d", &arr[i]); // Bubble Sort for (i = 0; i < n - 1; i++) { int swapped = 0; for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = 1; } } if (swapped == 0) break; // Already sorted } printf("Sorted array:\n"); for (i = 0; i < n; i++) printf("%d ", arr[i]); return 0; }

✅ Binary Search:

  • Efficient searching technique on sorted arrays.

  • Time Complexity: O(log n)

  • Repeatedly divide the array and compare with middle element.


๐Ÿ‘จ‍๐Ÿ’ป Binary Search in C


#include <stdio.h> int binarySearch(int arr[], int n, int key) { int low = 0, high = n - 1, mid; while (low <= high) { mid = (low + high) / 2; if (arr[mid] == key) return mid; else if (arr[mid] < key) low = mid + 1; else high = mid - 1; } return -1; // Not found } int main() { int arr[100], n, key; printf("Enter number of elements: "); scanf("%d", &n); printf("Enter %d sorted elements:\n", n); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); printf("Enter element to search: "); scanf("%d", &key); int result = binarySearch(arr, n, key); if (result == -1) printf("Element not found.\n"); else printf("Element found at index %d.\n", result); return 0; }

๐Ÿ” Linear vs Binary Search

FeatureLinear SearchBinary Search
Time ComplexityO(n)O(log n)
Sorted Array Required❌ No✅ Yes
SpeedSlowerFaster for large data
ApproachScan all elementsDivide & Conquer

๐Ÿงช Practice Problems:

  1. Sort an array using Bubble Sort in descending order.

  2. Count how many swaps were done during Bubble Sort.

  3. Use Binary Search to find the number of occurrences of a given element.

  4. If not found in Binary Search, return where it should be inserted.


๐Ÿ“˜ Homework for Day 3:

  • Implement recursive Binary Search.

  • Write a program that first sorts using Bubble Sort and then searches using Binary Search.

  • LeetCode problem suggestion: Search Insert Position


๐Ÿ“… Day 3 Summary

  • ✅ Learned Bubble Sort (with optimization)

  • ✅ Implemented Binary Search (iterative)

  • ✅ Practiced comparing search algorithms

✅ UNIT 4 — POSET, LATTICES & BOOLEAN ALGEBRA (DISCRETE MATHEMATICS)

  ✅ UNIT 4 — POSET, LATTICES & BOOLEAN ALGEBRA 1. Poset Partially Ordered Set A pair (A, ≤) where relation is: Reflexive Anti-...