Complete Question Bank

C Programming

Mid-1 Exam Solutions • Units I, II & III

53 Total Questions Unit I: 20 Qs Unit II: 27 Qs Unit III: 6 Qs
Chapter
Unit One
Problem Solving Techniques & Fundamentals of C
Q01

Explain various problem-solving techniques with suitable examples.

Problem-solving is a systematic process of understanding a given problem, developing a logical solution, and implementing it using a programming language. The important problem-solving techniques are:

  1. Top-Down Approach (Stepwise Refinement): A complex problem is divided into smaller, manageable subproblems. Each subproblem is further divided into simpler tasks until it becomes easy to solve.
    Example (Student Result Processing): Divide into (1) Accept marks, (2) Calculate total, (3) Calculate average, (4) Display result.
  2. Bottom-Up Approach: Smaller individual modules are developed and tested first, then combined to build a complete program.
    Example (Calculator): Build separate modules for addition, subtraction, multiplication, and division, then integrate them into one calculator program.
  3. Algorithm: A finite, ordered sequence of unambiguous, well-defined steps used to solve a particular problem. It must satisfy five properties: Input, Output, Definiteness, Finiteness, and Effectiveness.
    Example (Sum of two numbers): Step 1: Start → Step 2: Read A, B → Step 3: SUM = A + B → Step 4: Print SUM → Step 5: Stop.
  4. Flowchart: A graphical/visual representation of an algorithm using standard geometric symbols (Oval = Start/Stop, Parallelogram = Input/Output, Rectangle = Process, Diamond = Decision, Arrows = Flow lines).
  5. Pseudocode: An informal, English-like representation of an algorithm using programming-like keywords, independent of any specific programming language syntax.
    Example: BEGIN → READ A, B → SUM = A + B → PRINT SUM → END
  6. Divide and Conquer: Splitting a problem into independent subproblems of the same type, solving them recursively, and combining their results (e.g., Binary Search).
Q02

Develop a C program to implement swapping of two numbers using 3rd variable.

  1. Step 1: Start.
  2. Step 2: Declare three integer variables a, b, and temp.
  3. Step 3: Read two numbers a and b from the user.
  4. Step 4: Display the values of a and b before swapping.
  5. Step 5: Assign temp = a.
  6. Step 6: Assign a = b.
  7. Step 7: Assign b = temp.
  8. Step 8: Display the values of a and b after swapping.
  9. Step 9: Stop.
#include <stdio.h>
int main()
{
    int a, b, temp;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

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

    temp = a;
    a = b;
    b = temp;

    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}
Sample Input:
Enter two numbers: 10 20

Sample Output:
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10
Q03

Explain the structure of a C program with a suitable example.

A standard C program is organized into six distinct sections:

  1. Documentation Section: Contains comments (/* ... */ or //) describing the program name, author, date, and purpose. Ignored by the compiler.
  2. Link Section: Provides instructions to the compiler to link functions from the system library using #include directives (e.g., #include <stdio.h>).
  3. Definition Section: Defines all symbolic constants using the #define preprocessor directive (e.g., #define PI 3.14).
  4. Global Declaration Section: Declares global variables that are accessed by more than one function, along with user-defined function prototypes.
  5. main() Function Section: Every C program must have exactly one main() function where execution begins. It contains two parts:
    • Declaration Part: Declares all local variables used in the executable part.
    • Executable Part: Contains statements to perform operations and produce output.
  6. Sub-program Section: Contains all user-defined functions that are called from the main() function.
/* Program to add two numbers */        // 1. Documentation Section
#include <stdio.h>                       // 2. Link Section
#define PI 3.14                          // 3. Definition Section

int add(int, int);                       // 4. Global Declaration Section

int main()                               // 5. main() Function Section
{
    int a = 5, b = 7, sum;               // Declaration part
    sum = add(a, b);                     // Executable part
    printf("Sum = %d\n", sum);
    return 0;
}

int add(int x, int y)                    // 6. Sub-program Section
{
    return x + y;
}
Q04

Develop an algorithm to calculate sum and average of three numbers.

  1. Step 1: Start.
  2. Step 2: Declare variables a, b, c, sum, and avg.
  3. Step 3: Read three numbers a, b, and c from the user.
  4. Step 4: Calculate sum = a + b + c.
  5. Step 5: Calculate avg = sum / 3.0.
  6. Step 6: Display the values of sum and avg.
  7. Step 7: Stop.
Q05

Explain different steps involved in the compilation and execution of a C program.

Converting a human-readable C source file into an executable machine program involves six stages:

Source Code (.c) → Preprocessor (.i) → Compiler (.s) → Assembler (.o) → Linker (.exe) → Loader & Execution
  1. Editing (Creating Source Code): The programmer writes the C source code in a text editor/IDE and saves it with a .c extension (e.g., program.c).
  2. Preprocessing: The preprocessor processes lines starting with # (such as #include and #define), expands macros, includes header files, and removes comments to generate an expanded source file (program.i).
  3. Compilation: The compiler checks for syntax errors. If error-free, it translates the expanded C code into assembly-level instructions (program.s).
  4. Assembly: The assembler translates the assembly code into machine-readable binary object code (program.o or program.obj).
  5. Linking: The linker combines the object file with precompiled standard library routines (like printf() and scanf()) to produce a single executable file (a.out or program.exe).
  6. Loading and Execution: The operating system's loader loads the executable file from secondary storage into main memory (RAM), and the CPU executes the instructions sequentially.
Q06

Draw a flowchart to calculate area and perimeter of circle.

Symbols Used: Oval for Start/Stop, Parallelogram for Input/Output, Rectangle for Processing, and Arrows for Flow Direction.

START Read radius r area = 3.14159 * r * r perimeter = 2 * 3.14159 * r Print area, perimeter STOP
Q07

Discuss various data types available in C.

A data type specifies the type of data that a variable can store and how much memory is allocated to it. C data types are classified into four categories:

1. Primary (Basic) Data Types:

Data TypeDescriptionTypical SizeFormat SpecifierRange
charStores a single character1 Byte%c-128 to 127
intStores whole numbers (integers)4 Bytes%d-2,147,483,648 to 2,147,483,647
floatSingle-precision floating-point number4 Bytes%f3.4E-38 to 3.4E+38 (6 decimal digits)
doubleDouble-precision floating-point number8 Bytes%lf1.7E-308 to 1.7E+308 (15 decimal digits)
voidRepresents absence of value / no return type0 Bytes—Valueless

2. Type Modifiers: Keywords used with basic types to alter size or sign range: short, long, signed, and unsigned (e.g., unsigned int, long double).

3. Derived Data Types: Constructed from primary data types — Arrays, Pointers, and Functions.

4. User-Defined Data Types: Defined by the programmer — Structures (struct), Unions (union), Enumerations (enum), and typedef.

Q08

Develop a C program to find square and square root of a given number.

  1. Step 1: Start.
  2. Step 2: Include header files stdio.h and math.h.
  3. Step 3: Declare float variables n, sq, and root.
  4. Step 4: Read a number n from the user.
  5. Step 5: Calculate square using sq = n * n.
  6. Step 6: Calculate square root using root = sqrt(n).
  7. Step 7: Display sq and root.
  8. Step 8: Stop.
#include <stdio.h>
#include <math.h>
int main()
{
    float n, sq, root;
    printf("Enter a number: ");
    scanf("%f", &n);

    sq = n * n;
    root = sqrt(n);

    printf("Square = %.2f\n", sq);
    printf("Square root = %.2f\n", root);
    return 0;
}
Sample Input:
Enter a number: 16

Sample Output:
Square = 256.00
Square root = 4.00
Q09

Differentiate variables and constants in C with examples.

FeatureVariableConstant
DefinitionA named memory location whose value can change during program execution.A fixed value that cannot be altered during program execution.
Declaration Syntaxdata_type variable_name = value;const data_type name = value; or #define NAME value
ModificationCan be reassigned multiple times (e.g., age = 21;).Attempting to reassign causes a compile-time error.
MemoryAlways occupies memory in RAM.const occupies memory; #define is replaced by the preprocessor.
Examplesint age = 20;, float marks = 85.5;const float PI = 3.14;, #define MAX 100, literals 10, 'A'
Q10

Develop an algorithm to calculate simple interest.

  1. Step 1: Start.
  2. Step 2: Declare variables P, T, R, and SI.
  3. Step 3: Read Principal amount P, Time period T (in years), and Rate of interest R (% per annum).
  4. Step 4: Calculate Simple Interest using formula: SI = (P * T * R) / 100.0.
  5. Step 5: Display the value of SI.
  6. Step 6: Stop.
Q11

Discuss the rules for identifiers in C with suitable examples.

An identifier is a user-defined name given to program elements such as variables, functions, arrays, and structures.

Rules for Naming Identifiers:

  1. Allowed Characters: Can contain only uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), and the underscore (_).
  2. First Character Rule: Must begin with a letter or an underscore (_). It cannot start with a digit.
  3. No Spaces or Special Symbols: Whitespace and special characters (like @, #, $, %, -) are strictly prohibited.
  4. No Keywords: Reserved C keywords (such as int, for, while, return) cannot be used as identifiers.
  5. Case Sensitivity: C is case-sensitive; total, Total, and TOTAL are treated as three distinct identifiers.
  6. Length Significance: According to ANSI C standards, at least the first 31 characters are significant.

Examples:
Valid Identifiers: sum, student_marks, _count, num1, totalAmount
Invalid Identifiers: 1num (starts with digit), my var (contains space), int (keyword), price$ (special symbol), a-b (hyphen not allowed)

Q12

Develop a C program to calculate perimeter of circle.

  1. Step 1: Start.
  2. Step 2: Define symbolic constant PI = 3.14159.
  3. Step 3: Declare float variables r and perimeter.
  4. Step 4: Read the radius r from the user.
  5. Step 5: Calculate perimeter = 2 * PI * r.
  6. Step 6: Display the perimeter of the circle.
  7. Step 7: Stop.
#include <stdio.h>
#define PI 3.14159
int main()
{
    float r, perimeter;
    printf("Enter radius of circle: ");
    scanf("%f", &r);

    perimeter = 2 * PI * r;

    printf("Perimeter of circle = %.2f\n", perimeter);
    return 0;
}
Sample Input:
Enter radius of circle: 7

Sample Output:
Perimeter of circle = 43.98
Q13

Explain about input and output statements in C with an example.

C provides standard library functions (defined in <stdio.h>) for Input and Output operations, categorized into Formatted I/O and Unformatted I/O:

1. Formatted I/O Functions: Allow data to be read or displayed in a specific format using format specifiers (%d, %f, %c, %s, %lf).

  • printf("format string", arg1, arg2, ...); — Prints formatted output to the console.
  • scanf("format string", &var1, &var2, ...); — Reads formatted input from the keyboard. The address-of operator (&) provides the memory location of the variable.

2. Unformatted I/O Functions: Work primarily with characters and strings without format specifiers.

  • getchar() / putchar() — Reads / writes a single character.
  • gets() / puts() — Reads / writes a string (fgets() is preferred in modern C for safety).
#include <stdio.h>
int main()
{
    int age;
    float marks;
    char grade;

    printf("Enter age, marks and grade: ");
    scanf("%d %f %c", &age, &marks, &grade);

    printf("Age = %d, Marks = %.1f, Grade = %c\n", age, marks, grade);
    return 0;
}
Sample Input:
Enter age, marks and grade: 18 92.5 A

Sample Output:
Age = 18, Marks = 92.5, Grade = A
Q14

Develop a C program to find area of triangle using Heron's formula.

  1. Step 1: Start.
  2. Step 2: Include stdio.h and math.h header files.
  3. Step 3: Declare float variables a, b, c, s, and area.
  4. Step 4: Read the three sides of the triangle a, b, and c.
  5. Step 5: Calculate semi-perimeter s = (a + b + c) / 2.0.
  6. Step 6: Calculate area = sqrt(s * (s - a) * (s - b) * (s - c)).
  7. Step 7: Display the calculated area.
  8. Step 8: Stop.
#include <stdio.h>
#include <math.h>
int main()
{
    float a, b, c, s, area;
    printf("Enter three sides of triangle: ");
    scanf("%f %f %f", &a, &b, &c);

    s = (a + b + c) / 2.0;
    area = sqrt(s * (s - a) * (s - b) * (s - c));

    printf("Area of triangle = %.2f\n", area);
    return 0;
}
Sample Input:
Enter three sides of triangle: 3 4 5

Sample Output:
Area of triangle = 6.00
Q15

Explain arithmetic and logical operators with suitable examples.

1. Arithmetic Operators: Used to perform mathematical calculations on numeric operands.

OperatorMeaningExample (a = 10, b = 3)Result
+Additiona + b13
-Subtractiona - b7
*Multiplicationa * b30
/Division (quotient)a / b3
%Modulus (remainder, integers only)a % b1

2. Logical Operators: Used to combine or negate relational conditions. They return 1 (True) or 0 (False).

OperatorNameDescriptionExample (a = 10, b = 3)Result
&&Logical ANDTrue only if both conditions are true(a > 5) && (b > 5)0 (False)
||Logical ORTrue if at least one condition is true(a > 5) || (b > 5)1 (True)
!Logical NOTReverses the truth state of the condition!(a > 5)0 (False)
#include <stdio.h>
int main()
{
    int a = 10, b = 3;
    printf("Arithmetic: %d, %d, %d, %d, %d\n", a+b, a-b, a*b, a/b, a%b);
    printf("Logical AND: %d\n", (a > 5) && (b > 5));
    printf("Logical OR : %d\n", (a > 5) || (b > 5));
    printf("Logical NOT: %d\n", !(a > 5));
    return 0;
}
Q16

Develop an algorithm to convert temperature from Celsius to Fahrenheit and vice-versa.

  1. Step 1: Start.
  2. Step 2: Declare integer variable choice and float variables C and F.
  3. Step 3: Display menu: 1. Celsius to Fahrenheit, 2. Fahrenheit to Celsius.
  4. Step 4: Read choice from the user.
  5. Step 5: If choice == 1, then read Celsius temperature C, compute F = (C * 9.0 / 5.0) + 32, and print F.
  6. Step 6: Else if choice == 2, then read Fahrenheit temperature F, compute C = (F - 32) * 5.0 / 9.0, and print C.
  7. Step 7: Else print "Invalid choice".
  8. Step 8: Stop.
Q17

Explain relational and bitwise operators with suitable examples.

1. Relational Operators: Compare two values and return 1 (True) or 0 (False).

OperatorMeaningExample (a = 5, b = 3)Result
<Less thana < b0
>Greater thana > b1
<=Less than or equal toa <= b0
>=Greater than or equal toa >= b1
==Equal toa == b0
!=Not equal toa != b1

2. Bitwise Operators: Perform operations directly on individual bits of integer operands (let a = 5 [0101], b = 3 [0011]).

OperatorNameOperationResult
&Bitwise AND0101 & 0011 = 00011
|Bitwise OR0101 | 0011 = 01117
^Bitwise XOR0101 ^ 0011 = 01106
~Bitwise NOT (1's complement)~0101-6
<<Left Shift0101 << 1 = 101010
>>Right Shift0101 >> 1 = 00102
#include <stdio.h>
int main()
{
    int a = 5, b = 3;
    printf("Relational (a > b): %d, (a == b): %d\n", a > b, a == b);
    printf("Bitwise AND: %d, OR: %d, XOR: %d\n", a & b, a | b, a ^ b);
    printf("Left Shift: %d, Right Shift: %d\n", a << 1, a >> 1);
    return 0;
}
Q18

Write a C program to find the size of the data types.

  1. Step 1: Start.
  2. Step 2: Use the sizeof() operator for basic data types: char, short, int, long, float, and double.
  3. Step 3: Print the byte size of each data type using printf() with %zu format specifier.
  4. Step 4: Stop.
#include <stdio.h>
int main()
{
    printf("Size of char   : %zu byte\n", sizeof(char));
    printf("Size of short  : %zu bytes\n", sizeof(short));
    printf("Size of int    : %zu bytes\n", sizeof(int));
    printf("Size of long   : %zu bytes\n", sizeof(long));
    printf("Size of float  : %zu bytes\n", sizeof(float));
    printf("Size of double : %zu bytes\n", sizeof(double));
    return 0;
}
Sample Output (64-bit Compiler):
Size of char   : 1 byte
Size of short  : 2 bytes
Size of int    : 4 bytes
Size of long   : 8 bytes
Size of float  : 4 bytes
Size of double : 8 bytes
Q19

Develop a C program to find largest of three numbers using ternary operator.

  1. Step 1: Start.
  2. Step 2: Declare integer variables a, b, c, and largest.
  3. Step 3: Read three integers a, b, and c from the user.
  4. Step 4: Evaluate largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c).
  5. Step 5: Display the largest number.
  6. Step 6: Stop.
#include <stdio.h>
int main()
{
    int a, b, c, largest;
    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

    printf("Largest = %d\n", largest);
    return 0;
}
Sample Input:
Enter three numbers: 15 42 28

Sample Output:
Largest = 42
Q20

Explain about implicit type casting and explicit type casting in C with an example.

Type Casting is the process of converting a variable or expression from one data type into another.

  1. Implicit Type Casting (Automatic Type Conversion): Performed automatically by the compiler when operands of different data types are mixed in an expression. To prevent data loss, the compiler promotes the smaller data type to the larger data type following the hierarchy:
    char → short → int → unsigned int → long → float → double → long double
  2. Explicit Type Casting (Manual Type Conversion): Forced manually by the programmer using the cast operator (target_type) before an expression.
    Syntax: (data_type) expression;
#include <stdio.h>
int main()
{
    int a = 7, b = 2;
    float x;

    // Implicit type casting: 'a' is automatically promoted to float (7.0)
    x = a + 2.5;
    printf("Implicit result = %.1f\n", x);

    // Without explicit cast (integer division truncates decimal)
    printf("Integer division = %d\n", a / b);

    // Explicit type casting: 'a' is manually cast to float
    printf("Explicit cast division = %.2f\n", (float)a / b);

    return 0;
}
Sample Output:
Implicit result = 9.5
Integer division = 3
Explicit cast division = 3.50
Chapter
Unit Two
Control Structures, Loops & Arrays
Q01

Differentiate between while loop and do-while loop.

Featurewhile Loopdo-while Loop
Control TypeEntry-controlled loop (pre-test).Exit-controlled loop (post-test).
Condition CheckCondition is checked before executing the loop body.Condition is checked after executing the loop body.
Minimum ExecutionExecutes 0 times if the condition is initially false.Executes at least once even if the condition is false.
SemicolonNo semicolon after while(condition).Semicolon is mandatory after while(condition);.
Syntaxwhile (condition)
{
  // statements
}
do
{
  // statements
} while (condition);
Use CaseUsed when repetitions are unknown and zero executions are acceptable.Used for menu-driven programs or input validation.
Q02

Develop a C program to Check Vowel or Consonant.

  1. Step 1: Start.
  2. Step 2: Declare a character variable ch.
  3. Step 3: Read a character ch from the user.
  4. Step 4: Check if ch is any of 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'. If true, print "Vowel".
  5. Step 5: Else check if ch is an alphabet between 'A'-'Z' or 'a'-'z'. If true, print "Consonant".
  6. Step 6: Else print "Not a Valid Alphabet".
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    char ch;
    printf("Enter a character: ");
    scanf("%c", &ch);

    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
        ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
    {
        printf("%c is a Vowel\n", ch);
    }
    else if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
    {
        printf("%c is a Consonant\n", ch);
    }
    else
    {
        printf("Not a Valid Alphabet\n");
    }
    return 0;
}
Sample Input:
Enter a character: E

Sample Output:
E is a Vowel
Q03

Discuss the Syntax and flow chart for if-else.

The if-else statement is a two-way selection control structure that chooses between two alternative paths based on a condition. If the condition evaluates to True (non-zero), the if block executes; if it evaluates to False (0), the else block executes.

Syntax:

if (condition)
{
    // Statements executed if True
}
else
{
    // Statements executed if False
}
// Statement below if-else

Flowchart:

START Condition? True if block False else block Statement below if STOP
Q04

Develop a C program to generate sum of even numbers from 1 to N.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, i, and initialize sum = 0.
  3. Step 3: Read the upper limit n from the user.
  4. Step 4: Repeat for i = 2 to n in steps of 2 (i = i + 2):
  5. Step 5: Add i to sum (sum = sum + i).
  6. Step 6: Display the value of sum.
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    int n, i, sum = 0;
    printf("Enter N value: ");
    scanf("%d", &n);

    for (i = 2; i <= n; i += 2)
    {
        sum = sum + i;
    }

    printf("Sum of even numbers from 1 to %d = %d\n", n, sum);
    return 0;
}
Sample Input:
Enter N value: 10

Sample Output:
Sum of even numbers from 1 to 10 = 30
Q05

Discuss the syntax for declaration, initialization and accessing of 1D array elements with an example.

A One-Dimensional (1D) Array is a linear collection of elements of the same data type stored in contiguous memory locations and accessed using a single index.

1. Declaration of 1D Array: Specifies the data type, array name, and size.
Syntax: data_type array_name[size];  |  Example: int marks[5];

2. Initialization of 1D Array:

  • Compile-Time Initialization: Values are assigned directly during declaration.
    Syntax: data_type array_name[size] = {val1, val2, ...};  |  Example: int marks[5] = {10, 20, 30, 40, 50};
  • Run-Time Initialization: Values are read from the user during execution using a loop.
    Syntax: for(i = 0; i < size; i++) scanf("%d", &array_name[i]);

3. Accessing 1D Array Elements: Accessed using the subscript/index starting from 0 up to size - 1.
Syntax: array_name[index];  |  Example: marks[0] gives 10, marks[2] gives 30.

#include <stdio.h>
int main()
{
    int marks[5] = {10, 20, 30, 40, 50}; // Compile-time initialization
    int i;

    printf("First element: %d\n", marks[0]);
    printf("All array elements: ");
    for (i = 0; i < 5; i++)
    {
        printf("%d ", marks[i]);
    }
    return 0;
}
Q06

Develop a C program for calculating the factorial of a given number.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, i, and initialize fact = 1.
  3. Step 3: Read a positive integer n from the user.
  4. Step 4: Repeat for i = 1 to n:
  5. Step 5: Multiply fact by i (fact = fact * i).
  6. Step 6: Display the calculated factorial fact.
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    int n, i, fact = 1;
    printf("Enter a number: ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++)
    {
        fact = fact * i;
    }

    printf("Factorial of %d = %d\n", n, fact);
    return 0;
}
Sample Input:
Enter a number: 5

Sample Output:
Factorial of 5 = 120
Q07

Develop a C Program to print Grade of Student using else-if ladder.

  1. Step 1: Start.
  2. Step 2: Declare integer variables for 5 subject marks, total, float percentage, and char grade.
  3. Step 3: Read marks of 5 subjects from the user.
  4. Step 4: Compute total = s1 + s2 + s3 + s4 + s5 and percentage = (total / 500.0) * 100.
  5. Step 5: Use else-if ladder to assign grade: >=90 'O', >=80 'A', >=70 'B', >=60 'C', >=50 'D', else 'F'.
  6. Step 6: Print total, percentage, and grade.
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    int s1, s2, s3, s4, s5, total;
    float percentage;
    char grade;

    printf("Enter marks of 5 subjects: ");
    scanf("%d %d %d %d %d", &s1, &s2, &s3, &s4, &s5);

    total = s1 + s2 + s3 + s4 + s5;
    percentage = (total / 500.0) * 100;

    if (percentage >= 90)
        grade = 'O';
    else if (percentage >= 80)
        grade = 'A';
    else if (percentage >= 70)
        grade = 'B';
    else if (percentage >= 60)
        grade = 'C';
    else if (percentage >= 50)
        grade = 'D';
    else
        grade = 'F';

    printf("Total = %d, Percentage = %.2f%%, Grade = %c\n", total, percentage, grade);
    return 0;
}
Sample Input:
Enter marks of 5 subjects: 85 90 88 92 80

Sample Output:
Total = 435, Percentage = 87.00%, Grade = A
Q08

Discuss the syntax for declaration, initialization and accessing of 2D array elements with an example.

A Two-Dimensional (2D) Array is a collection of elements of the same data type organized in the form of rows and columns (like a matrix).

1. Declaration of 2D Array:
Syntax: data_type array_name[rows][columns];  |  Example: int a[2][3]; (2 rows, 3 columns).

2. Initialization of 2D Array:

  • Compile-Time Initialization:
    Syntax: data_type array_name[rows][cols] = {{r0_vals}, {r1_vals}};
    Example: int a[2][3] = {{10, 20, 30}, {40, 50, 60}};
  • Run-Time Initialization: Using nested for loops.
    Syntax: for(i=0; i<rows; i++) for(j=0; j<cols; j++) scanf("%d", &a[i][j]);

3. Accessing 2D Array Elements: Accessed using both row index and column index.
Syntax: array_name[row_index][column_index];  |  Example: a[1][2] accesses row 1, column 2 (60).

#include <stdio.h>
int main()
{
    int a[2][3] = {{10, 20, 30}, {40, 50, 60}};
    int i, j;

    printf("Element at a[1][2] = %d\n", a[1][2]);
    printf("Matrix elements:\n");
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 3; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }
    return 0;
}
Q09

Develop a C program to generate Multiplication Table.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, range, i, and result.
  3. Step 3: Read the number n and table range from the user.
  4. Step 4: Repeat for i = 1 to range:
  5. Step 5: Calculate result = n * i.
  6. Step 6: Display n, i, and result in format "n x i = result".
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    int n, range, i, result;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("Enter table range: ");
    scanf("%d", &range);

    for (i = 1; i <= range; i++)
    {
        result = n * i;
        printf("%d x %d = %d\n", n, i, result);
    }
    return 0;
}
Sample Input:
Enter a number: 5
Enter table range: 5

Sample Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
Q10

Discuss the Syntax and flow chart for switch statement.

The switch statement is a multi-way decision-making control structure that tests a variable or integer/character expression against a list of constant case values. When a match is found, the corresponding block executes until a break; statement is encountered.

Syntax:

switch (expression)
{
    case constant1:
        // statements
        break;
    case constant2:
        // statements
        break;
    default:
        // default statements
        break;
}

Flowchart:

Switch expression Case 1 True Case 1; break; False Case 2 True Case 2; break; False default default block Stmt after switch
Q11

Construct a calculator using a C program that performs arithmetic operations using switch statement.

  1. Step 1: Start.
  2. Step 2: Declare integer variables a, b and character variable op.
  3. Step 3: Read the arithmetic operator (+, -, *, /, %) into op.
  4. Step 4: Read two operands a and b.
  5. Step 5: Use switch(op) to match the operator:
  6. Step 6: Case '+': print a + b; break.
  7. Step 7: Case '-': print a - b; break.
  8. Step 8: Case '*': print a * b; break.
  9. Step 9: Case '/': if b != 0 print a / b, else print division by zero error; break.
  10. Step 10: Case '%': print a % b; break.
  11. Step 11: Default: print "Invalid operator".
  12. Step 12: Stop.
#include <stdio.h>
int main()
{
    int a, b;
    char op;

    printf("Enter an operator (+, -, *, /, %%): ");
    scanf("%c", &op);
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    switch (op)
    {
        case '+':
            printf("Sum = %d\n", a + b);
            break;
        case '-':
            printf("Difference = %d\n", a - b);
            break;
        case '*':
            printf("Product = %d\n", a * b);
            break;
        case '/':
            if (b != 0)
                printf("Quotient = %d\n", a / b);
            else
                printf("Error: Division by zero\n");
            break;
        case '%':
            printf("Remainder = %d\n", a % b);
            break;
        default:
            printf("Invalid operator\n");
    }
    return 0;
}
Sample Input:
Enter an operator (+, -, *, /, %): *
Enter two numbers: 6 7

Sample Output:
Product = 42
Q12

Differentiate 1D and 2D Arrays.

Feature1D Array (One-Dimensional)2D Array (Two-Dimensional)
DefinitionStores elements in a single linear row/list.Stores elements in rows and columns (matrix form).
Declaration Syntaxdata_type array_name[size];
Example: int a[5];
data_type array_name[rows][cols];
Example: int a[2][3];
Number of SubscriptsRequires only one index: a[i].Requires two indices: a[i][j].
Data OrganizationLinear sequence of elements.Tabular / Grid structure (rows × columns).
Loops for TraversalTypically requires a single loop.Typically requires nested loops (outer for rows, inner for columns).
ApplicationsList of student marks, temperatures, linear search.Matrix addition/multiplication, tables, image pixels.
Q13

Develop a C program to check whether a given number is prime or not.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, i, and initialize count = 0.
  3. Step 3: Read a number n from the user.
  4. Step 4: Repeat for i = 1 to n:
  5. Step 5: If n % i == 0, increment count by 1 (count++).
  6. Step 6: After the loop, check if count == 2.
  7. Step 7: If true, print "Prime Number"; otherwise print "Not a Prime Number".
  8. Step 8: Stop.
#include <stdio.h>
int main()
{
    int n, i, count = 0;
    printf("Enter a number: ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++)
    {
        if (n % i == 0)
            count++;
    }

    if (count == 2)
        printf("%d is a Prime Number\n", n);
    else
        printf("%d is Not a Prime Number\n", n);

    return 0;
}
Sample Input:
Enter a number: 7

Sample Output:
7 is a Prime Number
Q14

Discuss the Syntax and flow chart for nested if.

A nested if statement is an if statement placed inside another if or else block. It is used when one decision depends on the result of a previous condition.

Syntax:

if (condition1)
{
    if (condition2)
    {
        // Statement 1
    }
    else
    {
        // Statement 2
    }
}
else
{
    if (condition3)
    {
        // Statement 3
    }
    else
    {
        // Statement 4
    }
}

Flowchart:

START Cond 1? True Cond 2? False Cond 3? Stmt 1 Stmt 2 Stmt 3 Stmt 4 STOP
Q15

Construct a C program to find the transpose of a given matrix.

  1. Step 1: Start.
  2. Step 2: Read the number of rows r and columns c.
  3. Step 3: Declare original matrix a[r][c] and transpose matrix t[c][r].
  4. Step 4: Read elements of matrix a using nested for loops.
  5. Step 5: Compute transpose by interchanging rows and columns: t[j][i] = a[i][j].
  6. Step 6: Display the transpose matrix t of order c x r using nested for loops.
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    int r, c, i, j;
    printf("Enter rows and columns: ");
    scanf("%d %d", &r, &c);

    int a[r][c], t[c][r];

    printf("Enter matrix elements:\n");
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &a[i][j]);

    // Finding transpose
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            t[j][i] = a[i][j];

    printf("Transpose Matrix:\n");
    for (i = 0; i < c; i++)
    {
        for (j = 0; j < r; j++)
            printf("%d ", t[i][j]);
        printf("\n");
    }
    return 0;
}
Sample Input:
Enter rows and columns: 2 3
Enter matrix elements:
1 2 3
4 5 6

Sample Output:
Transpose Matrix:
1 4
2 5
3 6
Q16

Discuss the Syntax of for, while and do-while loop.

Loops (Iterative Statements) execute a block of code repeatedly as long as a specified condition remains true.

1. for Loop (Entry-Controlled): Used when the number of iterations is known in advance.

for (initialization; condition; update)
{
    // Loop body statements
}
  • Initialization: Sets the starting value of the loop counter (executes once).
  • Condition: Evaluated before every iteration; loop runs while true.
  • Update: Increments/decrements the counter after each iteration.

2. while Loop (Entry-Controlled): Used when the number of iterations is not known beforehand.

initialization;
while (condition)
{
    // Loop body statements
    update;
}

3. do-while Loop (Exit-Controlled): Executes the loop body at least once before testing the condition.

initialization;
do
{
    // Loop body statements
    update;
} while (condition);
Q17

Develop a C program to check whether a given number is a palindrome.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, temp, rem, and initialize rev = 0.
  3. Step 3: Read a number n from the user and store a copy in temp = n.
  4. Step 4: Repeat while n > 0:
  5. Step 5: Extract last digit: rem = n % 10.
  6. Step 6: Build reversed number: rev = rev * 10 + rem.
  7. Step 7: Remove last digit: n = n / 10.
  8. Step 8: If temp == rev, print "Palindrome Number"; else print "Not a Palindrome Number".
  9. Step 9: Stop.
#include <stdio.h>
int main()
{
    int n, temp, rem, rev = 0;
    printf("Enter a number: ");
    scanf("%d", &n);

    temp = n;
    while (n > 0)
    {
        rem = n % 10;
        rev = rev * 10 + rem;
        n = n / 10;
    }

    if (temp == rev)
        printf("%d is a Palindrome Number\n", temp);
    else
        printf("%d is Not a Palindrome Number\n", temp);

    return 0;
}
Sample Input:
Enter a number: 121

Sample Output:
121 is a Palindrome Number
Q18

Implement a C program to reverse the elements of a one-dimensional integer array.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, i, j, and temp.
  3. Step 3: Read the array size n and declare array a[n].
  4. Step 4: Read n array elements using a for loop.
  5. Step 5: Initialize i = 0 and j = n - 1.
  6. Step 6: Repeat using a for loop while i < j: swap a[i] and a[j] using temp, then increment i and decrement j.
  7. Step 7: Display the reversed array elements.
  8. Step 8: Stop.
#include <stdio.h>
int main()
{
    int n, i, j, temp;
    printf("Enter array size: ");
    scanf("%d", &n);

    int a[n];
    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    // Reverse array by swapping
    for (i = 0, j = n - 1; i < j; i++, j--)
    {
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    printf("Reversed array: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);

    return 0;
}
Sample Input:
Enter array size: 5
Enter 5 elements: 10 20 30 40 50

Sample Output:
Reversed array: 50 40 30 20 10
Q19

Apply matrix multiplication rules to develop a C program for multiplying two matrices.

Matrix Multiplication Rule: Two matrices A (m × n) and B (n × p) can be multiplied only if the number of columns in the first matrix equals the number of rows in the second matrix (c1 == r2). The resultant matrix C will have order m × p.

  1. Step 1: Start.
  2. Step 2: Read rows and columns of Matrix A (r1, c1) and Matrix B (r2, c2).
  3. Step 3: Check if c1 != r2. If not equal, display "Matrix multiplication is not possible" and stop.
  4. Step 4: Declare matrices a[r1][c1], b[r2][c2], and c[r1][c2], and read elements of A and B.
  5. Step 5: Use three nested loops: i from 0 to r1-1, j from 0 to c2-1, and k from 0 to c1-1.
  6. Step 6: Initialize c[i][j] = 0, then compute c[i][j] += a[i][k] * b[k][j].
  7. Step 7: Display the resultant matrix c.
  8. Step 8: Stop.
#include <stdio.h>
int main()
{
    int r1, c1, r2, c2, i, j, k;
    printf("Enter rows and columns of A: ");
    scanf("%d %d", &r1, &c1);
    printf("Enter rows and columns of B: ");
    scanf("%d %d", &r2, &c2);

    if (c1 != r2)
    {
        printf("Matrix multiplication is not possible\n");
        return 0;
    }

    int a[r1][c1], b[r2][c2], c[r1][c2];

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

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

    // Matrix multiplication
    for (i = 0; i < r1; i++)
    {
        for (j = 0; j < c2; j++)
        {
            c[i][j] = 0;
            for (k = 0; k < c1; k++)
            {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }

    printf("Resultant Matrix:\n");
    for (i = 0; i < r1; i++)
    {
        for (j = 0; j < c2; j++)
            printf("%d ", c[i][j]);
        printf("\n");
    }
    return 0;
}
Sample Input:
Enter rows and columns of A: 2 2
Enter rows and columns of B: 2 2
Enter elements of A: 1 2 3 4
Enter elements of B: 5 6 7 8

Sample Output:
Resultant Matrix:
19 22
43 50
Q20

Discuss about command line arguments.

Command Line Arguments are values passed to a C program from the command prompt/terminal at the time of program execution. They allow passing inputs directly without using scanf().

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

  • argc (Argument Count): An integer storing the total number of arguments passed, including the program name itself (minimum value is 1).
  • argv (Argument Vector): An array of character pointers (strings) storing each argument:
    • argv[0] stores the executable program name.
    • argv[1] stores the first user argument, argv[2] the second, and so on.

Note: All command line arguments are received as strings; numeric arguments must be converted using atoi() or atof() (from <stdlib.h>).

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    int i, sum = 0;
    printf("Program Name: %s\n", argv[0]);
    printf("Total Arguments: %d\n", argc);

    for (i = 1; i < argc; i++)
    {
        sum = sum + atoi(argv[i]);
    }
    printf("Sum of numeric arguments = %d\n", sum);
    return 0;
}
Command Execution:
./program 10 20 30

Output:
Program Name: ./program
Total Arguments: 4
Sum of numeric arguments = 60
Q21

Determine the minimum and maximum elements in one-dimensional integer array using C program.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, i, largest, and smallest.
  3. Step 3: Read array size n and declare array a[n].
  4. Step 4: Read n elements into array a.
  5. Step 5: Initialize largest = a[0] and smallest = a[0].
  6. Step 6: Traverse from i = 1 to n - 1: if a[i] > largest, update largest = a[i]; if a[i] < smallest, update smallest = a[i].
  7. Step 7: Display largest and smallest elements.
  8. Step 8: Stop.
#include <stdio.h>
int main()
{
    int n, i, largest, smallest;
    printf("Enter array size: ");
    scanf("%d", &n);

    int a[n];
    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    largest = a[0];
    smallest = a[0];

    for (i = 1; i < n; i++)
    {
        if (a[i] > largest)
            largest = a[i];
        if (a[i] < smallest)
            smallest = a[i];
    }

    printf("Largest Element = %d\n", largest);
    printf("Smallest Element = %d\n", smallest);
    return 0;
}
Sample Input:
Enter array size: 5
Enter 5 elements: 10 40 20 50 30

Sample Output:
Largest Element = 50
Smallest Element = 10
Q22

Develop a C program to perform linear search on 1D array.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, i, key, and initialize found = 0.
  3. Step 3: Read array size n and n elements into array a[n].
  4. Step 4: Read the search element key.
  5. Step 5: Repeat for i = 0 to n - 1: if a[i] == key, set found = 1, print position i + 1, and break.
  6. Step 6: If found == 0, print "Element not found".
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    int n, i, key, found = 0;
    printf("Enter array size: ");
    scanf("%d", &n);

    int a[n];
    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    printf("Enter element to search: ");
    scanf("%d", &key);

    for (i = 0; i < n; i++)
    {
        if (a[i] == key)
        {
            found = 1;
            printf("Element found at position %d\n", i + 1);
            break;
        }
    }

    if (found == 0)
        printf("Element not found\n");

    return 0;
}
Sample Input:
Enter array size: 5
Enter 5 elements: 10 20 30 40 50
Enter element to search: 30

Sample Output:
Element found at position 3
Q23

Develop a C program to perform addition of two matrices.

  1. Step 1: Start.
  2. Step 2: Declare variables r, c, i, and j, and read rows r and columns c.
  3. Step 3: Declare three 2D arrays a[r][c], b[r][c], and sum[r][c].
  4. Step 4: Read elements of first matrix a and second matrix b using nested for loops.
  5. Step 5: Add corresponding elements: sum[i][j] = a[i][j] + b[i][j].
  6. Step 6: Display the resultant matrix sum.
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    int r, c, i, j;
    printf("Enter rows and columns: ");
    scanf("%d %d", &r, &c);

    int a[r][c], b[r][c], sum[r][c];

    printf("Enter first matrix elements:\n");
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &a[i][j]);

    printf("Enter second matrix elements:\n");
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            scanf("%d", &b[i][j]);

    // Matrix addition
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            sum[i][j] = a[i][j] + b[i][j];

    printf("Sum of matrices:\n");
    for (i = 0; i < r; i++)
    {
        for (j = 0; j < c; j++)
            printf("%d ", sum[i][j]);
        printf("\n");
    }
    return 0;
}
Sample Input:
Enter rows and columns: 2 2
Enter first matrix: 1 2 3 4
Enter second matrix: 5 6 7 8

Sample Output:
Sum of matrices:
6 8
10 12
Q24

Develop a C program to display prime numbers from 1 to N.

  1. Step 1: Start.
  2. Step 2: Declare integer variables n, i, j, and count.
  3. Step 3: Read upper limit n from the user.
  4. Step 4: Outer loop: for i = 2 to n, set count = 0.
  5. Step 5: Inner loop: for j = 1 to i, if i % j == 0 increment count.
  6. Step 6: If count == 2, print i as a prime number.
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    int n, i, j, count;
    printf("Enter N value: ");
    scanf("%d", &n);

    printf("Prime numbers from 1 to %d are: ", n);
    for (i = 2; i <= n; i++)
    {
        count = 0;
        for (j = 1; j <= i; j++)
        {
            if (i % j == 0)
                count++;
        }
        if (count == 2)
            printf("%d ", i);
    }
    return 0;
}
Sample Input:
Enter N value: 20

Sample Output:
Prime numbers from 1 to 20 are: 2 3 5 7 11 13 17 19
Q25

Discuss any 2 operations on arrays with an example program.

Common operations performed on 1D arrays include Traversal, Insertion, Deletion, Searching, and Updating.

1. Traversal: Accessing and displaying each element of an array sequentially from index 0 to n - 1.

2. Insertion: Adding a new element at a specified position pos by shifting existing elements from index n - 1 down to pos - 1 one place to the right.

  1. Step 1: Start.
  2. Step 2: Read array size n and n elements into array a.
  3. Step 3: Traverse and display the original array.
  4. Step 4: Read the insertion position pos and new element value.
  5. Step 5: Shift elements right from i = n down to pos: a[i] = a[i - 1].
  6. Step 6: Insert a[pos - 1] = value and increment n.
  7. Step 7: Traverse and display the updated array.
  8. Step 8: Stop.
#include <stdio.h>
int main()
{
    int a[50], n, i, pos, value;
    printf("Enter array size: ");
    scanf("%d", &n);

    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    // 1. Traversal
    printf("Original Array: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);

    // 2. Insertion
    printf("\nEnter position and value to insert: ");
    scanf("%d %d", &pos, &value);

    for (i = n; i >= pos; i--)
        a[i] = a[i - 1];
    a[pos - 1] = value;
    n++;

    printf("Array after insertion: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);

    return 0;
}
Sample Input:
Enter array size: 5
Enter 5 elements: 10 20 30 40 50
Enter position and value to insert: 3 25

Sample Output:
Original Array: 10 20 30 40 50
Array after insertion: 10 20 25 30 40 50
Q26

Develop a C program to check whether the given number is even or odd.

  1. Step 1: Start.
  2. Step 2: Declare an integer variable n.
  3. Step 3: Read an integer n from the user.
  4. Step 4: Check if n % 2 == 0.
  5. Step 5: If true, print "Even Number"; otherwise print "Odd Number".
  6. Step 6: Stop.
#include <stdio.h>
int main()
{
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);

    if (n % 2 == 0)
        printf("%d is an Even Number\n", n);
    else
        printf("%d is an Odd Number\n", n);

    return 0;
}
Sample Input:
Enter a number: 17

Sample Output:
17 is an Odd Number
Q27

Differentiate break statement and continue statements.

Featurebreak Statementcontinue Statement
PurposeTerminates the enclosing loop or switch immediately.Skips the remaining statements of the current iteration and jumps to the next iteration.
Control FlowTransfers control outside the loop body.Transfers control to the condition/update step of the same loop.
Applicable InLoops (for, while, do-while) and switch.Only in loops (for, while, do-while); not in switch.
Nested LoopsExits only the innermost loop containing it.Skips the current iteration of the innermost loop only.
Syntaxbreak;continue;
Chapter
Unit Three
Strings & String Handling Functions
Q01

Explain various string handling functions with an example program.

A string in C is a one-dimensional array of characters terminated by a null character ('\0'). C provides predefined string handling functions in the <string.h> header file:

FunctionSyntaxPurpose
strlen()strlen(str)Returns the length of the string (number of characters excluding '\0').
strcpy()strcpy(dest, src)Copies contents of source string src into destination dest.
strcat()strcat(dest, src)Concatenates (appends) src at the end of dest.
strcmp()strcmp(s1, s2)Compares two strings lexicographically. Returns 0 if equal, <0 if s1 < s2, >0 if s1 > s2.
strncpy()strncpy(dest, src, n)Copies the first n characters from src to dest.
strncmp()strncmp(s1, s2, n)Compares the first n characters of s1 and s2.
strrev()strrev(str)Reverses the characters of a string in-place (compiler-dependent).
strupr() / strlwr()strupr(str) / strlwr(str)Converts string characters to uppercase / lowercase (compiler-dependent).
#include <stdio.h>
#include <string.h>
int main()
{
    char s1[30] = "Hello";
    char s2[] = "World";
    char s3[30];

    printf("Length of s1 = %zu\n", strlen(s1));

    strcpy(s3, s1);
    printf("Copied string s3 = %s\n", s3);

    strcat(s1, s2);
    printf("Concatenated s1 = %s\n", s1);

    if (strcmp(s2, "World") == 0)
        printf("Strings are equal\n");
    else
        printf("Strings are not equal\n");

    return 0;
}
Sample Output:
Length of s1 = 5
Copied string s3 = Hello
Concatenated s1 = HelloWorld
Strings are equal
Q02

Develop a C program to check whether the given string is Palindrome or not.

  1. Step 1: Start.
  2. Step 2: Declare character array str[100] and integer variables i, j, len = 0, flag = 0.
  3. Step 3: Read a string str from the user.
  4. Step 4: Find string length manually by counting characters until '\0'.
  5. Step 5: Set i = 0 and j = len - 1. Repeat while i < j: if str[i] != str[j], set flag = 1 and break.
  6. Step 6: If flag == 0, print "Palindrome"; otherwise print "Not Palindrome".
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    char str[100];
    int i, j, len = 0, flag = 0;

    printf("Enter a string: ");
    scanf("%s", str);

    // Find length without strlen()
    for (i = 0; str[i] != '\0'; i++)
        len++;

    // Compare characters from both ends
    for (i = 0, j = len - 1; i < j; i++, j--)
    {
        if (str[i] != str[j])
        {
            flag = 1;
            break;
        }
    }

    if (flag == 0)
        printf("%s is a Palindrome\n", str);
    else
        printf("%s is Not a Palindrome\n", str);

    return 0;
}
Sample Input:
Enter a string: madam

Sample Output:
madam is a Palindrome
Q03

Develop a C program to perform Concatenation of two strings without built-in functions.

  1. Step 1: Start.
  2. Step 2: Declare character arrays s1[100], s2[50], and integer variables i = 0, j = 0.
  3. Step 3: Read first string s1 and second string s2.
  4. Step 4: Move index i to the end of s1 using while (s1[i] != '\0') i++.
  5. Step 5: Copy each character of s2 into s1 starting at index i using while (s2[j] != '\0').
  6. Step 6: Append null character s1[i] = '\0' at the end.
  7. Step 7: Display the concatenated string s1.
  8. Step 8: Stop.
#include <stdio.h>
int main()
{
    char s1[100], s2[50];
    int i = 0, j = 0;

    printf("Enter first string: ");
    scanf("%s", s1);
    printf("Enter second string: ");
    scanf("%s", s2);

    // Move to end of first string
    while (s1[i] != '\0')
        i++;

    // Copy second string to end of first string
    while (s2[j] != '\0')
    {
        s1[i] = s2[j];
        i++;
        j++;
    }
    s1[i] = '\0';

    printf("Concatenated string: %s\n", s1);
    return 0;
}
Sample Input:
Enter first string: Hello
Enter second string: World

Sample Output:
Concatenated string: HelloWorld
Q04

Develop a C program to find the length of a string without built-in functions.

  1. Step 1: Start.
  2. Step 2: Declare character array str[100] and integer variables i, len = 0.
  3. Step 3: Read a string str from the user.
  4. Step 4: Repeat for i = 0 while str[i] != '\0': increment len by 1.
  5. Step 5: Display the length len.
  6. Step 6: Stop.
#include <stdio.h>
int main()
{
    char str[100];
    int i, len = 0;

    printf("Enter a string: ");
    scanf("%s", str);

    for (i = 0; str[i] != '\0'; i++)
    {
        len++;
    }

    printf("Length of string = %d\n", len);
    return 0;
}
Sample Input:
Enter a string: Programming

Sample Output:
Length of string = 11
Q05

Develop a C program to find reverse of string without built-in functions.

  1. Step 1: Start.
  2. Step 2: Declare character array str[100], char temp, and integer variables i, j, len = 0.
  3. Step 3: Read a string str from the user.
  4. Step 4: Calculate string length len by counting characters until '\0'.
  5. Step 5: Set i = 0 and j = len - 1. While i < j, swap str[i] and str[j] using temp.
  6. Step 6: Display the reversed string str.
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    char str[100], temp;
    int i, j, len = 0;

    printf("Enter a string: ");
    scanf("%s", str);

    while (str[len] != '\0')
        len++;

    for (i = 0, j = len - 1; i < j; i++, j--)
    {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }

    printf("Reversed string: %s\n", str);
    return 0;
}
Sample Input:
Enter a string: HELLO

Sample Output:
Reversed string: OLLEH
Q06

Develop a C program to convert uppercase of the string to lower case without built-in functions.

  1. Step 1: Start.
  2. Step 2: Declare character array str[100] and integer variable i.
  3. Step 3: Read a string str from the user.
  4. Step 4: Traverse each character from i = 0 until str[i] != '\0':
  5. Step 5: If str[i] >= 'A' and str[i] <= 'Z', add 32 to its ASCII value (str[i] = str[i] + 32).
  6. Step 6: Display the lowercase string str.
  7. Step 7: Stop.
#include <stdio.h>
int main()
{
    char str[100];
    int i;

    printf("Enter an uppercase string: ");
    scanf("%s", str);

    for (i = 0; str[i] != '\0'; i++)
    {
        if (str[i] >= 'A' && str[i] <= 'Z')
        {
            str[i] = str[i] + 32;
        }
    }

    printf("Lowercase string: %s\n", str);
    return 0;
}
Sample Input:
Enter an uppercase string: COMPUTER

Sample Output:
Lowercase string: computer