🚨 EXAM QUESTION LEAK 🚨

πŸ“… 18 MAY 2026 β€” EXAM DATE

Programming with C

// Complete Study Guide β€” All Questions Answered //

⚑ 18 MAY 2026 β€” PROGRAMMING WITH C β€” QUESTION LEAK ⚑
πŸ’€ Leaked By: Hacker Vishw Pratap, Hacker Ankush & Hariom Mishra πŸ’€
All answers are detailed and exam-ready. Click any question to expand.
Q.1

Discuss about "C" Programming and write the structure of C Program

β–Ό

What is C?

C is a general-purpose, structured, middle-level programming language developed by Dennis Ritchie at Bell Laboratories in 1972. It was developed to write the UNIX operating system.

Key Features of C:
  • Simple and efficient β€” close to machine language
  • Structured programming β€” uses functions
  • Portable β€” code runs on different machines
  • Rich library of built-in functions
  • Supports pointers, arrays, structures
  • Fast execution speed
  • Extensible β€” can add your own functions

Structure of a C Program

/* ===== STRUCTURE OF A C PROGRAM ===== */

/* 1. Documentation Section */
// Author: Your Name, Date: 18-May-2026

/* 2. Preprocessor / Link Section */
#include <stdio.h>   // Standard Input/Output
#include <stdlib.h>  // Standard Library
#include <math.h>    // Math functions

/* 3. Definition Section (Macros / Constants) */
#define PI 3.14159
#define MAX 100

/* 4. Global Declaration Section */
int globalVar = 10;   // Accessible everywhere

/* 5. Function Prototype Section */
void greet();
int add(int a, int b);

/* 6. Main Function β€” Entry Point */
int main() {
    /* 6a. Local Variable Declaration */
    int x = 5, y = 10;
    int result;

    /* 6b. Executable Statements */
    result = add(x, y);
    printf("Sum = %d\n", result);
    greet();

    return 0;  // Return to OS
}

/* 7. User-Defined Functions */
void greet() {
    printf("Hello, C Programming!\n");
}

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

Sections Explained

SectionPurpose
DocumentationComments about program β€” author, date, description
Link / Preprocessor#include files to add library functions
Definition#define macros and constants
Global DeclarationVariables accessible throughout the program
main()Starting point of execution
User-defined FunctionsCustom functions for specific tasks
Q.2

Define an Algorithm

β–Ό

Definition

An algorithm is a finite set of well-defined, ordered instructions (steps) to solve a specific problem or perform a computation. It takes input, processes it, and gives an output.

Characteristics of a Good Algorithm:
  • Input: Has zero or more inputs
  • Output: Produces at least one output
  • Definiteness: Each step is clear and unambiguous
  • Finiteness: Must terminate after a finite number of steps
  • Effectiveness: Each step must be basic and executable

Example β€” Algorithm to Find Sum of Two Numbers

Step 1: Start
Step 2: Read two numbers A and B
Step 3: Compute SUM = A + B
Step 4: Print SUM
Step 5: Stop

Example β€” Algorithm to Find Largest of Two Numbers

Step 1: Start
Step 2: Read A, B
Step 3: If A > B, print "A is largest", else print "B is largest"
Step 4: Stop

Importance of Algorithms

  • Helps in planning before writing code
  • Makes program logic clear and correct
  • Helps in analyzing time and space complexity
  • Reusable and language-independent
Q.3

List and explain the different data types in C

β–Ό

What is a Data Type?

A data type defines the type of data a variable can hold, how much memory it occupies, and what operations can be performed on it.

Classification of Data Types

1. Primary (Fundamental) Data Types

Data TypeSizeRangeExample
int2 or 4 bytes-32768 to 32767 (2B) / -2B to 2B (4B)int x = 10;
float4 bytes3.4E-38 to 3.4E+38float f = 3.14;
double8 bytes1.7E-308 to 1.7E+308double d = 3.14159;
char1 byte-128 to 127char c = 'A';
void0 bytesNo valuevoid func();

2. Modifiers

Modifiers change the size or sign of primary types:

  • signed β€” can hold positive and negative values
  • unsigned β€” only positive values (doubles the positive range)
  • short β€” smaller size (short int = 2 bytes)
  • long β€” larger size (long int = 4/8 bytes)

3. Derived Data Types

  • Array: Collection of same-type elements β€” int arr[10];
  • Pointer: Stores address of another variable β€” int *p;
  • Function: A block of code with a return type

4. User-Defined Data Types

  • Structure (struct): Groups different types
  • Union: Members share same memory
  • Enum: Named integer constants
  • typedef: Creates alias for data types
#include <stdio.h>
int main() {
    int age = 20;
    float salary = 25000.50;
    double pi = 3.14159265;
    char grade = 'A';
    unsigned int marks = 450;

    printf("Age: %d\n", age);
    printf("Salary: %.2f\n", salary);
    printf("Pi: %lf\n", pi);
    printf("Grade: %c\n", grade);
    printf("Marks: %u\n", marks);
    return 0;
}
Q.4

What are conditional statements? Compare nested-if else with else-if Ladder

β–Ό

What are Conditional Statements?

Conditional statements control program flow based on conditions. They allow the program to make decisions and execute specific blocks of code when certain conditions are true or false.

Types of Conditional Statements in C:
  1. Simple if
  2. if-else
  3. Nested if-else
  4. else-if Ladder
  5. switch-case

Nested if-else

When an if or else block contains another if-else inside it, it is called nested if-else.

/* Nested if-else: Find largest of 3 numbers */
int a = 10, b = 20, c = 15;

if (a > b) {
    if (a > c)
        printf("A is largest\n");   // inner if
    else
        printf("C is largest\n");   // inner else
} else {
    if (b > c)
        printf("B is largest\n");
    else
        printf("C is largest\n");
}

else-if Ladder

A series of if-else-if conditions chained together. When one condition is true, its block runs and the rest are skipped.

/* else-if Ladder: Grade System */
int marks = 75;

if (marks >= 90)
    printf("Grade: A+\n");
else if (marks >= 80)
    printf("Grade: A\n");
else if (marks >= 70)
    printf("Grade: B\n");     // This executes
else if (marks >= 60)
    printf("Grade: C\n");
else
    printf("Grade: Fail\n");

Comparison: Nested if-else vs else-if Ladder

FeatureNested if-elseelse-if Ladder
Structureif inside ifSequential if-else-if chain
ReadabilityCan get complex/deepMore readable and clean
Use CaseMultiple conditions on different variablesMultiple conditions on same variable
IndentationDeeply indentedFlat structure
ComplexityCan become confusingEasy to follow
FlexibilityEach branch can branch furtherLinear, one path chosen
Q.5

What do you mean by Loop? Differentiate between 'while' and 'do while'

β–Ό

What is a Loop?

A loop is a control structure that repeats a block of code as long as a specified condition is true. Loops avoid writing repetitive code.

Types of Loops in C:
  • for loop β€” when number of iterations is known
  • while loop β€” when condition is checked before execution
  • do-while loop β€” when block executes at least once

while Loop

Checks the condition before executing the body. If condition is false from the start, the loop body never executes.

/* Syntax */
while (condition) {
    // body
}

/* Example: Print 1 to 5 */
int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}
// Output: 1 2 3 4 5

do-while Loop

Checks the condition after executing the body. The loop body executes at least once, even if the condition is false.

/* Syntax */
do {
    // body
} while (condition);

/* Example: Print 1 to 5 */
int i = 1;
do {
    printf("%d ", i);
    i++;
} while (i <= 5);
// Output: 1 2 3 4 5

/* Key Difference β€” false condition from start */
int j = 10;
while (j < 5) { printf("while"); }   // Never prints
do { printf("do-while"); } while (j < 5); // Prints ONCE

Difference: while vs do-while

Featurewhiledo-while
Condition CheckBefore loop body (Entry-controlled)After loop body (Exit-controlled)
Minimum Executions0 (may not execute)1 (always executes once)
SemicolonNo semicolon after conditionSemicolon after while(condition);
Use CaseWhen condition may be false initiallyMenu-driven programs, user input validation
Syntaxwhile(cond) { }do { } while(cond);
Q.6

Explain the switch statement in C with suitable example

β–Ό

What is Switch Statement?

The switch statement is a multi-way branching statement. It tests the value of a variable or expression and compares it with multiple cases. When a match is found, that case's code executes.

Key Rules:
  • Switch expression must be of int or char type
  • Each case ends with break (to prevent fall-through)
  • default runs when no case matches (optional)
  • Case values must be constants, not variables

Syntax

switch (expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    // ...more cases
    default:
        // code if no case matches
}

Example β€” Simple Calculator

#include <stdio.h>

int main() {
    int a = 10, b = 4;
    char op;
    printf("Enter operator (+,-,*,/): ");
    scanf("%c", &op);

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

Example β€” Day of Week

int day = 3;
switch (day) {
    case 1: printf("Monday\n"); break;
    case 2: printf("Tuesday\n"); break;
    case 3: printf("Wednesday\n"); break; // This executes
    default: printf("Other Day\n");
}
Q.7

Write short notes on: break, continue, goto

β–Ό

1. break Statement

The break statement immediately exits the nearest enclosing loop or switch statement. Execution continues with the statement after the loop/switch.

/* break Example */
int i;
for (i = 1; i <= 10; i++) {
    if (i == 5)
        break;     // Loop stops when i=5
    printf("%d ", i);
}
// Output: 1 2 3 4
Used in: loops (for, while, do-while) and switch statements to exit early.

2. continue Statement

The continue statement skips the current iteration of the loop and jumps to the next iteration. Unlike break, it does NOT exit the loop.

/* continue Example */
int i;
for (i = 1; i <= 10; i++) {
    if (i % 2 == 0)
        continue;  // Skip even numbers
    printf("%d ", i);
}
// Output: 1 3 5 7 9 (odd numbers only)
Used in: loops when you want to skip certain iterations but continue the loop.

3. goto Statement

The goto statement transfers program control unconditionally to a labeled statement. It is generally considered bad practice but useful in error handling.

/* goto Example */
#include <stdio.h>

int main() {
    int i = 1;

start:                          // Label
    printf("%d ", i);
    i++;
    if (i <= 5)
        goto start;         // Jump to label 'start'

    printf("\nDone!\n");
    return 0;
}
// Output: 1 2 3 4 5
Note: goto is discouraged because it makes code hard to read and debug. Use loops instead whenever possible.

Summary Comparison

StatementPurposeWhere Used
breakExits loop/switch immediatelyLoops, switch
continueSkips current iterationLoops only
gotoJumps to a label unconditionallyAnywhere in function
Q.8

Write a program in C to find given number is Prime or not

β–Ό

What is a Prime Number?

A prime number is a number greater than 1 that has no divisors other than 1 and itself. Examples: 2, 3, 5, 7, 11, 13...

Algorithm

Step 1: Read number n
Step 2: If n <= 1, it is NOT prime
Step 3: Check divisibility from 2 to n/2
Step 4: If divisible by any, NOT prime
Step 5: Else, it IS prime
Step 6: Print result

C Program

#include <stdio.h>

int main() {
    int n, i, flag = 0;

    printf("Enter a number: ");
    scanf("%d", &n);

    if (n <= 1) {
        printf("%d is NOT a prime number.\n", n);
        return 0;
    }

    for (i = 2; i <= n / 2; i++) {
        if (n % i == 0) {
            flag = 1;   // Divisible, not prime
            break;
        }
    }

    if (flag == 0)
        printf("%d is a PRIME number.\n", n);
    else
        printf("%d is NOT a prime number.\n", n);

    return 0;
}
Output (n=7): 7 is a PRIME number.
Output (n=10): 10 is NOT a prime number.
Output (n=1): 1 is NOT a prime number.
Q.9

Write a program in C to print Fibonacci Series

β–Ό

What is Fibonacci Series?

The Fibonacci Series is a sequence where each number is the sum of the two preceding numbers.

Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Formula: F(n) = F(n-1) + F(n-2) where F(0)=0, F(1)=1

C Program

#include <stdio.h>

int main() {
    int n, a = 0, b = 1, c, i;

    printf("Enter number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    if (n >= 1) printf("%d ", a);
    if (n >= 2) printf("%d ", b);

    for (i = 3; i <= n; i++) {
        c = a + b;          // Next term = sum of previous two
        printf("%d ", c);
        a = b;              // Shift forward
        b = c;
    }
    printf("\n");
    return 0;
}
Output (n=10): 0 1 1 2 3 5 8 13 21 34
Q.10

Explain Array in C

β–Ό

What is an Array?

An array is a collection of elements of the same data type stored in contiguous memory locations. Each element is accessed by an index (starting from 0).

Key Points:
  • All elements are of the same type
  • Stored in consecutive memory locations
  • Accessed using index: arr[0], arr[1], ...
  • Index starts from 0 to size-1
  • Size must be specified at declaration (or initialized)

Types of Arrays

1. One-Dimensional (1D) Array

/* Declaration */
int marks[5];

/* Declaration + Initialization */
int marks[5] = {90, 85, 78, 92, 88};

/* Accessing elements */
printf("%d", marks[0]);   // 90 (first element)
printf("%d", marks[4]);   // 88 (last element)

/* Traversal */
int i;
for (i = 0; i < 5; i++)
    printf("%d ", marks[i]);

2. Two-Dimensional (2D) Array (Matrix)

/* 3x3 Matrix Declaration */
int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

/* Access: matrix[row][column] */
printf("%d", matrix[1][2]);  // 6

Properties of Arrays

PropertyDetails
Data TypeAll elements must be same type
IndexStarts from 0
MemoryContiguous allocation
SizeFixed at compile time
AccessRandom access via index (O(1))
Dimensions1D, 2D, Multi-dimensional
Q.11

Write a program in C for multiplication of 2D matrices of size 2Γ—2

β–Ό

Matrix Multiplication Concept

For two 2Γ—2 matrices A and B, the result C = A Γ— B is calculated as:

C[i][j] = Ξ£ A[i][k] * B[k][j] for k = 0 to n-1

For 2Γ—2:
C[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0]
C[0][1] = A[0][0]*B[0][1] + A[0][1]*B[1][1]
C[1][0] = A[1][0]*B[0][0] + A[1][1]*B[1][0]
C[1][1] = A[1][0]*B[0][1] + A[1][1]*B[1][1]

C Program

#include <stdio.h>

int main() {
    int A[2][2], B[2][2], C[2][2];
    int i, j, k;

    printf("Enter elements of Matrix A (2x2):\n");
    for (i = 0; i < 2; i++)
        for (j = 0; j < 2; j++)
            scanf("%d", &A[i][j]);

    printf("Enter elements of Matrix B (2x2):\n");
    for (i = 0; i < 2; i++)
        for (j = 0; j < 2; j++)
            scanf("%d", &B[i][j]);

    /* Matrix Multiplication */
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            C[i][j] = 0;
            for (k = 0; k < 2; k++)
                C[i][j] += A[i][k] * B[k][j];
        }
    }

    printf("\nResult Matrix C = A x B:\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++)
            printf("%d\t", C[i][j]);
        printf("\n");
    }
    return 0;
}
Sample Input A: [[1,2],[3,4]]   Input B: [[5,6],[7,8]]
Output C:
19   22
43   50
Q.12

Difference between Call by Value and Call by Reference function

β–Ό

Call by Value

A copy of the actual argument is passed to the function. Changes made inside the function do NOT affect the original variable.

/* Call by Value Example */
#include <stdio.h>

void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
    printf("Inside function: a=%d, b=%d\n", a, b);
}

int main() {
    int x = 10, y = 20;
    swap(x, y);
    printf("After call: x=%d, y=%d\n", x, y);
    // x and y unchanged! Output: x=10, y=20
    return 0;
}

Call by Reference

The address (reference) of the actual argument is passed. Changes inside the function DO affect the original variable.

/* Call by Reference Example */
#include <stdio.h>

void swap(int *a, int *b) {  // Pointers
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 10, y = 20;
    swap(&x, &y);   // Pass addresses
    printf("After call: x=%d, y=%d\n", x, y);
    // x=20, y=10 (ACTUALLY swapped!)
    return 0;
}

Comparison Table

FeatureCall by ValueCall by Reference
What is passedCopy of valueAddress of variable
Original affected?NoYes
MemoryExtra memory for copyNo extra memory
SafetySafer (original protected)Risk of accidental change
Syntaxfunc(x)func(&x)
Parameter typeint xint *x (pointer)
Q.13

What is String? Explain String handling functions with example

β–Ό

What is a String?

A string is a sequence of characters terminated by a null character '\0'. In C, strings are stored as character arrays.

/* String Declaration */
char name[20] = "Hello";  // {'H','e','l','l','o','\0'}
char city[] = "Delhi";   // Size auto-determined

/* Input/Output */
scanf("%s", name);       // Reads one word
gets(name);              // Reads full line with spaces
printf("%s", name);     // Print string
puts(name);              // Print + newline

String Handling Functions (string.h)

1. strlen() β€” String Length

#include <string.h>
char str[] = "Hello";
printf("%d", strlen(str));   // Output: 5

2. strcpy() β€” String Copy

char src[] = "World";
char dest[20];
strcpy(dest, src);
printf("%s", dest);    // Output: World

3. strcat() β€” String Concatenation

char s1[20] = "Hello";
char s2[] = " World";
strcat(s1, s2);
printf("%s", s1);     // Output: Hello World

4. strcmp() β€” String Compare

int result = strcmp("apple", "apple");
// Returns 0 if equal, negative if s1 < s2, positive if s1 > s2
if (result == 0) printf("Strings are equal\n");

5. strupr() / strlwr() β€” Upper/Lower Case

char str[] = "hello";
printf("%s", strupr(str));  // HELLO
printf("%s", strlwr(str));  // hello

6. strrev() β€” Reverse String

char str[] = "Hello";
printf("%s", strrev(str));  // olleH
FunctionPurposeHeader
strlen(s)Returns length of stringstring.h
strcpy(d, s)Copies s into dstring.h
strcat(d, s)Appends s to dstring.h
strcmp(s1, s2)Compares two stringsstring.h
strrev(s)Reverses stringstring.h
strupr(s)Converts to uppercasestring.h
strlwr(s)Converts to lowercasestring.h
Q.14

Write a program to declare, initialize and access a pointer and explain Pointer

β–Ό

What is a Pointer?

A pointer is a variable that stores the memory address of another variable. Instead of holding data directly, it holds the location of data in memory.

Key Operators:
& β€” Address-of operator (gives address of variable)
* β€” Dereference operator (gives value at address)

Declaration, Initialization, Access

#include <stdio.h>

int main() {
    int num = 42;          // Normal variable
    int *ptr;               // Pointer DECLARATION

    ptr = &num;             // INITIALIZATION β€” store address of num

    /* ACCESSING */
    printf("Value of num    : %d\n", num);
    printf("Address of num  : %p\n", &num);
    printf("Value of ptr    : %p\n", ptr);   // Same as &num
    printf("Value at *ptr   : %d\n", *ptr);  // Dereference = 42

    /* Modify original via pointer */
    *ptr = 100;
    printf("num after *ptr=100: %d\n", num); // 100

    return 0;
}

Types of Pointers

TypeDescriptionExample
NULL PointerPoints to nothingint *p = NULL;
Void PointerGeneric pointer, any typevoid *p;
Wild PointerUninitialized pointer (dangerous)int *p; (no init)
Dangling PointerPoints to freed memoryAfter free(p)
Double PointerPointer to pointerint **pp;

Pointer Arithmetic

int arr[3] = {10, 20, 30};
int *p = arr;           // Points to arr[0]
printf("%d\n", *p);    // 10
p++;                    // Move to next element
printf("%d\n", *p);    // 20
Q.15

What is recursion? Write a recursive program to find factorial of any given number

β–Ό

What is Recursion?

Recursion is a programming technique where a function calls itself to solve a smaller version of the same problem. Every recursive function must have a base case to stop.

Two Essential Parts:
  • Base Case: Condition where recursion stops (e.g., n==0)
  • Recursive Case: Function calls itself with smaller input

Factorial β€” Mathematical Definition

n! = n Γ— (n-1) Γ— (n-2) Γ— ... Γ— 1
0! = 1 (base case)
5! = 5 Γ— 4 Γ— 3 Γ— 2 Γ— 1 = 120

Recursive C Program for Factorial

#include <stdio.h>

/* Recursive Function */
long factorial(int n) {
    if (n == 0 || n == 1)
        return 1;          // Base Case
    else
        return n * factorial(n - 1);  // Recursive Call
}

int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);

    if (n < 0)
        printf("Factorial not defined for negative numbers.\n");
    else
        printf("Factorial of %d = %ld\n", n, factorial(n));

    return 0;
}

How Recursion Works for factorial(5)

factorial(5) β†’ 5 Γ— factorial(4)
factorial(4) β†’ 4 Γ— factorial(3)
factorial(3) β†’ 3 Γ— factorial(2)
factorial(2) β†’ 2 Γ— factorial(1)
factorial(1) β†’ 1 ← BASE CASE
↑ Returns back: 1Γ—2Γ—3Γ—4Γ—5 = 120
Output (n=5): Factorial of 5 = 120
Output (n=0): Factorial of 0 = 1
Q.16

Define a Structure and explain its features

β–Ό

What is a Structure?

A structure is a user-defined data type that groups variables of different data types under a single name. It is used to represent a record.

Syntax and Example

/* Structure Definition */
struct Student {
    int rollNo;
    char name[50];
    float marks;
    char grade;
};

int main() {
    /* Declaration of structure variable */
    struct Student s1;

    /* Accessing members using dot operator */
    s1.rollNo = 101;
    strcpy(s1.name, "Rahul");
    s1.marks = 85.5;
    s1.grade = 'A';

    printf("Roll No : %d\n", s1.rollNo);
    printf("Name    : %s\n", s1.name);
    printf("Marks   : %.1f\n", s1.marks);
    printf("Grade   : %c\n", s1.grade);

    return 0;
}

Features of Structure

  • Heterogeneous: Can hold different data types (int, float, char)
  • User-defined: You define its members
  • Dot operator (.): Used to access members via variable
  • Arrow operator (β†’): Used with structure pointers
  • Nested structure: Structure inside another structure
  • Array of structures: Useful for storing records (like a database)
  • Memory: Each member gets its own memory (unlike union)

Array of Structures

struct Student arr[3];   // 3 students
arr[0].rollNo = 1;
arr[1].rollNo = 2;

Structure vs Union

FeatureStructureUnion
MemorySum of all membersSize of largest member
MembersAll accessible at onceOnly one at a time
Keywordstructunion
Q.17

Explain any five standard Library functions in C

β–Ό

1. printf() β€” stdio.h

Used to print formatted output to the screen.

printf("Name: %s, Age: %d, GPA: %.2f\n", "Rohan", 20, 8.75);
// Output: Name: Rohan, Age: 20, GPA: 8.75

2. scanf() β€” stdio.h

Used to read formatted input from the keyboard.

int n; float x;
scanf("%d %f", &n, &x);   // Read int and float

3. sqrt() β€” math.h

Returns the square root of a number.

#include <math.h>
double result = sqrt(25.0);
printf("%.1f", result);   // 5.0

4. malloc() / free() β€” stdlib.h

malloc() dynamically allocates memory. free() releases it.

#include <stdlib.h>
int *ptr = (int*) malloc(5 * sizeof(int));  // 5 ints
if (ptr == NULL) { printf("Allocation failed!\n"); }
ptr[0] = 10;
free(ptr);    // Release memory

5. abs() β€” stdlib.h / math.h

Returns the absolute value of an integer.

#include <stdlib.h>
int x = -15;
printf("%d", abs(x));   // 15

Bonus Functions

FunctionPurposeHeader
pow(x, y)x raised to power ymath.h
rand()Generate random numberstdlib.h
exit()Terminate the programstdlib.h
toupper(c)Convert char to uppercasectype.h
isdigit(c)Check if char is digitctype.h
Q.18

W.A.P in C to Print pattern

β–Ό

Pattern 1 β€” Right Triangle of Stars

#include <stdio.h>
int main() {
    int i, j, n = 5;
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= i; j++)
            printf("* ");
        printf("\n");
    }
    return 0;
}
* * * * * * * * * * * * * * *

Pattern 2 β€” Number Triangle

int i, j, n = 5;
for (i = 1; i <= n; i++) {
    for (j = 1; j <= i; j++)
        printf("%d ", j);
    printf("\n");
}
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Pattern 3 β€” Inverted Triangle

int i, j, n = 5;
for (i = n; i >= 1; i--) {
    for (j = 1; j <= i; j++)
        printf("* ");
    printf("\n");
}
* * * * * * * * * * * * * * *

Pattern 4 β€” Pyramid (Diamond top)

int i, j, n = 5;
for (i = 1; i <= n; i++) {
    for (j = i; j < n; j++)   printf(" ");
    for (j = 1; j <= (2*i-1); j++) printf("*");
    printf("\n");
}
* *** ***** ******* *********

Pattern 5 β€” Alphabet Pattern

int i, j, n = 5;
for (i = 1; i <= n; i++) {
    for (j = 1; j <= i; j++)
        printf("%c ", (char)('A' + j - 1));
    printf("\n");
}
A A B A B C A B C D A B C D E
Q.19

Explain how Pointers can be used with function, array or structure

β–Ό

1. Pointer with Functions

Pointers allow functions to modify original variables (Call by Reference) and return multiple values.

/* Pointer with Function β€” Swap */
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 5, y = 10;
    swap(&x, &y);              // Pass addresses
    printf("%d %d\n", x, y); // 10 5 β€” actually swapped
    return 0;
}

/* Function Pointer */
int add(int a, int b) { return a+b; }
int (*fp)(int, int) = add;  // Function pointer
printf("%d", fp(3, 4));        // 7

2. Pointer with Arrays

An array name is itself a pointer to its first element. We can traverse arrays using pointer arithmetic.

int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;    // ptr points to arr[0]
int i;

/* Traverse array with pointer */
for (i = 0; i < 5; i++) {
    printf("%d ", *(ptr + i));  // Same as arr[i]
}
// Output: 10 20 30 40 50

/* Equivalent ways to access arr[2] */
printf("%d\n", arr[2]);        // 30
printf("%d\n", *(arr + 2));    // 30
printf("%d\n", *(ptr + 2));   // 30
printf("%d\n", ptr[2]);        // 30

3. Pointer with Structures

Pointers to structures use the arrow operator (β†’) to access members.

struct Student {
    int roll;
    char name[20];
};

int main() {
    struct Student s = {101, "Ankit"};
    struct Student *ptr = &s;   // Pointer to structure

    /* Access using arrow operator */
    printf("Roll: %d\n", ptr->roll);
    printf("Name: %s\n", ptr->name);

    /* Same as: (*ptr).roll */
    return 0;
}
UsageSyntaxDescription
Pointer + Functionfunc(&x) / int *pModifies original
Pointer + Array*(ptr+i) / ptr[i]Traverse array
Pointer + Structureptr→memberAccess struct member
Q.20

Explain Flow Chart with all its symbols

β–Ό

What is a Flowchart?

A flowchart is a graphical/diagrammatic representation of an algorithm or process using standard symbols connected by arrows showing the flow of control. It helps visualize the logic before coding.

Standard Flowchart Symbols

START/END
Oval / Terminator
Marks the start or end of the flowchart
Process
Rectangle / Process
Represents a process, calculation or action
Decision
Diamond / Decision
Represents Yes/No, True/False condition
Input/Output
Parallelogram
Input (read) or Output (print/display)
Flow
Arrow / Flowline
Shows direction of flow/control
Conn
Circle / Connector
Connects different parts of the flowchart
Predefined
Predefined Process
Calls a subroutine or pre-written function
Document
Document Symbol
Represents a printed document or report

Example: Flowchart to Find Largest of Two Numbers

START
↓
[Input A, B] (Parallelogram)
↓
<Is A > B?> (Diamond)
↓ YES          NO ↓
[Print A is Largest]    [Print B is Largest]
↓                     ↓
STOP

Advantages of Flowcharts

  • Provides visual representation of logic
  • Helps in program design before coding
  • Easy to understand and communicate
  • Helpful in debugging and finding errors
  • Serves as documentation for the program

Summary Table

SymbolShapeMeaning
TerminatorOvalStart / Stop
ProcessRectangleAssignment, calculation
DecisionDiamondCondition check (Yes/No)
I/OParallelogramInput/Output operations
FlowlineArrowDirection of flow
ConnectorCircleJoin flowchart parts
PredefinedRect with linesFunction / subroutine