Skip to main content

Chapter 2

C Programming

TU BSc CSIT past exam questions

Past questions and answers

104 questions set from this chapter, 1 of them more than once. Most repeated first.

  • Asked 2 times
  • 2074 · 10 marks
  • 2078 · 5 marks

Discuss structure of a C Program with suitable example.

Answer

A C program is organised into a fixed set of sections. Each section has a definite purpose, and the compiler processes them from top to bottom.

1. Documentation section. Comments (/* ... */ or // ...) giving the program name, author and purpose. The compiler ignores them.

2. Preprocessor (link) section. Lines beginning with # such as #include <stdio.h> and #define PI 3.1416. They are handled before compilation; #include pulls in header files and #define creates symbolic constants and macros.

3. Global declaration section. Variables, structures and function prototypes declared outside every function, visible to the whole program.

4. main() function. Every program must have exactly one main(); execution starts here. It has a declaration part (local variables) followed by an executable part (statements), enclosed in { }.

5. User-defined functions. Functions written by the programmer, defined after or before main(), and called from it.

Example

/* Program to find the area of a circle */      /* documentation section */
#include <stdio.h>                               /* preprocessor section */
#define PI 3.1416

float area(float r);                             /* global declaration (prototype) */

int main()                                       /* main function */
{
    float r, a;                                  /* declaration part */
    printf("Enter radius: ");                    /* executable part */
    scanf("%f", &r);
    a = area(r);
    printf("Area = %.2f\n", a);
    return 0;
}

float area(float r)                              /* user-defined function */
{
    return PI * r * r;
}

Each statement ends with a semicolon, and the body of every function is enclosed in braces.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Write a program to display first n prime numbers.

Similar questions: C Programming: Write a program to display first 50 (2081)

Answer

A prime number is greater than 1 and has no divisors other than 1 and itself. To test a number numnum, it is enough to check divisibility by 2,3,…,⌊num⌋2, 3, \dots, \lfloor\sqrt{num}\rfloor. The program keeps testing numbers starting from 2 until nn primes have been printed.

#include <stdio.h>
#include <math.h>

int main()
{
    int n, count = 0, num = 2, i, isPrime;

    printf("How many prime numbers? ");
    scanf("%d", &n);

    printf("First %d prime numbers:\n", n);
    while (count < n) {
        isPrime = 1;
        for (i = 2; i <= (int)sqrt(num); i++) {
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
        }
        if (isPrime) {
            printf("%d ", num);
            count++;
        }
        num++;
    }
    printf("\n");
    return 0;
}

For n=6n = 6 the output is 2 3 5 7 11 13.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

List different types of operators and explain any three of them.

Similar questions: C Programming: List different types of operators and explain (2081)

Answer

Operators are symbols that tell the compiler to perform specific operations on operands.

Types of operators in C

  1. Arithmetic operators: + - * / %
  2. Relational operators: < > <= >= == !=
  3. Logical operators: && || !
  4. Assignment operators: = += -= *= /= %=
  5. Increment and decrement operators: ++ --
  6. Bitwise operators: & | ^ ~ << >>
  7. Conditional (ternary) operator: ?:
  8. Special operators: sizeof, comma ,, address &, dereference *, member access . and ->

Explanation of three

(a) Arithmetic operators perform mathematical calculations. If a = 7 and b = 2, then a + b = 9, a - b = 5, a * b = 14, a / b = 3 (integer division) and a % b = 1 (remainder).

(b) Relational operators compare two operands and give 1 (true) or 0 (false). For a = 7 and b = 2, a > b is 1 and a == b is 0.

(c) Logical operators combine conditions. && is true only if both operands are true, || is true if at least one is true, and ! reverses the truth value. For example, (a > 5 && b < 5) evaluates to 1.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 10 marks

List different types of operators and explain any four of them.

Similar questions: C Programming: List different types of operators and explain (2080)

Answer

An operator is a symbol that tells the compiler to perform a specific operation on one or more operands.

Types of operators in C

  1. Arithmetic: + - * / %
  2. Relational: < > <= >= == !=
  3. Logical: && || !
  4. Assignment: = += -= *= /= %=
  5. Increment and decrement: ++ --
  6. Bitwise: & | ^ ~ << >>
  7. Conditional (ternary): ?:
  8. Special: sizeof, comma, &, *, ., ->

Explanation of four

(a) Arithmetic operators perform mathematical calculations on numeric operands. With a = 17 and b = 5: a + b = 22, a - b = 12, a * b = 85, a / b = 3 (integer division truncates) and a % b = 2. The modulus operator works only on integers.

(b) Relational operators compare two values and yield 1 if the relation is true and 0 if false. With a = 17 and b = 5: a > b gives 1, a < b gives 0, a == b gives 0 and a != b gives 1.

(c) Logical operators combine or invert conditions. && (AND) is true only if both operands are non-zero, || (OR) is true if at least one is non-zero, and ! (NOT) inverts the truth value. Evaluation is short-circuit. For example, (a > 10 && b < 10) is 1 and !(a > b) is 0.

(d) Increment and decrement operators add or subtract 1 from a variable. In the prefix form (++x) the value is changed before use, and in the postfix form (x++) it is changed after use. If x = 5, then y = ++x gives x = 6, y = 6, whereas y = x++ gives y = 5, x = 6.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write a program to display first 50 prime numbers.

Similar questions: C Programming: Write a program to display first n (2077)

Answer

Method. A number n>1n>1 is prime if it has no divisor from 22 to n\sqrt{n}. We test each number starting from 22 and count primes until 5050 have been displayed. The 50th prime is 229229.

#include <stdio.h>
#include <math.h>

int isPrime(int n)
{
    int i;
    if (n < 2) return 0;
    for (i = 2; i <= (int)sqrt(n); i++)
        if (n % i == 0)
            return 0;
    return 1;
}

int main()
{
    int n = 2, count = 0;
    printf("First 50 prime numbers:\n");
    while (count < 50)
    {
        if (isPrime(n))
        {
            printf("%d ", n);
            count++;
            if (count % 10 == 0)
                printf("\n");
        }
        n++;
    }
    return 0;
}

Output.

2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 10 marks

Discuss different types of if statements with example of each. Differentiate if statement with switch statement.

Answer

The if family lets a program choose between alternative actions depending on a condition. A non-zero value means true and zero means false.

1. Simple if. Executes a block only when the condition is true.

if (marks >= 40)
    printf("Pass");

2. if-else. Chooses one of two blocks.

if (n % 2 == 0)
    printf("Even");
else
    printf("Odd");

3. Nested if. An if placed inside another if or else.

if (a >= b) {
    if (a >= c) printf("a is largest");
    else        printf("c is largest");
} else {
    if (b >= c) printf("b is largest");
    else        printf("c is largest");
}

4. else-if ladder. Tests several conditions in order; the first true one is executed and the rest are skipped.

if (p >= 80)      printf("Distinction");
else if (p >= 60) printf("First division");
else if (p >= 40) printf("Pass");
else              printf("Fail");

Difference between if and switch

if statementswitch statement
Can test any relational or logical expression, including ranges and floatsTests only equality of an integer or character expression against constants
Condition may combine several variables (a > b && c < d)One expression only
Slower for many alternatives, since conditions are checked one by oneOften compiled to a jump table, so cleaner and faster for many fixed values
else handles the remaining casesdefault handles the remaining cases
No break neededbreak is needed to stop fall-through

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 10 marks

What is structure? How is it different from array? Create a structure student having data members name, roll-number and percentage. Complete the program to display the name of student having percentage greater than or equal to 60.

Answer

Structure. A structure is a user-defined data type that groups variables of different data types under one name. The grouped variables are called members.

struct student {
    char name[30];
    int roll;
    float percentage;
};

Difference between structure and array

StructureArray
Collection of elements of different data typesCollection of elements of the same data type
Members are accessed by name with the . operatorElements are accessed by index a[i]
Declared with the keyword structDeclared with [ ]
Memory for members is not necessarily contiguous in an index-friendly way (padding may occur)Elements occupy contiguous memory
Structure variables can be assigned to one another directlyWhole arrays cannot be assigned with =

Program. Read the data of nn students and display the names of those with percentage greater than or equal to 60.

#include <stdio.h>

struct student {
    char name[30];
    int roll;
    float percentage;
};

int main()
{
    struct student s[100];
    int i, n;

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

    for (i = 0; i < n; i++) {
        printf("Enter name, roll number and percentage: ");
        scanf("%s %d %f", s[i].name, &s[i].roll, &s[i].percentage);
    }

    printf("Students with percentage >= 60:\n");
    for (i = 0; i < n; i++) {
        if (s[i].percentage >= 60)
            printf("%s\n", s[i].name);
    }
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

What is algorithm? How is it different from flow chart?

Answer

Algorithm. An algorithm is a finite, ordered sequence of well-defined steps written in simple language to solve a problem. It must have input, output, definiteness, finiteness and effectiveness.

Example: algorithm to find the sum of two numbers.

  1. Start
  2. Read aa and bb
  3. sum=a+bsum = a + b
  4. Print sumsum
  5. Stop

Flow chart. A flow chart is a diagrammatic representation of an algorithm using standard symbols (oval for start/stop, parallelogram for input/output, rectangle for process, diamond for decision) joined by arrows showing the flow of control.

Difference

AlgorithmFlow chart
Step-by-step description in wordsPictorial representation using symbols
Easy to write, but long logic is harder to followEasy to see flow and branching at a glance
Needs no special symbols or drawing toolsNeeds standard symbols and drawing effort
Easier to modify and convert directly into codeHarder to modify; large charts become complex
Takes less spaceTakes more space

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

What is type conversion? Discuss type casting with suitable example.

Answer

Type conversion. Type conversion is the change of a value from one data type to another when an expression contains operands of different types. It is of two kinds.

1. Implicit (automatic) conversion. The compiler converts the lower type to the higher type, following the order char -> int -> long -> float -> double, so that no information is lost.

int a = 5;
float b = 2.5, c;
c = a + b;      /* a is converted to float; c = 7.5 */

2. Explicit conversion (type casting). The programmer forces a conversion by placing the required type in parentheses before the expression:

(type) expression\text{(type) expression}

#include <stdio.h>
int main()
{
    int sum = 17, n = 5;
    float avg;
    avg = sum / n;            /* integer division: 3.000000 */
    printf("%f\n", avg);
    avg = (float) sum / n;    /* sum cast to float: 3.400000 */
    printf("%f\n", avg);
    return 0;
}

Without the cast, 17/517/5 is evaluated as integer division giving 33; with the cast, the result is 3.43.4. The cast changes only the value used in the expression, not the type of the variable itself.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

Discuss increment and decrement operators with example.

Answer

Increment operator ++ adds 1 to its operand and decrement operator -- subtracts 1 from it. Both are unary operators and can be used as prefix or postfix.

Prefix (++a, --a). The variable is changed first, then the new value is used in the expression.

Postfix (a++, a--). The current value is used in the expression first, then the variable is changed.

#include <stdio.h>
int main()
{
    int a = 5, b;

    b = ++a;                       /* a = 6, b = 6 */
    printf("%d %d\n", a, b);

    b = a++;                       /* b = 6, then a = 7 */
    printf("%d %d\n", a, b);

    b = --a;                       /* a = 6, b = 6 */
    printf("%d %d\n", a, b);

    b = a--;                       /* b = 6, then a = 5 */
    printf("%d %d\n", a, b);
    return 0;
}

Output:

6 6
7 6
6 6
5 6

They are commonly used to control loops, for example for (i = 0; i < n; i++). They can be applied only to variables, not to constants or expressions such as 5++.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

Write a program that computes the sum of digits of a given integer number

Answer

The digits are extracted one at a time: n % 10 gives the last digit, which is added to the sum, and n / 10 removes it. This is repeated until nn becomes 0.

#include <stdio.h>

int main()
{
    int n, digit, sum = 0;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n < 0)
        n = -n;              /* ignore the sign */

    while (n != 0) {
        digit = n % 10;
        sum = sum + digit;
        n = n / 10;
    }

    printf("Sum of digits = %d\n", sum);
    return 0;
}

Trace for n=1234n = 1234: digits 4,3,2,14, 3, 2, 1 are removed in turn, so sum=4+3+2+1=10sum = 4 + 3 + 2 + 1 = 10.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

What is function? Discuss the benefits of using function.

Answer

Function. A function is a self-contained block of statements that performs a specific task and can be called from other parts of a program. It has a name, optional parameters and an optional return value.

int square(int x)        /* function definition */
{
    return x * x;
}

Called as y = square(5); it returns 25.

Benefits of using functions

  1. Modularity. A large program is divided into small manageable parts, each solving one sub-problem.
  2. Reusability. Code written once can be called many times, even in other programs, so repetition is avoided.
  3. Easier debugging and testing. Each function can be tested separately and errors are easier to locate.
  4. Shorter, readable programs. Using meaningful function names makes the main program clear.
  5. Easy maintenance. A change made in one function affects every call without editing many places.
  6. Team development. Different programmers can write different functions of the same program.
  7. Reduced memory use. The code exists once, no matter how often it is called.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

Write a program to find sum and average of 10 integer numbers stored in an array.

Answer

#include <stdio.h>

int main()
{
    int a[10], i, sum = 0;
    float avg;

    printf("Enter 10 integers:\n");
    for (i = 0; i < 10; i++) {
        scanf("%d", &a[i]);
        sum = sum + a[i];
    }

    avg = (float) sum / 10;

    printf("Sum = %d\n", sum);
    printf("Average = %.2f\n", avg);
    return 0;
}

The array a stores the ten numbers. Each value is added to sum as it is read, and the average is avg=sum10avg = \frac{sum}{10} The cast (float) prevents integer division from truncating the average.

For example, for the inputs 1,2,…,101,2,\dots,10 the sum is 5555 and the average is 5.505.50.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

Define pointer. Discuss the relationship between pointer and one-dimensional array

Answer

Pointer. A pointer is a variable that stores the memory address of another variable. It is declared with *:

int x = 10;
int *p = &x;     /* p holds the address of x; *p is 10 */

& gives the address of a variable and * (dereference) gives the value stored at an address.

Relationship between pointer and one-dimensional array

  1. The name of an array is a constant pointer to its first element: a is the same as &a[0].
  2. If int *p = a;, then p + i is the address of a[i] and *(p + i) is the value of a[i]. Pointer arithmetic moves in units of the element size, so p + 1 advances by sizeof(int) bytes.
  3. Hence a[i], *(a + i), *(p + i) and p[i] are all equivalent.
  4. Unlike p, the array name a cannot be modified (a++ is illegal), while p++ is allowed.
#include <stdio.h>
int main()
{
    int a[5] = {10, 20, 30, 40, 50}, i, *p = a;
    for (i = 0; i < 5; i++)
        printf("%d %d %d\n", a[i], *(a + i), *(p + i));
    return 0;
}

Each line prints the same value three times, which shows that array access is pointer access.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

Write a program to read and print data stored in a file input.txt.

Answer

The file is opened in read mode with fopen, characters are read until EOF is reached, and each is printed. The pointer is checked for NULL in case the file does not exist.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    char ch;

    fp = fopen("input.txt", "r");
    if (fp == NULL) {
        printf("Cannot open file input.txt\n");
        exit(1);
    }

    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);

    fclose(fp);
    return 0;
}

fgetc reads one character from the stream, putchar writes it to the screen, and fclose releases the file.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2074 · 5 marks

Why do we need graphics functions? Write a program to draw a circle.

Answer

Need for graphics functions. The ordinary printf family can display only text. Graphics functions are needed to:

  1. Draw shapes such as lines, circles, rectangles and arcs, and to fill them with colours and patterns.
  2. Produce charts, graphs and diagrams to present data visually.
  3. Build games, animation and simulations.
  4. Create user interfaces with windows, buttons and menus.
  5. Display pictures and use different fonts, colours and text styles.

In Turbo C, these functions are declared in graphics.h and use the BGI drivers.

Program to draw a circle

#include <graphics.h>
#include <conio.h>

int main()
{
    int gd = DETECT, gm;

    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");   /* initialise graphics mode */
    circle(300, 200, 80);                      /* centre (300,200), radius 80 */
    getch();
    closegraph();                              /* return to text mode */
    return 0;
}

initgraph detects the graphics driver and mode, circle(x, y, r) draws a circle with centre (x,y)(x, y) and radius rr, and closegraph shuts down graphics mode.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 10 marks

What is looping statement? Discuss different looping statements with suitable example of each.

Answer

Looping statement. A looping statement repeats a block of statements as long as a given condition remains true. It avoids writing the same code many times. C provides three loops: while, do-while and for.

1. while loop (entry-controlled). The condition is tested before each iteration; if it is false at the start, the body never executes.

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

Output: 1 2 3 4 5

2. do-while loop (exit-controlled). The body executes first and the condition is tested afterwards, so the body runs at least once. Note the semicolon after the condition.

int i = 1;
do {
    printf("%d ", i);
    i++;
} while (i <= 5);

Output: 1 2 3 4 5

3. for loop. Initialisation, condition and update are written together in one line, which suits a known number of repetitions.

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

Output: 1 2 3 4 5

Summary

LoopCondition testedMinimum executions
whilebefore body0
do-whileafter body1
forbefore body0

Loops can be nested, and break and continue can be used to alter their flow.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 10 marks

Define array? What are the benefits of using array? Write a program to add two matrices using array.

Answer

Array. An array is a collection of elements of the same data type stored in contiguous memory locations and referred to by a common name and an index (starting at 0). Example: int marks[5];

Benefits of using an array

  1. Many values of the same type can be stored under one name instead of declaring many variables.
  2. Elements are accessed directly by index, which is fast.
  3. Loops can process all the elements easily.
  4. Useful for sorting, searching, tables and matrices.
  5. Memory is allocated contiguously, so traversal is efficient.

Program to add two matrices

Matrix addition is defined element by element: Cij=Aij+BijC_{ij} = A_{ij} + B_{ij} Both matrices must have the same order.

#include <stdio.h>

int main()
{
    int a[10][10], b[10][10], c[10][10];
    int r, col, i, j;

    printf("Enter rows and columns: ");
    scanf("%d %d", &r, &col);

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

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

    for (i = 0; i < r; i++)
        for (j = 0; j < col; j++)
            c[i][j] = a[i][j] + b[i][j];

    printf("Sum of the matrices:\n");
    for (i = 0; i < r; i++) {
        for (j = 0; j < col; j++)
            printf("%d\t", c[i][j]);
        printf("\n");
    }
    return 0;
}

For example, adding (1234)\begin{pmatrix}1&2\\3&4\end{pmatrix} and (5678)\begin{pmatrix}5&6\\7&8\end{pmatrix} gives (681012)\begin{pmatrix}6&8\\10&12\end{pmatrix}.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 10 marks

Why do we need data files? What are the different file opening modes? Write a program that reads data from a file “input.txt” and writes to “output.txt” file.

Answer

Need for data files. Variables live in RAM and are lost when the program ends. Data files are needed to:

  1. Store data permanently on disk.
  2. Handle large amounts of data that cannot be typed repeatedly or kept in memory.
  3. Share data between programs and transfer it between computers.
  4. Separate input and output from the program, so data can be reused or edited without recompiling.

File opening modes (used in fopen(name, mode))

ModeMeaning
"r"Open an existing file for reading; returns NULL if absent
"w"Create a file for writing; an existing file is erased
"a"Open for appending at the end; creates the file if absent
"r+"Read and write on an existing file
"w+"Read and write; creates new or erases existing file
"a+"Read and append; creates the file if absent

Appending b (for example "rb", "wb") opens the file in binary mode.

Program to copy input.txt to output.txt

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fin, *fout;
    char ch;

    fin = fopen("input.txt", "r");
    if (fin == NULL) {
        printf("Cannot open input.txt\n");
        exit(1);
    }
    fout = fopen("output.txt", "w");
    if (fout == NULL) {
        printf("Cannot create output.txt\n");
        fclose(fin);
        exit(1);
    }

    while ((ch = fgetc(fin)) != EOF)
        fputc(ch, fout);

    fclose(fin);
    fclose(fout);
    printf("File copied successfully.\n");
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

Discuss different logical operation in detail.

Answer

Logical operators combine or negate conditions and give a result of 1 (true) or 0 (false). In C any non-zero value is treated as true.

1. Logical AND &&. True only if both operands are true.

2. Logical OR ||. True if at least one operand is true.

3. Logical NOT !. Reverses the truth value of its operand.

Truth table

ABA && BA || B!A
00001
01011
10010
11110

Example

#include <stdio.h>
int main()
{
    int age = 25, marks = 70;

    if (age >= 18 && marks >= 40)
        printf("Eligible\n");           /* both true */

    if (age < 18 || marks >= 40)
        printf("At least one true\n");  /* second is true */

    if (!(marks < 40))
        printf("Not failed\n");

    return 0;
}

Short-circuit evaluation. In A && B, if A is false then B is not evaluated; in A || B, if A is true then B is not evaluated. Precedence order: ! highest, then &&, then ||.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

What is break statement? Discuss with example. How the break statement is different from continue statement?

Answer

break statement. break terminates the nearest enclosing loop (for, while, do-while) or switch immediately, and control passes to the statement following it.

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

Output: 1 2 3 4. The loop ends when i=5i = 5.

Difference between break and continue

breakcontinue
Exits the loop or switch completelySkips the rest of the current iteration only
Control goes to the statement after the loopControl goes to the next iteration (to the update part in for, the condition in while)
Can be used in switchCannot be used in switch (only in loops)

Using continue in the same loop:

for (i = 1; i <= 6; i++) {
    if (i == 3)
        continue;
    printf("%d ", i);
}

Output: 1 2 4 5 6. Only the value 3 is skipped.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

Write a program to check whether a number entered is even or odd.

Answer

A number is even if it is exactly divisible by 2, that is, the remainder n % 2 is 0; otherwise it is odd.

#include <stdio.h>

int main()
{
    int n;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n % 2 == 0)
        printf("%d is even.\n", n);
    else
        printf("%d is odd.\n", n);

    return 0;
}

For n=8n = 8: 8 mod 2=08 \bmod 2 = 0, so it is even. For n=7n = 7: 7 mod 2=17 \bmod 2 = 1, so it is odd. Negative numbers work as well since n % 2 == 0 is true for every even value.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

Write a program to calculate sum of first 10 odd numbers.

Answer

The first 10 odd numbers are 1,3,5,…,191, 3, 5, \dots, 19. The kk-th odd number is 2k−12k-1, and the loop adds them using step 2.

#include <stdio.h>

int main()
{
    int i, sum = 0;

    for (i = 1; i <= 19; i += 2)
        sum = sum + i;

    printf("Sum of first 10 odd numbers = %d\n", sum);
    return 0;
}

Check: the sum of the first nn odd numbers is n2n^2, so for n=10n = 10: 1+3+5+⋯+19=102=1001 + 3 + 5 + \dots + 19 = 10^2 = 100 and the program prints Sum of first 10 odd numbers = 100.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

What is preprocessor directives? Discuss # define directive with example.

Answer

Preprocessor directives. These are instructions to the preprocessor, which runs before the compiler. Each begins with # and does not end with a semicolon. The preprocessor modifies the source text (including files, substituting macros, selecting code) before compilation.

Common directives: #include, #define, #undef, #ifdef, #ifndef, #if, #else, #endif.

#define directive. It defines a symbolic constant or a macro; every occurrence of the name is replaced by its text before compilation.

Symbolic constant

#define PI 3.1416
#define MAX 100

Macro with arguments

#include <stdio.h>
#define PI 3.1416
#define SQUARE(x) ((x) * (x))

int main()
{
    float r = 2.0;
    printf("Area = %.2f\n", PI * SQUARE(r));   /* 3.1416 * 4 = 12.57 */
    return 0;
}

Advantages: the value is changed in one place, programs are more readable, and macros avoid function call overhead. The parentheses around x prevent wrong results such as SQUARE(a+1) expanding incorrectly.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

Discuss any five string library functions.

Answer

String library functions are declared in <string.h>.

1. strlen(s) returns the number of characters in s, excluding the null character.

strlen("Nepal");      /* 5 */

2. strcpy(dest, src) copies the string src into dest.

char a[20];
strcpy(a, "Hello");   /* a = "Hello" */

3. strcat(dest, src) appends src to the end of dest.

char a[20] = "Hello ";
strcat(a, "World");   /* a = "Hello World" */

4. strcmp(s1, s2) compares two strings alphabetically. It returns 0 if equal, a negative value if s1 < s2 and a positive value if s1 > s2.

strcmp("apple", "apple");   /* 0 */
strcmp("apple", "banana");  /* negative */

5. strrev(s) reverses a string (available in Turbo C; non-standard).

char s[] = "abc";
strrev(s);                  /* s = "cba" */

Other useful ones are strncpy, strncat, strchr, strstr, strlwr and strupr. Destination arrays must be large enough to hold the result.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

What is dynamic memory allocation? Discuss the use of malloc() in dynamic memory allocation with example.

Answer

Dynamic memory allocation. It is the allocation of memory at run time from the heap, as opposed to static allocation at compile time. The size need not be known in advance, memory can be released when not needed, and so memory is used efficiently (for example arrays whose size is entered by the user). The functions are malloc(), calloc(), realloc() and free(), declared in <stdlib.h>.

malloc(). It allocates a block of the given number of bytes and returns a void * pointer to its start, or NULL if allocation fails. The memory is not initialised.

ptr = (cast_type *) malloc(size_in_bytes);\text{ptr = (cast\_type *) malloc(size\_in\_bytes);}

Example. Store nn integers and display their sum.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *p, n, i, sum = 0;

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

    p = (int *) malloc(n * sizeof(int));
    if (p == NULL) {
        printf("Memory not available\n");
        exit(1);
    }

    for (i = 0; i < n; i++) {
        scanf("%d", p + i);
        sum += *(p + i);
    }
    printf("Sum = %d\n", sum);

    free(p);           /* release the memory */
    return 0;
}

free(p) returns the block to the system and avoids memory leaks.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

What is structure? Create a structure rectangle with data members length and breadth.

Answer

Structure. A structure is a user-defined data type that groups related variables, possibly of different types, under a single name. Its members are accessed with the dot operator (variable.member), or -> through a pointer.

Structure rectangle

struct rectangle {
    float length;
    float breadth;
};

Use in a program (computing area and perimeter)

#include <stdio.h>

struct rectangle {
    float length;
    float breadth;
};

int main()
{
    struct rectangle r;

    printf("Enter length and breadth: ");
    scanf("%f %f", &r.length, &r.breadth);

    printf("Area = %.2f\n", r.length * r.breadth);
    printf("Perimeter = %.2f\n", 2 * (r.length + r.breadth));
    return 0;
}

For length 55 and breadth 33: area =5×3=15= 5 \times 3 = 15 and perimeter =2(5+3)=16= 2(5+3) = 16.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2075 · 5 marks

Write short notes on:
  • Benefits of data files
  • Graphics functions

Answer

Benefits of data files

  1. Permanent storage. Data stays on disk after the program ends, unlike variables in memory.
  2. Large data handling. Big volumes of data can be processed without entering them each time or holding them all in RAM.
  3. Reusability and sharing. The same data can be used by different programs and moved between computers.
  4. Separation of data from program. Data can be changed without modifying or recompiling the code.
  5. Automation. Input can be read from files and results written to files, avoiding repeated keyboard entry.

Graphics functions

Graphics functions, declared in graphics.h (Turbo C, BGI), allow a program to draw on the screen instead of printing only text. They are used for pictures, charts, games, animation and interfaces.

FunctionPurpose
initgraph(&gd, &gm, path)Initialise graphics mode
closegraph()Close graphics mode
line(x1, y1, x2, y2)Draw a line
circle(x, y, r)Draw a circle
rectangle(l, t, r, b)Draw a rectangle
arc, ellipseDraw arcs and ellipses
setcolor(c), setfillstyle, floodfillSet colour and fill
outtextxy(x, y, str)Display text at a position

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 10 marks

What do you mean by looping? Explain while loop with suitable example. Compare while loop with do-while loop. Write a program to find sum and average of first n natural numbers.

Answer

Looping. Looping is the repeated execution of a block of statements while a condition holds. It saves writing the same code many times. C has the while, do-while and for loops.

while loop. It is an entry-controlled loop: the condition is evaluated first, and the body runs only if it is true. The loop repeats until the condition becomes false, so the body may execute zero times.

Syntax:

while (condition) {
    statements;
}

Example: print the numbers 1 to 5.

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

Output: 1 2 3 4 5

Comparison of while and do-while

whiledo-while
Entry-controlled: condition tested before the bodyExit-controlled: condition tested after the body
Body may never executeBody executes at least once
No semicolon after the conditionSemicolon is required after while (condition);
Syntax: while (cond) { ... }Syntax: do { ... } while (cond);
Used when the loop may need to be skippedUsed when the body must run at least once (such as menus)

Program: sum and average of the first nn natural numbers

#include <stdio.h>

int main()
{
    int n, i = 1, sum = 0;
    float avg;

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

    while (i <= n) {
        sum = sum + i;
        i++;
    }
    avg = (float) sum / n;

    printf("Sum = %d\n", sum);
    printf("Average = %.2f\n", avg);
    return 0;
}

Check with n=10n = 10: the sum is n(n+1)2=10×112=55\frac{n(n+1)}{2} = \frac{10 \times 11}{2} = 55 and the average is 55/10=5.5055/10 = 5.50, which matches the program output.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 10 marks

What are the benefits of using arrays? Compare one dimensional array with two dimensional array. Write a program to find transpose of a matrix.

Answer

Benefits of arrays

An array is a collection of elements of the same data type stored in contiguous memory locations and accessed by a common name and an index.

  • Many values can be stored under one name, so we do not declare hundreds of separate variables (marks[100] instead of m1, m2, ... m100).
  • Elements are accessed directly by index in constant time, O(1)O(1).
  • Loops can process all elements easily (input, output, sum, search, sort).
  • Contiguous storage makes traversal fast and makes pointer arithmetic possible.
  • Arrays are the basis for strings, matrices and data structures such as stacks and queues.

One dimensional vs two dimensional array

BasisOne dimensional arrayTwo dimensional array
StructureA single row (list) of elementsA table of rows and columns (array of arrays)
Declarationint a[5];int a[3][4];
SubscriptsOne index: a[i]Two indices: a[i][j]
Total elementsnnrows×colsrows \times cols
TraversalOne loopNested loops
Typical useList of marks, stringMatrix, table, image grid
Initializationint a[3] = {1,2,3};int a[2][2] = {{1,2},{3,4}};

Program to find the transpose of a matrix

The transpose B=ATB = A^T of an m×nm \times n matrix is the n×mn \times m matrix with bji=aijb_{ji} = a_{ij}.

#include <stdio.h>

int main()
{
    int a[10][10], t[10][10];
    int i, j, r, c;

    printf("Enter rows and columns: ");
    scanf("%d %d", &r, &c);

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

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

    printf("Original matrix:\n");
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++)
            printf("%d\t", a[i][j]);
        printf("\n");
    }

    printf("Transpose of the matrix:\n");
    for (i = 0; i < c; i++) {
        for (j = 0; j < r; j++)
            printf("%d\t", t[i][j]);
        printf("\n");
    }
    return 0;
}

Example: for A=[123456]A = \begin{bmatrix}1&2&3\\4&5&6\end{bmatrix} the output is AT=[142536]A^T = \begin{bmatrix}1&4\\2&5\\3&6\end{bmatrix}.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 10 marks

What is structure? How is it different from union? Create a structure named course with name, code, and credit_hour as its members. Write a program using this structure to read data of 5courses and display data of those curses with credit_hour greater than 3.

Answer

Structure

A structure is a user-defined data type that groups variables of different data types under one name. Each variable is called a member. It is declared with the keyword struct.

struct student {
    char name[20];
    int roll;
    float marks;
};

Structure vs union

BasisStructureUnion
Keywordstructunion
MemoryEach member has its own memory; size is at least the sum of member sizesAll members share the same memory; size equals the largest member
AccessAll members can hold values at the same timeOnly one member holds a valid value at a time
ModifyingChanging one member does not affect the othersChanging one member overwrites the others
UseWhen all data is needed togetherTo save memory when only one value is needed at a time

For struct {int i; float f;} the size is 8 bytes (with 4-byte int and float); for the same members in a union it is 4 bytes.

Program

#include <stdio.h>

struct course {
    char name[50];
    char code[10];
    int credit_hour;
};

int main()
{
    struct course c[5];
    int i;

    for (i = 0; i < 5; i++) {
        printf("Enter data of course %d\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", c[i].name);
        printf("Code: ");
        scanf("%s", c[i].code);
        printf("Credit hour: ");
        scanf("%d", &c[i].credit_hour);
    }

    printf("\nCourses with credit hour greater than 3:\n");
    printf("%-30s %-10s %s\n", "Name", "Code", "Credit hour");
    for (i = 0; i < 5; i++) {
        if (c[i].credit_hour > 3)
            printf("%-30s %-10s %d\n", c[i].name, c[i].code, c[i].credit_hour);
    }
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Explain flowchart with example. What are the benefits of using flowcharts?

Answer

Flowchart

A flowchart is a pictorial representation of the steps of an algorithm or program using standard symbols connected by arrows that show the flow of control.

SymbolMeaning
Oval (terminator)Start / Stop
ParallelogramInput / Output
RectangleProcess (calculation, assignment)
DiamondDecision (condition, Yes/No)
ArrowDirection of flow
CircleConnector

Example: largest of two numbers

  1. Start
  2. Read aa, bb
  3. Is a>ba > b? If Yes, print aa; if No, print bb
  4. Stop

In flowchart form: Start -> Input a, b -> a > b ? -> (Yes) Print a / (No) Print b -> Stop.

Benefits of flowcharts

  • They make the logic of a program easy to understand visually.
  • They help in planning and finding logical errors before coding.
  • They serve as documentation for later maintenance.
  • They help in communication between programmers, analysts and non-technical people.
  • They are language independent and make the program easier to code and debug.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

What is data type? Why do we need it in programming? Explain any three basic data types with example.

Answer

Data type

A data type specifies the kind of value a variable can hold, the amount of memory allocated to it, the range of values and the operations allowed on it.

Need for data types

  • The compiler knows how much memory to reserve for each variable.
  • They define the valid range of values and the operations (for example % is allowed on int but not on float).
  • They allow type checking, which catches errors at compile time.
  • They decide how the stored bits are interpreted (integer, real number, character).

Three basic data types

TypeSize (typical)RangeFormatExample
int4 bytes−231-2^{31} to 231−12^{31}-1%dint age = 20;
float4 bytesabout 3.4×10±383.4\times10^{\pm38}, 6 digits precision%ffloat pi = 3.14;
char1 byte−128-128 to 127127%cchar grade = 'A';
#include <stdio.h>
int main()
{
    int age = 20;
    float pi = 3.14;
    char grade = 'A';
    printf("%d %f %c\n", age, pi, grade);
    return 0;
}

Others include double (8 bytes, higher precision), short, long and void.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

What do you mean by unformatted I/O? Explain

Answer

Unformatted I/O

Unformatted I/O functions read or write data in a raw form (a single character or a line of text) without using format specifiers such as %d or %f. No conversion between internal and external representation is performed. They are declared in <stdio.h> (and <conio.h> in some compilers).

FunctionPurpose
getchar()Reads one character from the keyboard (needs Enter)
putchar(c)Writes one character to the screen
getch() / getche()Reads a character without waiting for Enter (without / with echo), from <conio.h>
gets(str) / fgets(str, n, stdin)Reads a line of text including spaces into a string
puts(str)Writes a string followed by a newline
#include <stdio.h>
int main()
{
    char ch, name[30];

    printf("Enter a character: ");
    ch = getchar();
    printf("You entered: ");
    putchar(ch);
    putchar('\n');

    getchar();                       /* consume newline */
    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);
    puts(name);
    return 0;
}

gets() is unsafe because it does not check buffer size, so fgets() is preferred. Unlike scanf/printf, these functions deal only with characters and strings.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Write a program to find product of two integers using your own function.

Answer

The function product() receives two integers by value and returns their product to main().

#include <stdio.h>

int product(int x, int y)
{
    return x * y;
}

int main()
{
    int a, b, result;

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    result = product(a, b);
    printf("Product of %d and %d = %d\n", a, b, result);
    return 0;
}

For input 6 7 the output is Product of 6 and 7 = 42.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Define pointer. Flow to you return pointers from functions? Explain with example.

Answer

Pointer

A pointer is a variable that stores the memory address of another variable. It is declared with *, the address is obtained with &, and the value at the address is accessed with the dereference operator *.

int a = 10;
int *p = &a;      /* p holds the address of a */
printf("%d", *p); /* prints 10 */

Returning a pointer from a function

A function can return a pointer by declaring its return type as a pointer, for example int *func(). The returned address must stay valid after the function ends, so we must never return the address of an ordinary local variable (it is destroyed when the function returns). Safe choices are the address of a static variable, of dynamically allocated memory (malloc), or of a variable/array passed in from the caller.

#include <stdio.h>

int *larger(int *x, int *y)
{
    if (*x > *y)
        return x;
    else
        return y;
}

int main()
{
    int a = 15, b = 40;
    int *p;

    p = larger(&a, &b);
    printf("Larger value = %d\n", *p);
    return 0;
}

Output: Larger value = 40. Here the function returns a pointer to one of the caller's variables, which is still alive in main().

Example with dynamic memory:

int *create(int n)
{
    int *arr = (int *)malloc(n * sizeof(int));
    return arr;          /* heap memory remains valid */
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Explain different file I/O functions with example.

Answer

File I/O

A file stores data permanently on disk. In C a file is handled through a pointer of type FILE *, and the functions are declared in <stdio.h>.

Opening and closing

  • fp = fopen("data.txt", "w"); opens a file. Modes: "r" read, "w" write (creates or truncates), "a" append, "r+", "w+", "a+" for both; add b for binary files. It returns NULL if opening fails.
  • fclose(fp); closes the file.

Character I/O

  • fputc(ch, fp) writes a character; fgetc(fp) reads a character (returns EOF at the end).

String I/O

  • fputs(str, fp) writes a string; fgets(str, n, fp) reads a line.

Formatted I/O

  • fprintf(fp, "format", args) and fscanf(fp, "format", &args) work like printf and scanf on a file.

Block (binary) I/O

  • fwrite(&ptr, size, count, fp) and fread(&ptr, size, count, fp) write or read whole structures.

Random access

  • fseek(fp, offset, origin) moves to a position (origin is SEEK_SET, SEEK_CUR or SEEK_END), ftell(fp) returns the current position, rewind(fp) goes to the start, and feof(fp) tests for end of file.

Example

#include <stdio.h>

int main()
{
    FILE *fp;
    char name[30];
    int roll;

    fp = fopen("student.txt", "w");
    if (fp == NULL) {
        printf("Cannot open file\n");
        return 1;
    }
    fprintf(fp, "%s %d\n", "Ram", 12);
    fclose(fp);

    fp = fopen("student.txt", "r");
    fscanf(fp, "%s %d", name, &roll);
    printf("Name = %s, Roll = %d\n", name, roll);
    fclose(fp);
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Write a program to draw a circle using graphics function

Answer

Graphics in Turbo C are provided by <graphics.h>. initgraph() switches to graphics mode, circle(x, y, r) draws a circle with centre (x,y)(x, y) and radius rr in pixels, and closegraph() returns to text mode.

#include <stdio.h>
#include <conio.h>
#include <graphics.h>

int main()
{
    int gd = DETECT, gm;

    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");   /* path of BGI drivers */

    setcolor(RED);
    circle(200, 150, 80);     /* centre (200,150), radius 80 */

    getch();
    closegraph();
    return 0;
}

DETECT makes the system choose the best available graphics driver and mode. The path in initgraph must point to the folder containing the .BGI files.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Write short notes On
  • Compilation and execution
  • Operator precedence and associativity

Answer

(a) Compilation and execution

A C program passes through the following stages before it runs.

  1. Editing: the source code is written and saved as prog.c.
  2. Preprocessing: the preprocessor handles directives such as #include and #define, removes comments and expands macros.
  3. Compilation: the compiler checks syntax and translates the code into assembly/object code. Syntax errors are reported here, and the output is prog.obj (or prog.o).
  4. Linking: the linker combines the object file with library functions (such as printf from the standard library) to produce an executable file (prog.exe). Undefined references are reported here.
  5. Loading and execution: the loader places the executable into memory and the CPU executes it. Run-time (logical) errors such as division by zero appear here.

Flow: source file -> preprocessor -> compiler -> object file -> linker (with libraries) -> executable -> output.

With gcc: gcc prog.c -o prog compiles and links, and ./prog runs it.

(b) Operator precedence and associativity

Precedence decides which operator is evaluated first in an expression with different operators; associativity decides the order when operators have the same precedence.

Precedence (high to low)OperatorsAssociativity
1() [] . -> postfix ++ --Left to right
2unary + - ! ~ prefix ++ -- * & sizeof castsRight to left
3* / %Left to right
4+ -Left to right
5<< >>Left to right
6< <= > >=Left to right
7== !=Left to right
8& then ^ then |Left to right
9&& then ||Left to right
10?:Right to left
11= += -= etc.Right to left
12,Left to right

Example: in x = 2 + 3 * 4, * has higher precedence, so the value is 2+12=142 + 12 = 14. In a = b = 5, assignment is right to left, so b = 5 is done first. In 10 - 4 - 3 the result is (10−4)−3=3(10-4)-3 = 3 because - is left to right.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 10 marks

What do you mean by jump statement? Explain each jump statement with example. Write a program to check whether a number entered is prime or not.

Answer

Jump statements

Jump statements transfer control unconditionally from one point of a program to another. C has four: break, continue, goto and return.

(a) break terminates the nearest enclosing loop or switch and passes control to the statement after it.

for (i = 1; i <= 10; i++) {
    if (i == 5)
        break;
    printf("%d ", i);      /* prints 1 2 3 4 */
}

(b) continue skips the rest of the current iteration and goes to the next iteration of the loop.

for (i = 1; i <= 5; i++) {
    if (i == 3)
        continue;
    printf("%d ", i);      /* prints 1 2 4 5 */
}

(c) goto transfers control to a labelled statement in the same function.

    i = 1;
loop:
    printf("%d ", i);
    i++;
    if (i <= 3)
        goto loop;         /* prints 1 2 3 */

(d) return ends the execution of a function and optionally sends a value back to the caller.

int square(int x)
{
    return x * x;
}

Program to check whether a number is prime

#include <stdio.h>

int main()
{
    int n, i, isPrime = 1;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n <= 1)
        isPrime = 0;
    for (i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            isPrime = 0;
            break;
        }
    }

    if (isPrime)
        printf("%d is a prime number\n", n);
    else
        printf("%d is not a prime number\n", n);
    return 0;
}

For n=29n = 29 no divisor from 2 to 5 is found, so it is prime; for n=21n = 21, 21 mod 3=021 \bmod 3 = 0, so it is not.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 10 marks

Explain any three string functions. Write a program to check if two matrices are identical or act.

Answer

String functions (declared in <string.h>)

(a) strlen(s) returns the number of characters in s, not counting the terminating '\0'.

int n = strlen("Nepal");        /* n = 5 */

(b) strcpy(dest, src) copies the string src (including '\0') into dest.

char a[20];
strcpy(a, "Kathmandu");         /* a = "Kathmandu" */

(c) strcmp(s1, s2) compares two strings alphabetically. It returns 0 if they are equal, a negative value if s1 < s2 and a positive value if s1 > s2.

strcmp("apple", "apple");       /* 0 */
strcmp("apple", "banana");      /* negative */

Other useful functions are strcat(s1, s2) (appends s2 to s1), strrev and strupr/strlwr (non-standard).

Program to check whether two matrices are identical

Two matrices are identical if they have the same order and all corresponding elements are equal.

#include <stdio.h>

int main()
{
    int a[10][10], b[10][10];
    int r1, c1, r2, c2, i, j, same = 1;

    printf("Enter rows and columns of first matrix: ");
    scanf("%d %d", &r1, &c1);
    printf("Enter rows and columns of second matrix: ");
    scanf("%d %d", &r2, &c2);

    if (r1 != r2 || c1 != c2) {
        printf("Matrices are not identical (different order)\n");
        return 0;
    }

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

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

    for (i = 0; i < r1 && same; i++)
        for (j = 0; j < c1; j++)
            if (a[i][j] != b[i][j]) {
                same = 0;
                break;
            }

    if (same)
        printf("The matrices are identical\n");
    else
        printf("The matrices are not identical\n");
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 10 marks

Define structure. Explain nested structure with example. Create a structure named book with name, author, and publisher as its members. Write a program using this structure to read data of 50 books and display name of those books published by “XYX” publisher.

Answer

Structure

A structure is a user-defined data type that groups related variables of different types under a single name. Its variables are called members and are accessed with the dot operator (.), or the arrow operator (->) through a pointer.

struct student {
    char name[20];
    int roll;
};
struct student s1 = {"Sita", 5};
printf("%s", s1.name);

Nested structure

A structure that contains another structure as a member is a nested structure. It is used when data naturally has sub-parts, for example a date inside a student record.

#include <stdio.h>

struct date {
    int day, month, year;
};

struct employee {
    char name[20];
    struct date dob;          /* nested structure */
    float salary;
};

int main()
{
    struct employee e = {"Hari", {5, 8, 1999}, 45000.0};
    printf("%s was born on %d/%d/%d\n", e.name, e.dob.day, e.dob.month, e.dob.year);
    return 0;
}

Output: Hari was born on 5/8/1999. Inner members are reached by chaining the dot operator (e.dob.day).

Program for 50 books

#include <stdio.h>
#include <string.h>

struct book {
    char name[50];
    char author[30];
    char publisher[30];
};

int main()
{
    struct book b[50];
    int i, found = 0;

    for (i = 0; i < 50; i++) {
        printf("Enter data of book %d\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", b[i].name);
        printf("Author: ");
        scanf(" %[^\n]", b[i].author);
        printf("Publisher: ");
        scanf(" %[^\n]", b[i].publisher);
    }

    printf("\nBooks published by XYX:\n");
    for (i = 0; i < 50; i++) {
        if (strcmp(b[i].publisher, "XYX") == 0) {
            printf("%s\n", b[i].name);
            found = 1;
        }
    }
    if (!found)
        printf("No book found\n");
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

What is variable? How is it different from constant? How do you write comments in c?

Answer

Variable

A variable is a named memory location used to store a value that can change during program execution. It must be declared with a data type before use, for example int count = 0;. Rules for names: letters, digits and underscore only, must not start with a digit, must not be a keyword, and are case sensitive.

Variable vs constant

BasisVariableConstant
ValueCan change during executionFixed; cannot change once defined
Declarationint x = 5;const int x = 5; or #define PI 3.14159
Assignmentx = 10; is allowedx = 10; gives a compile error
MemoryHas a memory location whose content changesconst has a location but is read-only; #define is replaced by the preprocessor
Examplemarks, total3.14, 'A', "Nepal"

Comments in C

Comments are notes ignored by the compiler that make a program easier to understand.

  • Single line (C99 and later): // this is a comment
  • Multi line: /* this is a comment that can span several lines */
int a = 5;      // a stores the first number
/* The following loop
   prints numbers 1 to 5 */

Multi-line comments cannot be nested.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain formatted I/O functions in detail.

Answer

Formatted I/O functions

Formatted I/O functions read or print data in a specified format using format specifiers. They are declared in <stdio.h>.

printf() writes formatted output to the screen.

Syntax: printf("control string", argument list);

scanf() reads formatted input from the keyboard. Arguments must be addresses (&), except for strings.

Syntax: scanf("control string", &var1, &var2, ...);

Format specifiers

SpecifierMeaning
%d / %isigned integer
%uunsigned integer
%ffloat
%lfdouble (in scanf)
%ccharacter
%sstring
%x / %ohexadecimal / octal
%eexponential form
%ldlong integer

Field width and precision

  • %5d prints an integer in a field 5 characters wide (right aligned); %-5d left aligns.
  • %.2f prints 2 digits after the decimal point; %8.3f uses width 8 with 3 decimals.
#include <stdio.h>
int main()
{
    int age;
    float height;
    char name[20];

    printf("Enter name, age and height: ");
    scanf("%s %d %f", name, &age, &height);
    printf("Name: %s\nAge: %5d\nHeight: %.2f\n", name, age, height);
    return 0;
}

Related functions: fprintf()/fscanf() for files and sprintf()/sscanf() for strings.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write a program using your own function to find sum of two numbers

Answer

#include <stdio.h>

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

int main()
{
    int x, y, total;

    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);

    total = sum(x, y);
    printf("Sum = %d\n", total);
    return 0;
}

The user-defined function sum() takes two integer parameters, adds them and returns the result to main(). For input 12 8 the output is Sum = 20.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write a program to print largest among three numbers entered by the user.

Answer

#include <stdio.h>

int main()
{
    float a, b, c, largest;

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

    if (a >= b && a >= c)
        largest = a;
    else if (b >= a && b >= c)
        largest = b;
    else
        largest = c;

    printf("Largest number = %.2f\n", largest);
    return 0;
}

For input 12 45 30: a≥ba \ge b is false; b≥ab \ge a and b≥cb \ge c are true, so the output is Largest number = 45.00.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain dynamic memory allocation with example

Answer

Dynamic memory allocation

Dynamic memory allocation means allocating memory at run time from the heap, so the size need not be known at compile time and the memory can be released when no longer needed. The functions are in <stdlib.h>.

FunctionPurpose
malloc(size)Allocates size bytes; memory is uninitialised; returns void * (or NULL on failure)
calloc(n, size)Allocates n blocks of size bytes, all initialised to 0
realloc(ptr, newsize)Changes the size of a previously allocated block
free(ptr)Releases the memory so it can be reused

Example: sum of nn numbers using malloc

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, i, sum = 0;
    int *p;

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

    p = (int *)malloc(n * sizeof(int));
    if (p == NULL) {
        printf("Memory not available\n");
        return 1;
    }

    for (i = 0; i < n; i++) {
        scanf("%d", p + i);
        sum += *(p + i);
    }
    printf("Sum = %d\n", sum);

    free(p);
    return 0;
}

For n = 3 and values 4 5 6, the output is Sum = 15. Every allocated block should be freed to avoid memory leaks.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write a program that simply reads data from a file

Answer

The program opens an existing text file in read mode, reads it character by character until EOF and displays the content.

#include <stdio.h>

int main()
{
    FILE *fp;
    char ch;

    fp = fopen("data.txt", "r");
    if (fp == NULL) {
        printf("File cannot be opened\n");
        return 1;
    }

    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);

    fclose(fp);
    return 0;
}

fopen() returns NULL if the file does not exist, which is checked before reading. fgetc() returns EOF at the end of the file, and fclose() releases the file.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write a program to draw a line using graphics function.

Answer

Using <graphics.h> (Turbo C / WinBGIm), line(x1, y1, x2, y2) draws a line from the point (x1,y1)(x_1, y_1) to (x2,y2)(x_2, y_2).

#include <stdio.h>
#include <conio.h>
#include <graphics.h>

int main()
{
    int gd = DETECT, gm;

    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

    setcolor(YELLOW);
    line(100, 100, 300, 200);     /* from (100,100) to (300,200) */

    getch();
    closegraph();
    return 0;
}

initgraph() starts graphics mode, getch() holds the screen until a key is pressed, and closegraph() restores text mode.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write short notes on:
  • History of C
  • Bitwise Operator

Answer

(a) History of C

  • C was developed by Dennis Ritchie at Bell Laboratories (AT&T) in 1972, mainly to rewrite the UNIX operating system.
  • It evolved from the language B (Ken Thompson, 1970), which came from BCPL (Martin Richards, 1967), which in turn derived from ALGOL 60 (1960).
  • In 1978 Brian Kernighan and Dennis Ritchie published The C Programming Language, giving the "K&R C" standard.
  • In 1989 ANSI standardised the language (ANSI C / C89), adopted by ISO as C90.
  • Later revisions are C99, C11 and C17.
  • C is a middle-level, structured, portable and efficient language, and it influenced C++, Java and many other languages.

(b) Bitwise operators

Bitwise operators work on the individual bits of integer operands.

OperatorNameRule
&AND1 if both bits are 1
|OR1 if at least one bit is 1
^XOR1 if the bits differ
~NOT (complement)flips every bit
<<Left shiftshifts bits left; multiplies by 2n2^n
>>Right shiftshifts bits right; divides by 2n2^n

Example with a=12a = 12 (1100) and b=10b = 10 (1010):

  • a & b=1000=8a \,\&\, b = 1000 = 8
  • a ∣ b=1110=14a \,|\, b = 1110 = 14
  • a ∧ b=0110=6a \,\wedge\, b = 0110 = 6
  • a≪1=11000=24a \ll 1 = 11000 = 24
  • a≫2=0011=3a \gg 2 = 0011 = 3
printf("%d %d %d %d %d", a & b, a | b, a ^ b, a << 1, a >> 2);   /* 8 14 6 24 3 */

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 10 marks

What is the difference between exit(0) and exit(1)? Discuss the need of nested structue with an example. Write a program to find the value of x^y without using POW code.

Answer

exit(0) vs exit(1)

exit() (in <stdlib.h>) terminates the whole program immediately, flushes buffers and closes open files. The argument is the exit status returned to the operating system.

Basisexit(0)exit(1)
MeaningSuccessful (normal) terminationAbnormal termination / error
ConstantEXIT_SUCCESSEXIT_FAILURE
UseProgram finished its work correctlyA failure occurred, e.g. file could not be opened
fp = fopen("a.txt", "r");
if (fp == NULL)
    exit(1);       /* report failure */

Need for nested structure

A nested structure is a structure that has another structure as a member. It is needed when a record is made of logically separate groups of data. It avoids repeating members, keeps related data together, makes the program readable and lets the inner structure be reused (for example date in student, employee and book).

#include <stdio.h>

struct date {
    int day, month, year;
};

struct student {
    char name[20];
    int roll;
    struct date dob;        /* nested structure */
};

int main()
{
    struct student s = {"Gita", 7, {12, 3, 2003}};
    printf("%s (roll %d) born on %d/%d/%d\n", s.name, s.roll,
           s.dob.day, s.dob.month, s.dob.year);
    return 0;
}

Output: Gita (roll 7) born on 12/3/2003.

Program for xyx^y without pow()

For a non-negative integer yy, xy=x×x×⋯×xx^y = x \times x \times \dots \times x (yy times). For a negative yy, xy=1/x∣y∣x^y = 1/x^{|y|}.

#include <stdio.h>

int main()
{
    double x, result = 1.0;
    int y, i, n;

    printf("Enter x and y: ");
    scanf("%lf %d", &x, &y);

    n = (y < 0) ? -y : y;
    for (i = 1; i <= n; i++)
        result = result * x;

    if (y < 0)
        result = 1.0 / result;

    printf("%g ^ %d = %g\n", x, y, result);
    return 0;
}

For x=2x = 2, y=5y = 5: 25=322^5 = 32. For x=2x = 2, y=−2y = -2: 1/4=0.251/4 = 0.25.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 10 marks

Why do we need a break and continue statement? Define formal argument and actual argument in function with examples. Identify and list the errors in the following code. int main(){ int a,b,c scanf("%d%d%d, &a, &b, &c); sum(a, b, c); return -1; } void sum(int x, int y, int z){ int sum; sum = a + b + c; return sum; }

Answer

Need of break and continue

  • break terminates the nearest enclosing loop or switch immediately. It is needed to leave a loop early when a condition is met (for example, when a search finds the item or a divisor is found), and to stop fall-through between case labels in a switch.
  • continue skips the remaining statements of the current iteration and starts the next iteration. It is needed to ignore unwanted values without leaving the loop (for example, skipping negative numbers while summing).
for (i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue;   /* skip even numbers */
    if (i > 7) break;           /* stop after 7 */
    printf("%d ", i);           /* 1 3 5 7 */
}

Formal and actual arguments

  • Formal arguments (parameters) are the variables listed in the function definition. They receive the values when the function is called and exist only inside the function.
  • Actual arguments are the values or variables written in the function call. They supply the values for the formal arguments.
int add(int x, int y)          /* x, y: formal arguments */
{
    return x + y;
}
int main()
{
    int a = 3, b = 4;
    printf("%d", add(a, b));   /* a, b: actual arguments */
    return 0;
}

Their number, order and types must match.

Errors in the given code

  1. int a,b,c is missing the terminating semicolon.
  2. In scanf("%d%d%d, &a, &b, &c); the closing double quote is misplaced. It should be scanf("%d%d%d", &a, &b, &c);.
  3. The function sum() is called before it is defined and no prototype is declared. Add void sum(int, int, int); (or int sum(int, int, int);) before main().
  4. return -1; in main() indicates failure. A normal program should return 0;.
  5. sum is declared void but contains return sum;, which returns a value from a void function. The return type should be int.
  6. Inside sum(), a, b and c are undeclared (they are local to main()). It should use the formal arguments: sum = x + y + z;.
  7. A local variable named sum has the same name as the function, which is confusing and should be renamed (for example total).
  8. In main() the returned value of sum(a, b, c) is ignored, so nothing is printed. It should be stored or printed.

Corrected code

#include <stdio.h>

int sum(int x, int y, int z);

int main()
{
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    printf("Sum = %d\n", sum(a, b, c));
    return 0;
}

int sum(int x, int y, int z)
{
    int total;
    total = x + y + z;
    return total;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 10 marks

Write a program to demonstrate the following menu-driven program. The user will provide an integer and alphabet for making choice and the corresponding task has to be performed according as follow:
  • Find Odd or Even
  • Find Positive or Negative
  • Find the Factorial value
  • Exit The choice will be displayed until the user will give “D” as a choice.

Answer

The program shows the menu repeatedly and reads a choice character. For choices A, B and C it asks for an integer and performs the task; the loop ends when the user enters D (Exit). Both upper and lower case are accepted.

Menu: A Odd or Even, B Positive or Negative, C Factorial, D Exit.

#include <stdio.h>

int main()
{
    char choice;
    int n, i;
    unsigned long long fact;

    do {
        printf("\n----- MENU -----\n");
        printf("A. Find Odd or Even\n");
        printf("B. Find Positive or Negative\n");
        printf("C. Find the Factorial value\n");
        printf("D. Exit\n");
        printf("Enter your choice: ");
        scanf(" %c", &choice);

        switch (choice) {
        case 'A':
        case 'a':
            printf("Enter an integer: ");
            scanf("%d", &n);
            if (n % 2 == 0)
                printf("%d is Even\n", n);
            else
                printf("%d is Odd\n", n);
            break;

        case 'B':
        case 'b':
            printf("Enter an integer: ");
            scanf("%d", &n);
            if (n > 0)
                printf("%d is Positive\n", n);
            else if (n < 0)
                printf("%d is Negative\n", n);
            else
                printf("Zero is neither positive nor negative\n");
            break;

        case 'C':
        case 'c':
            printf("Enter an integer: ");
            scanf("%d", &n);
            if (n < 0)
                printf("Factorial is not defined for negative numbers\n");
            else {
                fact = 1;
                for (i = 1; i <= n; i++)
                    fact *= i;
                printf("%d! = %llu\n", n, fact);
            }
            break;

        case 'D':
        case 'd':
            printf("Exiting program...\n");
            break;

        default:
            printf("Invalid choice, try again\n");
        }
    } while (choice != 'D' && choice != 'd');

    return 0;
}

Sample run: choice A with 7 prints 7 is Odd; choice C with 5 prints 5! = 120; choice D ends the program. (Factorial values fit in unsigned long long up to n=20n = 20.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

How do you swap the values of two integers without using the third temporary variable? Justify with the example.

Answer

Two integers can be swapped without a third variable by using arithmetic operations or the bitwise XOR operator.

Method 1: using addition and subtraction

Let a=10a = 10 and b=20b = 20.

  1. a=a+ba = a + b gives a=30a = 30
  2. b=a−bb = a - b gives b=30−20=10b = 30 - 20 = 10
  3. a=a−ba = a - b gives a=30−10=20a = 30 - 10 = 20

After the three steps a=20a = 20 and b=10b = 10, so the values are swapped.

#include <stdio.h>

int main() {
    int a = 10, b = 20;
    printf("Before swap: a = %d, b = %d\n", a, b);

    a = a + b;
    b = a - b;
    a = a - b;

    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}

Output:

Before swap: a = 10, b = 20
After swap: a = 20, b = 10

Method 2: using bitwise XOR

a = a ^ b;
b = a ^ b;   /* (a^b)^b = a */
a = a ^ b;   /* (a^b)^a = b */

This works because x⊕x=0x \oplus x = 0 and x⊕0=xx \oplus 0 = x. For a=10a = 10 (1010) and b=20b = 20 (10100): a=11110a = 11110 (30), b=11110⊕10100=01010b = 11110 \oplus 10100 = 01010 (10), a=11110⊕01010=10100a = 11110 \oplus 01010 = 10100 (20).

The addition method can overflow for very large values, whereas XOR cannot.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Write a program to find the sum of digits of a given integer using recursion.

Answer

The sum of digits of nn is the last digit n mod 10n \bmod 10 plus the sum of digits of n/10n/10. The base case is n=0n = 0, where the sum is 0.

#include <stdio.h>

int sumDigits(int n) {
    if (n == 0)
        return 0;
    return (n % 10) + sumDigits(n / 10);
}

int main() {
    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);
    if (n < 0)
        n = -n;
    printf("Sum of digits = %d\n", sumDigits(n));
    return 0;
}

Trace for n=123n = 123:

sumDigits(123)=3+sumDigits(12)=3+2+sumDigits(1)=3+2+1+sumDigits(0)=6\text{sumDigits}(123) = 3 + \text{sumDigits}(12) = 3 + 2 + \text{sumDigits}(1) = 3 + 2 + 1 + \text{sumDigits}(0) = 6

Output for input 123: Sum of digits = 6.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Differentiate between constant and literals. Why do we need to define the type of data?

Answer

Constant versus literal

ConstantLiteral
A named value that cannot be changed after it is defined, e.g. const float PI = 3.14; or #define MAX 100.A fixed value written directly in the source code, e.g. 10, 3.14, 'A', "Nepal".
It has a name (identifier) and is stored in memory (or substituted by the preprocessor).It has no name; it is the raw value itself.
It can be used many times by its name, and changing its definition updates every use.Each occurrence is typed separately.
Example: const int age = 18;Here 18 is the literal and age is the constant.

So a literal is the value, whereas a constant is a named object whose value is a literal and is protected from modification.

Why the type of data must be defined

  1. The type tells the compiler how much memory to reserve (char 1 byte, int usually 4 bytes, double 8 bytes).
  2. It determines how the stored bits are interpreted (as an integer, a floating-point number or a character).
  3. It decides which operations are valid (e.g. % is not allowed on float) and how expressions are evaluated.
  4. It fixes the range of values that can be stored, and lets the compiler detect type errors at compile time.
  5. It allows correct input and output formatting, such as %d and %f.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Write a program to find the second largest number in the given array of numbers.

Answer

The program scans the array once, keeping the largest and second largest values seen so far.

#include <stdio.h>
#include <limits.h>

int main() {
    int n, i, a[100];
    int largest, second;

    printf("Enter number of elements: ");
    scanf("%d", &n);
    if (n < 2) {
        printf("At least two elements are required.\n");
        return 0;
    }

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

    largest = second = INT_MIN;
    for (i = 0; i < n; i++) {
        if (a[i] > largest) {
            second = largest;
            largest = a[i];
        } else if (a[i] > second && a[i] != largest) {
            second = a[i];
        }
    }

    if (second == INT_MIN)
        printf("No second largest element (all elements are equal).\n");
    else
        printf("Second largest = %d\n", second);
    return 0;
}

Example: for 12 35 1 10 34 1, the largest becomes 35 and the second largest 34, so the output is Second largest = 34.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Create a structure “Employee” having Name, Address, Salary, and Age as member functions. Display the name of the employee having aged between 40 and 50 are living in Kathmandu.

Answer

#include <stdio.h>
#include <string.h>

struct Employee {
    char name[50];
    char address[50];
    float salary;
    int age;
};

int main() {
    struct Employee e[100];
    int n, i, found = 0;

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

    for (i = 0; i < n; i++) {
        printf("\nEmployee %d\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", e[i].name);
        printf("Address: ");
        scanf(" %[^\n]", e[i].address);
        printf("Salary: ");
        scanf("%f", &e[i].salary);
        printf("Age: ");
        scanf("%d", &e[i].age);
    }

    printf("\nEmployees aged between 40 and 50 living in Kathmandu:\n");
    for (i = 0; i < n; i++) {
        if (e[i].age >= 40 && e[i].age <= 50 &&
            strcmp(e[i].address, "Kathmandu") == 0) {
            printf("%s\n", e[i].name);
            found = 1;
        }
    }
    if (!found)
        printf("No such employee found.\n");
    return 0;
}

The members name, address, salary and age are data members of the structure (C structures cannot hold member functions). The condition combines the age range and a strcmp check on the address.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

List any one advantage and disadvantage of the pointer. How do you pass pointers as function arguments?

Answer

Advantage of pointers: They allow direct access to memory addresses, which makes dynamic memory allocation, linked data structures (lists, trees) and efficient array and string handling possible. Passing a pointer to a function avoids copying large data.

Disadvantage of pointers: They are error-prone. An uninitialized, dangling or out-of-range pointer can corrupt memory or crash the program, and memory leaks occur if dynamically allocated memory is not freed.

Passing pointers as function arguments

The address of the variable is passed with the & operator, and the function parameter is declared as a pointer. The function uses the dereference operator * to read or change the original variable (call by reference).

#include <stdio.h>

void increment(int *p) {
    *p = *p + 1;
}

int main() {
    int x = 5;
    increment(&x);
    printf("x = %d\n", x);   /* prints 6 */
    return 0;
}

Here &x is copied into p, so *p refers to the same memory as x and the change is visible in main. Arrays are passed the same way because the array name is the address of its first element.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Suppose a file named “Num.txt” contains a list of integers. Write a program to extract the prime numbers only from that file and write them on “Prime.txt” file.

Answer

#include <stdio.h>

int isPrime(int n) {
    int i;
    if (n < 2)
        return 0;
    for (i = 2; i * i <= n; i++)
        if (n % i == 0)
            return 0;
    return 1;
}

int main() {
    FILE *fin, *fout;
    int num;

    fin = fopen("Num.txt", "r");
    if (fin == NULL) {
        printf("Cannot open Num.txt\n");
        return 1;
    }
    fout = fopen("Prime.txt", "w");
    if (fout == NULL) {
        printf("Cannot open Prime.txt\n");
        fclose(fin);
        return 1;
    }

    while (fscanf(fin, "%d", &num) == 1) {
        if (isPrime(num))
            fprintf(fout, "%d\n", num);
    }

    fclose(fin);
    fclose(fout);
    printf("Prime numbers written to Prime.txt\n");
    return 0;
}

If Num.txt contains 4 7 10 13 15 17, then Prime.txt will contain 7, 13 and 17, each on its own line.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

What is the advantage of the union over structure? List any four-string library functions with the prototype.

Answer

Advantage of union over structure

In a structure every member has its own memory, so the size is the sum of all member sizes. In a union all members share the same memory location, so its size equals the size of the largest member. Hence a union saves memory when only one member is needed at a time.

struct S { int i; float f; char c; };   /* about 4 + 4 + 1 (plus padding) bytes */
union  U { int i; float f; char c; };   /* 4 bytes */

Four string library functions (header <string.h>)

FunctionPrototypePurpose
strlensize_t strlen(const char *s);Returns the length of the string (without \0).
strcpychar *strcpy(char *dest, const char *src);Copies src into dest.
strcatchar *strcat(char *dest, const char *src);Appends src to the end of dest.
strcmpint strcmp(const char *s1, const char *s2);Compares two strings; returns 0 if equal, negative if s1 < s2, positive if s1 > s2.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Write short notes on
  • Local, Global, and Static variables
  • Conditional Operator

Answer

Local, global and static variables

  • Local variable: Declared inside a function or block. It is visible only there, is created when the block is entered and destroyed when it exits, and holds garbage if not initialized.
  • Global variable: Declared outside all functions. It is visible to every function in the file after its declaration, lives for the whole program run, and is initialized to 0 by default.
  • Static variable: Declared with the keyword static. A static local variable is visible only inside its function but keeps its value between calls. It is initialized only once, and defaults to 0.
#include <stdio.h>

int g = 10;                 /* global */

void counter() {
    static int count = 0;   /* static: retains value */
    int temp = 0;           /* local: reset on every call */
    count++;
    temp++;
    printf("count = %d, temp = %d, g = %d\n", count, temp, g);
}

int main() {
    counter();   /* count = 1, temp = 1 */
    counter();   /* count = 2, temp = 1 */
    return 0;
}

Conditional operator (?:)

It is the only ternary operator in C and is a shorthand for if-else.

variable=condition  ?  expression1:expression2;\text{variable} = \text{condition} \; ? \; \text{expression1} : \text{expression2};

If the condition is true, expression1 is evaluated; otherwise expression2. Example: max = (a > b) ? a : b; stores the larger of a and b.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

Define structure and nested structure. Write a program to find out whether the nth term of the Fibonacci series is a prime number or not. Read the value of n from the user and display the result in the main function. Uses separate user-defined function to generate the nth Fibonacci term and to check whether that number is prime or not.

Answer

Structure: A structure is a user-defined data type that groups variables of different data types under a single name, declared with the struct keyword.

struct Student {
    int roll;
    char name[30];
    float marks;
};

Nested structure: A structure that contains another structure as one of its members.

struct Date { int day, month, year; };

struct Student {
    int roll;
    char name[30];
    struct Date dob;      /* nested structure */
};

The inner members are accessed with repeated dot operators, e.g. s.dob.year.

Program: is the nth Fibonacci term prime?

The series is taken as F1=1, F2=1, Fn=Fn−1+Fn−2F_1 = 1,\ F_2 = 1,\ F_n = F_{n-1} + F_{n-2}, so it runs 1, 1, 2, 3, 5, 8, 13, 21, ...

#include <stdio.h>

long fibonacci(int n) {
    long a = 1, b = 1, c;
    int i;
    if (n <= 2)
        return 1;
    for (i = 3; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }
    return b;
}

int isPrime(long num) {
    long i;
    if (num < 2)
        return 0;
    for (i = 2; i * i <= num; i++)
        if (num % i == 0)
            return 0;
    return 1;
}

int main() {
    int n;
    long term;

    printf("Enter the value of n: ");
    scanf("%d", &n);

    term = fibonacci(n);
    if (isPrime(term))
        printf("The %dth Fibonacci term %ld is a prime number.\n", n, term);
    else
        printf("The %dth Fibonacci term %ld is not a prime number.\n", n, term);
    return 0;
}

Examples: n=7n = 7 gives F7=13F_7 = 13, which is prime. n=8n = 8 gives F8=21=3×7F_8 = 21 = 3 \times 7, which is not prime. The reading of nn and the printing of the result are done in main, while fibonacci() generates the term and isPrime() tests it.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

Explain the relation to array and pointer. Differentiate call by value and call by reference with a suitable program.

Answer

Relation between array and pointer

  • The name of an array is a constant pointer to its first element: for int a[5], a is the same as &a[0].
  • Element access a[i] is equivalent to *(a + i), and &a[i] is equivalent to a + i. Pointer arithmetic moves in units of the element size.
  • An array pointer can be stored in a pointer variable, int *p = a;, and then p[i] and *(p + i) access the elements.
  • Differences: the array name cannot be reassigned (a++ is illegal) while a pointer variable can be (p++), and sizeof(a) gives the whole array size while sizeof(p) gives the pointer size.
  • When an array is passed to a function, only the address of its first element is passed.
#include <stdio.h>

int main() {
    int a[5] = {10, 20, 30, 40, 50}, i;
    int *p = a;
    for (i = 0; i < 5; i++)
        printf("%d %d %d\n", a[i], *(a + i), *(p + i));
    return 0;
}

Call by value versus call by reference

Call by valueCall by reference
Copies of the actual arguments are passed.Addresses of the actual arguments are passed.
Changes in the function do not affect the original variables.Changes affect the original variables.
Needs separate memory for the copies.Works on the same memory through pointers.
Parameters are ordinary variables.Parameters are pointers.
#include <stdio.h>

void swapValue(int x, int y) {
    int t = x; x = y; y = t;
}

void swapRef(int *x, int *y) {
    int t = *x; *x = *y; *y = t;
}

int main() {
    int a = 5, b = 10;
    swapValue(a, b);
    printf("After call by value: a = %d, b = %d\n", a, b);     /* 5 10 */
    swapRef(&a, &b);
    printf("After call by reference: a = %d, b = %d\n", a, b); /* 10 5 */
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

Differentiate between source code and object code. Create a structure named Book with members Book_Name, Price and Author_Name, then take input for 10 records of Book and print the name of authors having the price of book greater than 1000.

Answer

Source code versus object code

Source codeObject code
Human-readable program written in a high-level language such as C (.c file).Machine-level (binary) code produced by the compiler (.obj or .o file).
Written by the programmer.Generated by the compiler from the source code.
Can be read and edited with a text editor.Not readable by humans and cannot be edited directly.
Not directly executable.Closer to executable; the linker combines it with libraries to make the executable file.

Program

#include <stdio.h>

struct Book {
    char Book_Name[50];
    float Price;
    char Author_Name[50];
};

int main() {
    struct Book b[10];
    int i, found = 0;

    for (i = 0; i < 10; i++) {
        printf("\nRecord %d\n", i + 1);
        printf("Book name: ");
        scanf(" %[^\n]", b[i].Book_Name);
        printf("Price: ");
        scanf("%f", &b[i].Price);
        printf("Author name: ");
        scanf(" %[^\n]", b[i].Author_Name);
    }

    printf("\nAuthors of books priced above 1000:\n");
    for (i = 0; i < 10; i++) {
        if (b[i].Price > 1000) {
            printf("%s\n", b[i].Author_Name);
            found = 1;
        }
    }
    if (!found)
        printf("No book costs more than 1000.\n");
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Describe the different types of I/O functions used in file handling with syntax.

Answer

File I/O functions are declared in <stdio.h> and work through a FILE pointer obtained with fopen().

Opening and closing

  • FILE *fopen(const char *filename, const char *mode); opens a file. Modes include "r" (read), "w" (write, truncate), "a" (append), "r+", "w+", "a+", and b for binary. It returns NULL on failure.
  • int fclose(FILE *fp); closes the file.

Character I/O

  • int fgetc(FILE *fp); (or getc) reads one character; returns EOF at end of file.
  • int fputc(int ch, FILE *fp); (or putc) writes one character.

String I/O

  • char *fgets(char *str, int n, FILE *fp); reads a line of at most n−1n-1 characters.
  • int fputs(const char *str, FILE *fp); writes a string.

Formatted I/O

  • int fscanf(FILE *fp, const char *format, ...); reads formatted data.
  • int fprintf(FILE *fp, const char *format, ...); writes formatted data.

Block (binary) I/O

  • size_t fread(void *ptr, size_t size, size_t count, FILE *fp); reads count items of size bytes.
  • size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp); writes them.

Random access

  • int fseek(FILE *fp, long offset, int origin); moves the file position (origin is SEEK_SET, SEEK_CUR or SEEK_END).
  • long ftell(FILE *fp); returns the current position, and void rewind(FILE *fp); returns to the start.

Example:

FILE *fp = fopen("data.txt", "w");
fprintf(fp, "%d %s", 10, "Nepal");
fclose(fp);

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write a program to read P*Q matrix of integers and find the largest integer of each row and display it.

Answer

#include <stdio.h>

int main() {
    int a[50][50], p, q, i, j, max;

    printf("Enter number of rows (P) and columns (Q): ");
    scanf("%d %d", &p, &q);

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

    for (i = 0; i < p; i++) {
        max = a[i][0];
        for (j = 1; j < q; j++)
            if (a[i][j] > max)
                max = a[i][j];
        printf("Largest in row %d = %d\n", i + 1, max);
    }
    return 0;
}

Example: for the matrix with rows 3 9 2, 7 1 5 and 4 8 6, the output is 9, 7 and 8 for rows 1, 2 and 3.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write a program to calculate the factorial of a given number using recursion.

Answer

The factorial is defined as n!=n×(n−1)!n! = n \times (n-1)! with 0!=10! = 1, which gives a direct recursive function.

#include <stdio.h>

long factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    return n * factorial(n - 1);
}

int main() {
    int n;
    printf("Enter a non-negative integer: ");
    scanf("%d", &n);
    if (n < 0)
        printf("Factorial is not defined for negative numbers.\n");
    else
        printf("%d! = %ld\n", n, factorial(n));
    return 0;
}

For n=5n = 5: 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 = 120, so the output is 5! = 120.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write a program to check whether the entered word is pallindrome or not.

Answer

A word is a palindrome if it reads the same forwards and backwards (e.g. "madam"). The program compares the characters from both ends.

#include <stdio.h>
#include <string.h>

int main() {
    char word[100];
    int i, j, isPal = 1;

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

    for (i = 0, j = strlen(word) - 1; i < j; i++, j--) {
        if (word[i] != word[j]) {
            isPal = 0;
            break;
        }
    }

    if (isPal)
        printf("%s is a palindrome.\n", word);
    else
        printf("%s is not a palindrome.\n", word);
    return 0;
}

"madam" gives a palindrome, while "nepal" does not because n and l differ.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Trace the output #include<conio.h> #include<stdio.h> void main(){ int i =0,k; for(k=5;k>=0;k–){ i=i+k; } printf(“%d\t”,i); getch(); }

Answer

Output: 15

(The k– in the question is the decrement k--.)

Initially i=0i = 0. The loop runs for k=5,4,3,2,1,0k = 5, 4, 3, 2, 1, 0, and each iteration adds kk to ii:

ki after i = i + k
55
49
312
214
115
015

When kk becomes −1-1 the condition k >= 0 fails and the loop ends. printf("%d\t", i) then prints i=5+4+3+2+1+0=15i = 5+4+3+2+1+0 = 15 followed by a tab.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write a program to compute the sum of first 10 even numbers using function.

Answer

The first 10 even numbers are 2,4,6,…,202, 4, 6, \dots, 20, whose sum is 2(1+2+⋯+10)=2×55=1102(1 + 2 + \dots + 10) = 2 \times 55 = 110.

#include <stdio.h>

int sumEven(int count) {
    int i, sum = 0;
    for (i = 1; i <= count; i++)
        sum += 2 * i;
    return sum;
}

int main() {
    printf("Sum of first 10 even numbers = %d\n", sumEven(10));
    return 0;
}

Output: Sum of first 10 even numbers = 110.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

What is dynamic memory allocation? Explain with a suitable program.

Answer

Dynamic memory allocation is the process of allocating memory at run time from the heap, instead of fixing the size at compile time. It lets a program use exactly as much memory as needed and release it when finished. The functions are in <stdlib.h>:

FunctionPurpose
malloc(size)Allocates size bytes; memory is uninitialized.
calloc(n, size)Allocates memory for n elements of size bytes each and sets it to zero.
realloc(ptr, newsize)Changes the size of a previously allocated block.
free(ptr)Releases the memory so it can be reused.

Each allocation function returns NULL if memory is not available.

Program: store and sum n integers

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n, i, sum = 0;
    int *ptr;

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

    ptr = (int *)malloc(n * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    printf("Enter %d integers: ", n);
    for (i = 0; i < n; i++) {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
    }
    printf("Sum = %d\n", sum);

    free(ptr);
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write a program to initialize an array of dimension 10 and sort the numbers within the array in ascending order.

Answer

The program stores 10 numbers in an array and sorts them in ascending order with bubble sort.

#include <stdio.h>

int main() {
    int a[10], i, j, temp;

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

    for (i = 0; i < 9; i++) {
        for (j = 0; j < 9 - i; j++) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }

    printf("Sorted array: ");
    for (i = 0; i < 10; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Input 5 2 9 1 7 3 8 6 4 0 gives 0 1 2 3 4 5 6 7 8 9.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 10 marks

What are the characteristics of array? Write a program to input age of 500 persons and display the following
  • Average age
  • Age between 25 to 30

Answer

Characteristics of an array

  1. It is a collection of elements of the same data type stored under one name.
  2. Elements occupy contiguous memory locations.
  3. Elements are accessed by an index, and indexing starts from 0, so an array of size nn has indices 00 to n−1n-1.
  4. The size is fixed at declaration and cannot change at run time.
  5. Any element can be accessed directly (random access) in constant time.
  6. The array name represents the address of the first element.
  7. C does no bounds checking, so using an index outside the range gives undefined behaviour.

Program

#include <stdio.h>

#define N 500

int main() {
    int age[N], i, count = 0;
    long sum = 0;
    float average;

    printf("Enter the age of %d persons:\n", N);
    for (i = 0; i < N; i++) {
        scanf("%d", &age[i]);
        sum += age[i];
    }

    average = (float)sum / N;

    printf("Average age = %.2f\n", average);

    printf("Ages between 25 and 30: ");
    for (i = 0; i < N; i++) {
        if (age[i] >= 25 && age[i] <= 30) {
            printf("%d ", age[i]);
            count++;
        }
    }
    printf("\nNumber of persons aged between 25 and 30 = %d\n", count);
    return 0;
}

The average is ∑i=0499agei500\dfrac{\sum_{i=0}^{499} age_i}{500}. The second loop prints each age with 25≤age≤3025 \le age \le 30 and counts them.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 10 marks

Differentiate between library function and user defined function. Write a program to swap two values using call by refrence concept.

Answer

Library function versus user-defined function

Library functionUser-defined function
Pre-written and supplied with the compiler.Written by the programmer.
Declared in header files such as <stdio.h> and <math.h>.Declared and defined by the programmer in the program.
The programmer cannot change its definition.The programmer can modify it as needed.
Examples: printf(), scanf(), sqrt(), strlen().Examples: swap(), factorial(), isPrime().
Needs only #include of the header.Needs a prototype, a definition and a call.

Program: swap using call by reference

#include <stdio.h>

void swap(int *x, int *y) {
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

int main() {
    int a, b;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    printf("Before swap: a = %d, b = %d\n", a, b);

    swap(&a, &b);

    printf("After swap: a = %d, b = %d\n", a, b);
    return 0;
}

The addresses of a and b are passed, so swap() changes the original variables through the pointers. For input 10 20, the output after the swap is a = 20, b = 10.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Explain the basic structure of C Programming.

Answer

A C program is organised into the following sections, in order.

  1. Documentation section: Comments giving the program name, author and purpose, e.g. /* Program to add two numbers */.
  2. Link section: Preprocessor directives that include header files, e.g. #include <stdio.h>.
  3. Definition section: Symbolic constants and macros, e.g. #define PI 3.14159.
  4. Global declaration section: Variables and function prototypes declared outside all functions, visible to the whole program.
  5. main() function section: Every program starts execution here. It contains a declaration part (local variables) and an executable part (statements), enclosed in braces { }.
  6. Subprogram (user-defined function) section: Definitions of the other functions called from main().
/* Program to add two numbers */          /* documentation */
#include <stdio.h>                        /* link */
#define MSG "Sum ="                       /* definition */

int add(int, int);                        /* global declaration */

int main() {
    int a = 5, b = 7, s;                  /* declaration part */
    s = add(a, b);                        /* executable part */
    printf("%s %d\n", MSG, s);
    return 0;
}

int add(int x, int y) {                   /* subprogram section */
    return x + y;
}

Output: Sum = 12.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Describe different formatted input and output functions. Why do we use them?

Answer

Formatted I/O functions. Formatted input/output functions read or write data according to a format specification, so that the programmer controls the type, width and precision of each value. They are declared in <stdio.h>.

1. printf(): formatted output to the screen.

printf("format string", arg1, arg2, ...);

The format string contains plain text and conversion specifiers such as %d (int), %f (float), %c (char), %s (string), %ld (long), %lf (double), %x (hex). Width and precision can be given, e.g. %8.2f prints a real number in 8 columns with 2 decimal places.

2. scanf(): formatted input from the keyboard.

scanf("format string", &var1, &var2, ...);

It reads values according to the specifiers and stores them at the addresses given (hence &; no & is needed for a string stored in a char array).

3. fprintf() and fscanf(): formatted output/input for files.

fprintf(fp, "%d %s\n", roll, name);
fscanf(fp, "%d %s", &roll, name);

4. sprintf() and sscanf(): formatted output/input to or from a string in memory.

char buf[30];
sprintf(buf, "%d-%d", 12, 5);   /* buf = "12-5" */
sscanf(buf, "%d-%d", &a, &b);

Example.

#include <stdio.h>
int main()
{
    int age;
    float cgpa;
    printf("Enter age and CGPA: ");
    scanf("%d %f", &age, &cgpa);
    printf("Age = %3d, CGPA = %.2f\n", age, cgpa);
    return 0;
}

Why we use them.

  • They handle values of different data types (int, float, char, string) with one function call.
  • The output can be neatly aligned and rounded using width and precision.
  • Several values can be read or printed in a single statement.
  • The same format mechanism works for the console, files and strings.
  • They convert between the text form of data and its internal binary form automatically.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write a program to display the following series up to 25 terms but do not print the 7th term. 2 x 3, 3 x 5, 4 x 7, 5 x 9…

Answer

Pattern. The terms are 2×3, 3×5, 4×7, 5×9,…2\times3,\ 3\times5,\ 4\times7,\ 5\times9,\dots The first factor starts at 22 and increases by 11; the second starts at 33 and increases by 22. For the ii-th term:

Ti=(i+1)×(2i+1)T_i=(i+1)\times(2i+1)

Check: i=1i=1 gives 2×32\times3, i=4i=4 gives 5×95\times9. The 7th term (8×158\times15) is skipped using continue, and the loop runs to i=25i=25 (last term 26×5126\times51).

#include <stdio.h>

int main()
{
    int i;
    for (i = 1; i <= 25; i++)
    {
        if (i == 7)
            continue;               /* do not print the 7th term */
        printf("%d x %d", i + 1, 2 * i + 1);
        if (i != 25)
            printf(", ");
    }
    printf("\n");
    return 0;
}

Output.

2 x 3, 3 x 5, 4 x 7, 5 x 9, 6 x 11, 7 x 13, 9 x 17, 10 x 19, ..., 26 x 51

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Demonstrate the use of recursive function with a suitable example.

Answer

Recursive function. A function that calls itself, directly or indirectly, is a recursive function. Every recursive function needs:

  1. a base case that stops the recursion, and
  2. a recursive case that reduces the problem toward the base case.

Example: factorial. Since n!=n×(n−1)!n! = n\times(n-1)! with 0!=10! = 1:

#include <stdio.h>

long factorial(int n)
{
    if (n == 0 || n == 1)          /* base case */
        return 1;
    return n * factorial(n - 1);   /* recursive case */
}

int main()
{
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("%d! = %ld\n", n, factorial(n));
    return 0;
}

Working for n=4n=4.

fact(4)=4×fact(3)=4×3×fact(2)=4×3×2×fact(1)=4×3×2×1=24\text{fact}(4)=4\times\text{fact}(3)=4\times3\times\text{fact}(2)=4\times3\times2\times\text{fact}(1)=4\times3\times2\times1=24

The calls are pushed on the stack until the base case is reached, then they return one by one, multiplying on the way back.

Advantages: short, clear code for problems that are naturally recursive (factorial, Fibonacci, Tower of Hanoi, tree traversal). Disadvantages: uses extra stack memory and is usually slower than a loop; missing a base case causes infinite recursion and stack overflow.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Create a structure called STUDENT with data members SID, name, address, CGPA. Write a program to initialize the value of 100 students and display the information of those students whose address is “KTM” and CGPA is between 3.5 to 4. using C program

Answer

#include <stdio.h>
#include <string.h>

struct STUDENT
{
    int   SID;
    char  name[30];
    char  address[20];
    float CGPA;
};

int main()
{
    struct STUDENT s[100];
    int i;

    for (i = 0; i < 100; i++)
    {
        printf("Enter SID, name, address and CGPA of student %d:\n", i + 1);
        scanf("%d %s %s %f", &s[i].SID, s[i].name, s[i].address, &s[i].CGPA);
    }

    printf("\nStudents from KTM with CGPA between 3.5 and 4:\n");
    printf("%-6s %-20s %-10s %s\n", "SID", "Name", "Address", "CGPA");
    for (i = 0; i < 100; i++)
    {
        if (strcmp(s[i].address, "KTM") == 0 &&
            s[i].CGPA >= 3.5 && s[i].CGPA <= 4.0)
        {
            printf("%-6d %-20s %-10s %.2f\n",
                   s[i].SID, s[i].name, s[i].address, s[i].CGPA);
        }
    }
    return 0;
}

The structure STUDENT groups the four data members. An array of 100 such structures stores the records; strcmp() is used to compare the address string with "KTM" because strings cannot be compared with ==.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Explain different file opening modes.

Answer

File opening modes. A file is opened with fopen("filename", "mode"), which returns a FILE * (or NULL on failure). The mode decides what operations are allowed.

ModeMeaning
rOpen an existing text file for reading. Fails (returns NULL) if the file does not exist.
wOpen for writing. Creates the file if absent; if present, its old contents are erased.
aOpen for appending. Creates the file if absent; new data is written at the end.
r+Open an existing file for both reading and writing. File must exist; contents are kept.
w+Open for reading and writing. Creates the file or erases an existing one.
a+Open for reading and appending. Creates the file if absent; writes go to the end.

For binary files a b is added: rb, wb, ab, rb+ (or r+b), wb+, ab+.

Example.

FILE *fp = fopen("data.txt", "w");
if (fp == NULL)
{
    printf("Cannot open file\n");
    return 1;
}
fprintf(fp, "Hello");
fclose(fp);

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write a program to draw two shapes of your choice using graphics function.

Answer

The following program uses the BGI graphics library (graphics.h, Turbo C / WinBGIm) to draw a circle and a rectangle.

#include <stdio.h>
#include <graphics.h>
#include <conio.h>

int main()
{
    int gd = DETECT, gm;

    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");   /* initialise graphics mode */

    setcolor(RED);
    circle(150, 200, 60);          /* centre (150,200), radius 60 */

    setcolor(GREEN);
    rectangle(300, 140, 450, 260); /* left, top, right, bottom */

    outtextxy(130, 290, "Circle");
    outtextxy(350, 290, "Rectangle");

    getch();                       /* wait for a key press */
    closegraph();                  /* return to text mode */
    return 0;
}
  • initgraph() loads the graphics driver and switches to graphics mode.
  • circle(x, y, r) draws a circle with centre (x,y)(x,y) and radius rr.
  • rectangle(left, top, right, bottom) draws a rectangle from its top-left to bottom-right corners.
  • setcolor() sets the drawing colour, outtextxy() writes text at a position, and closegraph() closes graphics mode.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write short notes on:
  • Global variable
  • Debugging

Answer

Global variable. A global variable is declared outside all functions, usually at the top of the program. Its scope is from the point of declaration to the end of the file, so every function after it can read and modify it. It lives for the whole run of the program and is initialised to 00 by default.

#include <stdio.h>
int count = 0;            /* global variable */

void inc() { count++; }

int main()
{
    inc(); inc();
    printf("%d\n", count);   /* prints 2 */
    return 0;
}

Advantage: data can be shared between functions without passing arguments. Disadvantage: any function can change it accidentally, which makes programs harder to debug and maintain, so globals should be used sparingly.

Debugging. Debugging is the process of finding, locating and removing errors (bugs) from a program after testing has shown that they exist. Errors are of three kinds:

  • Syntax errors: violations of language rules, reported by the compiler.
  • Runtime errors: occur during execution, e.g. division by zero or invalid memory access.
  • Logical errors: the program runs but gives wrong output.

Common techniques are reading the compiler messages, tracing the program by hand, inserting printf() statements to display variable values, and using a debugger (such as gdb) with breakpoints, single stepping and variable watches.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

Define null character. How do you concatenate and compare two strings? An array is called “Balanced Array” if the number of even elements in the array is twice the number of odd elements the array has. Write a program to take the array as input and check whether it is balanced or not.

Answer

Null character. The null character is the character with ASCII value 00, written '\0'. It marks the end of a string in C: a string is a character array terminated by '\0', so "Nepal" occupies 6 bytes (N e p a l \0). String functions use it to know where the string stops.

Concatenating two strings. Concatenation appends one string to the end of another. With the library function:

#include <string.h>
strcat(s1, s2);      /* s2 is appended to s1; s1 must be large enough */

Manually: move to the '\0' of the first string, copy characters of the second one by one, and finish with '\0'.

i = 0; while (s1[i] != '\0') i++;
j = 0; while (s2[j] != '\0') s1[i++] = s2[j++];
s1[i] = '\0';

Comparing two strings. strcmp(s1, s2) compares character by character using ASCII values and returns 00 if the strings are equal, a negative value if s1 is smaller and a positive value if s1 is greater. Manually:

i = 0;
while (s1[i] == s2[i] && s1[i] != '\0') i++;
if (s1[i] == s2[i]) printf("Equal"); else printf("Not equal");

Balanced array program. Count the even elements ee and odd elements oo; the array is balanced if e=2oe = 2o. (Zero is even.)

#include <stdio.h>

int main()
{
    int a[100], n, i, even = 0, odd = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
        if (a[i] % 2 == 0)
            even++;
        else
            odd++;
    }

    if (even == 2 * odd)
        printf("The array is Balanced\n");
    else
        printf("The array is not Balanced\n");
    return 0;
}

Example: {2,4,3,6,8,1}\{2,4,3,6,8,1\} has e=4e=4, o=2o=2, and 4=2×24=2\times2, so it is balanced.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

Differentiate between debugging and testing. What are the uses of delimiters? Explain the different types of data types with examples.

Answer

(a) Debugging versus testing.

TestingDebugging
Process of running the program with test data to detect whether errors exist.Process of locating the cause of a known error and fixing it.
Its aim is to find failures.Its aim is to remove the failure.
Done by testers or developers, can be planned and automated.Done by the programmer, usually manual and needs knowledge of the code.
Comes first.Follows testing.

(b) Uses of delimiters. Delimiters are characters that separate or enclose parts of a program so the compiler can recognise its structure.

  • ; ends a statement.
  • , separates variables, arguments and array elements.
  • { } enclose a block of statements, a function body or an initialiser list.
  • ( ) enclose function arguments, conditions and expression grouping.
  • [ ] enclose array subscripts.
  • " " enclose string literals and ' ' enclose a character constant.
  • Space, tab and newline separate tokens; in scanf/strtok, a delimiter separates input fields.

(c) Data types. A data type specifies the kind of value a variable holds and the memory it uses.

  1. Primary (basic) types:
    • int: whole numbers, e.g. int age = 20; (typically 4 bytes)
    • float: single-precision real numbers, e.g. float pi = 3.14; (4 bytes)
    • double: double-precision reals, e.g. double d = 2.718281828; (8 bytes)
    • char: single character, e.g. char grade = 'A'; (1 byte)
    • void: no value, used for functions returning nothing. Modifiers short, long, signed, unsigned change size and range, e.g. unsigned int, long int.
  2. Derived types: arrays (int a[5];), pointers (int *p;), functions.
  3. User-defined types: structure (struct student {int id; char name[20];};), union, enumeration (enum day {SUN, MON, TUE};) and typedef.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

List any three examples of unformatted I/O. Write a program to find the sum of the first 5 prime numbers. The loop will continue to take input from the user until the user has given five prime numbers.

Answer

(a) Unformatted I/O functions. These read or write data without any format specifier, as a single character or a string:

  1. getchar() reads a single character from the keyboard.
  2. putchar(c) writes a single character to the screen.
  3. gets() / puts() read and write a string (gets is unsafe; fgets is preferred). Others are getch(), getche() and putch().

(b) Program. A number is accepted into the sum only if it is prime; otherwise it is rejected and the user is asked again. The loop ends once five primes have been accepted.

#include <stdio.h>

int isPrime(int n)
{
    int i;
    if (n < 2) return 0;
    for (i = 2; i * i <= n; i++)
        if (n % i == 0)
            return 0;
    return 1;
}

int main()
{
    int num, count = 0, sum = 0;

    while (count < 5)
    {
        printf("Enter prime number %d: ", count + 1);
        scanf("%d", &num);
        if (isPrime(num))
        {
            sum += num;
            count++;
        }
        else
            printf("%d is not prime, try again.\n", num);
    }
    printf("Sum of the five prime numbers = %d\n", sum);
    return 0;
}

Sample run. Inputs 2,4,3,5,9,7,112, 4, 3, 5, 9, 7, 11 accept 2,3,5,7,112,3,5,7,11 and reject 44 and 99, so the sum is 2+3+5+7+11=282+3+5+7+11=28.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Describe the task of any two graphics functions with example.

Answer

Graphics functions are declared in graphics.h and are used after calling initgraph().

1. circle(x, y, radius) draws a circle with centre (x,y)(x,y) and the given radius in the current drawing colour.

circle(200, 150, 50);   /* circle centred at (200,150), radius 50 */

2. line(x1, y1, x2, y2) draws a straight line from point (x1,y1)(x_1,y_1) to point (x2,y2)(x_2,y_2).

line(100, 100, 300, 200);

Complete example.

#include <graphics.h>
#include <conio.h>

int main()
{
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
    circle(200, 150, 50);
    line(100, 250, 300, 250);
    getch();
    closegraph();
    return 0;
}

Other common functions are rectangle(), arc(), ellipse(), setcolor() and outtextxy().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Write a program to create a function that will generate 5 random integers, which are stored in a static array and return their pointer to the main() function such that the elements of the array will be printed in the main() function.

Answer

A local static array keeps its memory after the function returns, so returning its address is safe. (A normal local array would be destroyed on return.)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int *generate()
{
    static int arr[5];
    int i;
    for (i = 0; i < 5; i++)
        arr[i] = rand() % 100;      /* random integers 0..99 */
    return arr;                     /* pointer to first element */
}

int main()
{
    int *p, i;
    srand((unsigned)time(NULL));    /* seed the generator */
    p = generate();
    printf("Random numbers:\n");
    for (i = 0; i < 5; i++)
        printf("%d ", *(p + i));
    printf("\n");
    return 0;
}

srand(time(NULL)) seeds the generator so different numbers are produced on each run; rand() % 100 limits each value to the range 0 to 99.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

What are the uses of the & and * operators? List the advantages of dynamic memory allocation.

Answer

Uses of & and *.

& (address-of operator). Unary & gives the memory address of a variable.

  • It is used with scanf() so that input is stored in the variable: scanf("%d", &n);
  • It assigns an address to a pointer: p = &x;
  • It passes addresses to functions (call by reference): swap(&a, &b);
  • (As a binary operator, & is bitwise AND.)

* (indirection / dereference operator).

  • In a declaration it declares a pointer: int *p;
  • In an expression it accesses the value stored at the address held by the pointer: y = *p; or *p = 10;
  • (As a binary operator, * is multiplication.)
int x = 5, *p;
p = &x;          /* p holds address of x */
*p = *p + 1;     /* x becomes 6 */

Advantages of dynamic memory allocation (malloc, calloc, realloc, free):

  • Memory is allocated at run time, so the size need not be known in advance.
  • No wastage: only the required amount is used, unlike fixed-size arrays.
  • Memory can be resized with realloc() and released with free() for reuse.
  • It allows dynamic data structures such as linked lists, stacks, queues and trees.
  • Memory comes from the heap and persists until freed, even after the function that allocated it returns.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

A file named NUM.DAT contains integers and real numbers. Write a program to copy the integers only from NUM.DAT to INT.DAT.

Answer

Method. The file is read token by token as text. A token is an integer if it consists only of digits (with an optional sign), i.e. it contains no decimal point or exponent. Such tokens are written to INT.DAT; real numbers are skipped.

#include <stdio.h>
#include <string.h>

int main()
{
    FILE *fin, *fout;
    char tok[50];

    fin = fopen("NUM.DAT", "r");
    if (fin == NULL)
    {
        printf("Cannot open NUM.DAT\n");
        return 1;
    }
    fout = fopen("INT.DAT", "w");
    if (fout == NULL)
    {
        printf("Cannot create INT.DAT\n");
        fclose(fin);
        return 1;
    }

    while (fscanf(fin, "%49s", tok) == 1)
    {
        /* a real number contains '.', 'e' or 'E' */
        if (strchr(tok, '.') == NULL &&
            strchr(tok, 'e') == NULL &&
            strchr(tok, 'E') == NULL)
        {
            fprintf(fout, "%s\n", tok);
        }
    }

    fclose(fin);
    fclose(fout);
    printf("Integers copied to INT.DAT\n");
    return 0;
}

For example, if NUM.DAT holds 12 3.5 -7 8.25 100, then INT.DAT will contain 12, -7 and 100.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Discuss operator precedence and associativity with example.

Answer

Precedence decides which operator is evaluated first in an expression with different operators; the operator of higher precedence is applied first. Associativity decides the order of evaluation when operators have the same precedence: left to right or right to left.

Precedence (high to low)OperatorsAssociativity
1() [] -> . postfix ++ --left to right
2unary + - ! ~ prefix ++ -- * & sizeof castsright to left
3* / %left to right
4+ -left to right
5<< >>left to right
6< <= > >=left to right
7== !=left to right
8& then ^ then |left to right
9&& then ||left to right
10?:right to left
11= += -= etc.right to left
12,left to right

Example 1 (precedence).

x=10+5∗2x = 10 + 5 * 2

* has higher precedence than +, so 5×2=105\times2=10 is done first, giving x=20x=20 (not 3030).

Example 2 (associativity, left to right).

y=20/5∗2y = 20 / 5 * 2

/ and * have equal precedence, so evaluation is left to right: (20/5)×2=8(20/5)\times2 = 8.

Example 3 (associativity, right to left).

a=b=c=5a = b = c = 5

Assignment is right to left: c = 5 first, then b = c, then a = b, so all three become 55.

Parentheses can be used to override the default order, e.g. (10+5)×2=30(10+5)\times2=30.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Write a program to take a string in the main() function and pass it to a user-defined function that will return the length of that string.

Answer

#include <stdio.h>

int length(char s[])
{
    int i = 0;
    while (s[i] != '\0')
        i++;
    return i;
}

int main()
{
    char str[100];
    int len;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    /* remove the trailing newline stored by fgets */
    {
        int k = 0;
        while (str[k] != '\0')
        {
            if (str[k] == '\n') { str[k] = '\0'; break; }
            k++;
        }
    }

    len = length(str);
    printf("Length of the string = %d\n", len);
    return 0;
}

The function counts characters until it reaches the null character '\0', which is not included in the length. For input Nepal the output is Length of the string = 5. fgets is used so that strings containing spaces are read correctly.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Create a structure called “Student” with members name, age, and total marks. Write a C program to input data for two students, and display the name of the student having the higher total marks.

Answer

#include <stdio.h>

struct Student
{
    char  name[30];
    int   age;
    float total_marks;
};

int main()
{
    struct Student s[2];
    int i;

    for (i = 0; i < 2; i++)
    {
        printf("Enter name, age and total marks of student %d: ", i + 1);
        scanf("%s %d %f", s[i].name, &s[i].age, &s[i].total_marks);
    }

    if (s[0].total_marks > s[1].total_marks)
        printf("Higher total marks: %s (%.2f)\n", s[0].name, s[0].total_marks);
    else if (s[1].total_marks > s[0].total_marks)
        printf("Higher total marks: %s (%.2f)\n", s[1].name, s[1].total_marks);
    else
        printf("Both students have equal total marks (%.2f)\n", s[0].total_marks);

    return 0;
}

For example, Ram 20 420 and Sita 19 455 print Higher total marks: Sita (455.00).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

How do you scan a file randomly? When do you prefer union over structure? Justify with an example.

Answer

Scanning a file randomly. Normally a file is read sequentially. Random access is achieved by moving the file position pointer with the following functions:

  • fseek(fp, offset, origin) moves the pointer by offset bytes from origin, which is SEEK_SET (beginning), SEEK_CUR (current position) or SEEK_END (end).
  • ftell(fp) returns the current position in bytes from the beginning.
  • rewind(fp) sets the pointer back to the beginning.
fseek(fp, 0, SEEK_END);       /* go to end */
long size = ftell(fp);        /* file size in bytes */
fseek(fp, 3 * sizeof(struct rec), SEEK_SET);   /* jump to 4th record */
fread(&r, sizeof(r), 1, fp);                    /* read it directly */

Union over structure. A structure allocates separate memory for every member, while all members of a union share the same memory, whose size equals that of its largest member. Prefer a union when only one of several members is needed at a time and memory must be saved, or when the same memory must be viewed in different ways.

union data
{
    int   i;        /* 4 bytes */
    float f;        /* 4 bytes */
    char  s[20];    /* 20 bytes */
};

sizeof(union data) is 2020 bytes, whereas an equivalent structure would need 4+4+20=284+4+20=28 bytes. For example, a record that stores either a roll number or a name (never both) can use a union, and only the last value assigned is valid.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

List any two types of bitwise operators. How do you create a nested structure?

Answer

Bitwise operators. They operate on the individual bits of integer operands. Two of them:

1. Bitwise AND (&) gives 1 only if both bits are 1.

12 & 10:1100 & 1010=1000=812 \,\&\, 10:\quad 1100 \,\&\, 1010 = 1000 = 8

2. Bitwise OR (|) gives 1 if at least one bit is 1.

12 ∣ 10:1100 ∣ 1010=1110=1412 \,|\, 10:\quad 1100 \,|\, 1010 = 1110 = 14

(Others: XOR ^, NOT ~, left shift <<, right shift >>.)

Nested structure. A structure that has another structure as one of its members. It is created by defining the inner structure first and then using it as a member type (or by defining it inside).

#include <stdio.h>

struct Date
{
    int day, month, year;
};

struct Employee
{
    int  id;
    char name[20];
    struct Date dob;       /* nested structure */
};

int main()
{
    struct Employee e = {1, "Hari", {5, 8, 2000}};
    printf("%s was born on %d/%d/%d\n",
           e.name, e.dob.day, e.dob.month, e.dob.year);
    return 0;
}

Members of the inner structure are accessed with the dot operator twice, as in e.dob.year.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Frequency of each character

Write a program to count the frequency of each character in a given string.

Answer

Count the Frequency of Each Character in a String

C Program

#include <stdio.h>
#include <string.h>

int main()
{
    char str[100];
    int freq[256] = {0};   /* count of each ASCII character */
    int i;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';   /* remove the newline kept by fgets() */

    /* Count frequency of each character */
    for (i = 0; str[i] != '\0'; i++)
    {
        freq[(unsigned char)str[i]]++;
    }

    /* Display the frequency of each character */
    printf("\nCharacter frequency:\n");
    for (i = 0; i < 256; i++)
    {
        if (freq[i] != 0)
        {
            printf("'%c' occurs %d time(s)\n", i, freq[i]);
        }
    }

    return 0;
}

Explanation

  1. Input: fgets() reads the whole line (including spaces). It also stores the trailing newline, so strcspn() is used to replace it with '\0'; otherwise '\n' would be counted as a character.
  2. Frequency array: freq[256] has one slot for every ASCII character and is initialised to 0.
  3. Counting: each character's ASCII value is used as an index and that slot is incremented: freq[(unsigned char)str[i]]++;
  4. Display: the array is scanned from 0 to 255; every non-zero slot is a character that appeared, so it is printed with its count.

Sample Output

Enter a string: hello world

Character frequency:
' ' occurs 1 time(s)
'd' occurs 1 time(s)
'e' occurs 1 time(s)
'h' occurs 1 time(s)
'l' occurs 3 time(s)
'o' occurs 2 time(s)
'r' occurs 1 time(s)
'w' occurs 1 time(s)

Note

  • The time complexity is O(n)O(n) for a string of length nn (plus a constant 256-step scan).
  • To count only lowercase letters, use a 26-element array with freq[str[i] - 'a']++.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Graphics mode initialization

Describe the functions used to initialize graphics mode. Write a C program using graphics functions to draw a rectangle and a circle on the screen.

Answer

Functions Used to Initialize Graphics Mode

In Turbo C/C++ graphics programming (BGI — Borland Graphics Interface), the following functions are used to initialize graphics mode:

1. initgraph()

void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);
  • Initializes the graphics system by loading a graphics driver from disk and putting the system into graphics mode.
  • graphdriver — pointer to an integer specifying the graphics driver (e.g., DETECT).
  • graphmode — pointer to an integer specifying the graphics mode; set to DETECT so that the function automatically detects the best available mode.
  • pathtodriver — path where the BGI driver files (e.g., EGAVGA.BGI) are located. An empty string "" means the current directory.

2. detectgraph()

void detectgraph(int *graphdriver, int *graphmode);
  • Determines the graphics driver and mode by examining the hardware. It is called automatically by initgraph() when DETECT is passed.

3. closegraph()

void closegraph(void);
  • Shuts down graphics mode, unloads the graphics driver from memory, and restores the original screen mode. It should be called at the end of every graphics program.

4. restorecrtmode()

void restorecrtmode(void);
  • Restores the screen mode to the mode it was in before initgraph() was called (text mode), without unloading the driver.

C Program to Draw a Rectangle and a Circle

#include <graphics.h>
#include <conio.h>

void main(void)
{
    int gd = DETECT, gm;

    /* Initialize graphics mode */
    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

    /* Draw a rectangle: left=100, top=100, right=400, bottom=300 */
    rectangle(100, 100, 400, 300);

    /* Draw a circle: center=(250, 200), radius=80 */
    circle(250, 200, 80);

    /* Hold the screen */
    getch();

    /* Close graphics mode */
    closegraph();
}

Explanation of the Graphics Functions Used

FunctionPurpose
initgraph()Switches the system from text mode to graphics mode.
rectangle(x1, y1, x2, y2)Draws a rectangle using the coordinates of the top-left corner (x1, y1) and bottom-right corner (x2, y2).
circle(x, y, r)Draws a circle with center (x, y) and radius r.
getch()Waits for a key press so the output remains visible.
closegraph()Restores the original text mode and frees graphics memory.

Note: The BGI driver path in initgraph() must point to the folder containing EGAVGA.BGI (commonly C:\TURBOC3\BGI). The program must be compiled and run in Turbo C/C++ (DOS environment or DOSBox), as modern compilers do not support the graphics.h header.

Answer checked by Claude Haiku · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • File opening modes

List any two file opening modes. Write a program to read a file that contains only integers separated by commas and count the number of even elements in that file.

Answer

Two file opening modes:

  1. "r" (read mode) — Opens an existing file for reading only. The file must already exist; if it does not, the function returns NULL.
  2. "w" (write mode) — Opens a file for writing. If the file exists, its contents are erased; if it does not exist, a new file is created.

(Other valid modes: "a", "r+", "w+", "a+", "rb", "wb".)

Program to count even integers in a comma-separated file:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp;
    int num, count = 0;
    char ch;

    fp = fopen("numbers.txt", "r");
    if (fp == NULL) {
        printf("Error: cannot open file.\n");
        return 1;
    }

    /* Read integers separated by commas */
    while (fscanf(fp, "%d", &num) == 1) {
        if (num % 2 == 0)
            count++;

        /* Skip the comma (and any whitespace) after the number */
        ch = fgetc(fp);
        while (ch == ',' || ch == ' ' || ch == '\n' || ch == '\t')
            ch = fgetc(fp);

        if (ch == EOF)
            break;

        /* Put back the first digit of the next number */
        ungetc(ch, fp);
    }

    fclose(fp);

    printf("Number of even elements = %d\n", count);
    return 0;
}

How it works:

  • fopen("numbers.txt", "r") opens the file in read mode; a NULL check handles a missing file.
  • fscanf(fp, "%d", &num) reads one integer at a time, stopping at the comma.
  • Each integer is tested with num % 2 == 0; if true, the counter is incremented.
  • The comma following the number is consumed by fgetc, and ungetc pushes back the first character of the next number so that the next fscanf reads it correctly.
  • The loop ends when fscanf fails (i.e. at end of file), and the final count is printed.

Example: If numbers.txt contains 12,7,8,15,20,33, the output is:

Number of even elements = 3

Answer checked by Claude Haiku · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Sort 10 integers descending

Write a program to read 10 integers into an array and arrange them in descending order.

Answer

C Program: Read 10 Integers and Arrange in Descending Order

#include <stdio.h>

int main()
{
    int a[10], i, j, temp;

    /* Read 10 integers into the array */
    printf("Enter 10 integers:\n");
    for (i = 0; i < 10; i++)
    {
        scanf("%d", &a[i]);
    }

    /* Sort in descending order using bubble sort */
    for (i = 0; i < 9; i++)
    {
        for (j = 0; j < 9 - i; j++)
        {
            if (a[j] < a[j + 1])      /* '<' gives descending order */
            {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }

    /* Display the sorted array */
    printf("Array in descending order:\n");
    for (i = 0; i < 10; i++)
    {
        printf("%d ", a[i]);
    }

    return 0;
}

Sample output

Enter 10 integers:
12 45 7 89 23 56 3 78 34 90
Array in descending order:
90 89 78 56 45 34 23 12 7 3

Explanation

  • An integer array a[10] stores the ten values read using scanf.
  • Two nested loops perform bubble sort. In each pass, adjacent elements are compared; if a[j] < a[j + 1], they are swapped. This pushes the largest element to the front, so the array ends up in descending order.
  • The condition a[j] < a[j + 1] is what makes the order descending; using > instead would give ascending order.
  • The outer loop runs 9 times and the inner loop runs 9 - i times, so the total number of comparisons is at most 45 for 10 elements.

Answer checked by Claude Haiku · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Pointers and modularity

Why do pointers improve program modularity? Write a C program to demonstrate pointer arithmetic by accessing array elements using a pointer.

Answer

Why pointers improve program modularity

Pointers let one module work on data that belongs to another module without copying it or exposing its internal layout. This reduces coupling and makes functions more reusable.

  • Pass by reference: A function receives the address of data, so it can read or modify the caller’s variable. The function interface stays small and independent of the caller’s variable names.
  • Generic array/string handling: An array name decays to a pointer. A function such as void process(int *a, int n) can handle an array of any size; the module only needs the base address and the length.
  • Dynamic data structures: Pointers allow linked lists, trees, graphs, etc. to be built at run time. The module can hide the internal nodes and expose only operations.
  • Function pointers: A module can accept a function as a parameter, e.g. a comparison function for sorting. This gives plug-in behaviour and keeps modules independent.
  • Data abstraction: A structure can be accessed through a pointer, so the module’s internal fields need not be known outside. Only the pointer and the public functions are exposed.
  • Avoids global variables: Data is shared by passing addresses, not by making everything global. This lowers dependency between modules.
  • Efficiency: Large structures are passed by address instead of being copied, so modules interact cheaply.

C program: pointer arithmetic on an array

#include <stdio.h>

/* Modular function: works for any int array using a pointer and size */
void print_array(int *ptr, int n)
{
    int i;
    printf("Accessing array using pointer arithmetic:\n");
    for (i = 0; i < n; i++)
    {
        /* *(ptr + i) is same as ptr[i] and arr[i] */
        printf("*(ptr + %d) = %d\n", i, *(ptr + i));
    }
}

int main(void)
{
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);

    /* arr decays to int* when passed to the function */
    print_array(arr, n);

    printf("\nAccessing array by incrementing the pointer:\n");
    int *p = arr;          /* p points to arr[0] */

    for (int i = 0; i < n; i++)
    {
        printf("arr[%d] = %d\n", i, *p);
        p++;               /* move pointer to next integer element */
    }

    return 0;
}

Sample output

Accessing array using pointer arithmetic:
*(ptr + 0) = 10
*(ptr + 1) = 20
*(ptr + 2) = 30
*(ptr + 3) = 40
*(ptr + 4) = 50

Accessing array by incrementing the pointer:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

Note on pointer arithmetic

If ptr points to an integer, then ptr + i does not add i bytes; it adds i×sizeof(int)i \times \text{sizeof(int)} bytes. So *(ptr + i) gives the same element as ptr[i] and arr[i]. Pointer arithmetic is valid only within the same array or one position past its end; otherwise the behaviour is undefined.

Answer checked by Claude Haiku · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Trace the output

Trace the output of the following program:
#include<stdio.h>
void main()
{
int a, b, c = 1, sum = 0;
for(a = 1; a <= 3; a++)
{
for(b = a; b >= 1; b–)
{
sum = sum + (a * b);
if(sum % 3 == 0)
{
c = c + a;
}
else
{
c = c + b;
}
}
}
printf(“%d”, c);
}

Answer

Trace (initially c=1c = 1, sum=0sum = 0):

absum = sum + a·bsum % 3Updatec
110 + 1 = 11c = c + b2
221 + 4 = 52c = c + b4
215 + 2 = 71c = c + b5
337 + 9 = 161c = c + b8
3216 + 6 = 221c = c + b10
3122 + 3 = 251c = c + b11

sum % 3 is never 00, so the else branch runs every time.

Output: 11

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Recursion sum of first n

Write a program using recursion to find the sum of the first n natural numbers where even numbers are added as their square and odd numbers are added as themselves

Answer

#include <stdio.h>

/* Recursive function to find the required sum */
long long sumSeries(int n)
{
    if (n == 0)                 /* base case */
        return 0;

    if (n % 2 == 0)             /* even number: add its square */
        return (long long)n * n + sumSeries(n - 1);
    else                        /* odd number: add the number itself */
        return n + sumSeries(n - 1);
}

int main()
{
    int n;

    printf("Enter the value of n: ");
    scanf("%d", &n);

    if (n < 0)
    {
        printf("Please enter a non-negative integer.\n");
        return 1;
    }

    printf("Sum of the first %d natural numbers = %lld\n", n, sumSeries(n));

    return 0;
}

Sample Run

Enter the value of n: 5
Sum of the first 5 natural numbers = 29

Explanation

For (n = 5), the terms are:

  • (1) → odd, add (1)
  • (2) → even, add (2^2 = 4)
  • (3) → odd, add (3)
  • (4) → even, add (4^2 = 16)
  • (5) → odd, add (5)

So,

[ 1 + 4 + 3 + 16 + 5 = 29 ]

The function sumSeries(n) calls itself with n - 1 until it reaches the base case n = 0.

Answer checked by Claude Haiku · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Smallest element of each column

Write a program to read a 3×3 matrix of integers and display the smallest element of each column.

Answer

Program to Display the Smallest Element of Each Column of a 3×3 Matrix

Problem Analysis

  • Read a 3×3 matrix of integers from the user.
  • For each column, find the smallest element among its three rows.
  • Display the smallest element of each column.

Algorithm

  1. Start.
  2. Declare a 2-D array a[3][3] and variables i, j, small.
  3. Read all 9 elements of the matrix using nested loops.
  4. For each column j from 0 to 2:
    • Set small = a[0][j].
    • For each row i from 1 to 2:
      • If a[i][j] < small, set small = a[i][j].
    • Print small as the smallest element of column j.
  5. Stop.

C Program

#include <stdio.h>

int main()
{
    int a[3][3];
    int i, j, small;

    /* Read the 3x3 matrix */
    printf("Enter the elements of 3x3 matrix:\n");
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            scanf("%d", &a[i][j]);
        }
    }

    /* Display the matrix */
    printf("\nThe entered matrix is:\n");
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            printf("%4d", a[i][j]);
        }
        printf("\n");
    }

    /* Find and display smallest element of each column */
    printf("\nSmallest element of each column:\n");
    for (j = 0; j < 3; j++)
    {
        small = a[0][j];
        for (i = 1; i < 3; i++)
        {
            if (a[i][j] < small)
            {
                small = a[i][j];
            }
        }
        printf("Column %d: %d\n", j + 1, small);
    }

    return 0;
}

Sample Output

Enter the elements of 3x3 matrix:
9 4 7
3 8 2
6 1 5

The entered matrix is:
   9   4   7
   3   8   2
   6   1   5

Smallest element of each column:
Column 1: 3
Column 2: 1
Column 3: 2

Explanation

  • The outer loop over j fixes one column at a time.
  • small is initialised with the first row element of that column, a[0][j].
  • The inner loop over i compares the remaining two elements of the same column and updates small whenever a smaller value is found.
  • After the inner loop finishes, small holds the minimum of that column, which is printed.
  • The same logic works for any square matrix if the loop bounds are changed from 3 to the required size.

Answer checked by Claude Haiku · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Parameters and call by value/reference

What is the difference between actual parameter and formal parameter? Differentiate between call by value and call by reference. Write a C program to reverse a given integer.

Answer

Actual Parameter vs Formal Parameter

Actual ParameterFormal Parameter
Parameters that appear in a function callParameters that appear in the function definition/declaration
Also called argumentsAlso called dummy parameters
They supply the actual values to the functionThey receive the values passed by the caller
They exist in the calling functionThey exist in the called function
Example: in sum(a, b);, a and b are actual parametersExample: in int sum(int x, int y), x and y are formal parameters

Call by Value vs Call by Reference

Call by ValueCall by Reference
A copy of the actual parameter's value is passedThe address of the actual parameter is passed
Changes made to the formal parameter do not affect the actual parameterChanges made to the formal parameter do affect the actual parameter
Formal parameter is a separate variable in memoryFormal parameter points to the same memory location
Safer — original data cannot be accidentally modifiedLess safe — original data can be modified
Example: void swap(int x, int y)Example: void swap(int *x, int *y)

C Program to Reverse a Given Integer

#include <stdio.h>

int main()
{
    int n, rem, rev = 0;

    printf("Enter an integer: ");
    scanf("%d", &n);

    while (n != 0)
    {
        rem = n % 10;        /* extract last digit */
        rev = rev * 10 + rem; /* append digit to reversed number */
        n = n / 10;          /* remove last digit */
    }

    printf("Reversed number = %d\n", rev);

    return 0;
}

Sample run

Enter an integer: 1234
Reversed number = 4321

Working: Each iteration takes the last digit of n using n % 10, places it at the end of rev by multiplying rev by 10 and adding the digit, then drops the last digit of n using n / 10. The loop stops when n becomes 0.

Answer checked by Claude Haiku · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from Frequency of each character (Semester 1 · C Programming), Graphics mode initialization (Semester 1 · C Programming), File opening modes (Semester 1 · C Programming), Sort 10 integers descending (Semester 1 · C Programming), Pointers and modularity (Semester 1 · C Programming), Trace the output (Semester 1 · C Programming), Recursion sum of first n (Semester 1 · C Programming), Smallest element of each column (BSc CSIT, Semester 1 · C Programming), Parameters and call by value/reference (Semester 1 · C Programming), TU BSc CSIT 2074 First Semester C Programming (TU IOST board exam, 2074), TU BSc CSIT 2075 First Semester C Programming (TU IOST board exam, 2075), TU BSc CSIT 2077 First Semester C Programming (TU IOST board exam, 2077), TU BSc CSIT 2078 First Semester C Programming (TU IOST board exam, 2078), TU BSc CSIT 2079 First Semester C Programming (TU IOST board exam, 2079), TU BSc CSIT 2080 First Semester C Programming (TU IOST board exam, 2080), TU BSc CSIT 2081 First Semester C Programming (TU IOST board exam, 2081), TU BSc CSIT 2082 First Semester C Programming (TU IOST board exam, 2082), TU BSc CSIT 2074 First Semester Digital Logic (TU IOST board exam, 2074), TU BSc CSIT 2075 First Semester Digital Logic (TU IOST board exam, 2075), TU BSc CSIT 2077 First Semester Digital Logic (TU IOST board exam, 2077), TU BSc CSIT 2078 First Semester Digital Logic (TU IOST board exam, 2078), TU BSc CSIT 2080 First Semester Digital Logic (TU IOST board exam, 2080), TU BSc CSIT 2081 First Semester Digital Logic (TU IOST board exam, 2081), TU BSc CSIT 2074 First Semester Introduction to Information Technology (TU IOST board exam, 2074), TU BSc CSIT 2075 First Semester Introduction to Information Technology (TU IOST board exam, 2075), TU BSc CSIT 2077 First Semester Introduction to Information Technology (TU IOST board exam, 2077), TU BSc CSIT 2078 First Semester Introduction to Information Technology (TU IOST board exam, 2078), TU BSc CSIT 2080 First Semester Introduction to Information Technology (TU IOST board exam, 2080), TU BSc CSIT 2081 First Semester Introduction to Information Technology (TU IOST board exam, 2081), TU BSc CSIT 2074 First Semester Mathematics I (TU IOST board exam, 2074), TU BSc CSIT 2075 First Semester Mathematics I (TU IOST board exam, 2075), TU BSc CSIT 2077 First Semester Mathematics I (TU IOST board exam, 2077), TU BSc CSIT 2078 First Semester Mathematics I (TU IOST board exam, 2078), TU BSc CSIT 2079 First Semester Mathematics I (TU IOST board exam, 2079), TU BSc CSIT 2080 First Semester Mathematics I (TU IOST board exam, 2080), TU BSc CSIT 2081 First Semester Mathematics I (TU IOST board exam, 2081), TU BSc CSIT 2082 First Semester Mathematics I (TU IOST board exam, 2082), TU BSc CSIT 2074 First Semester Physics (TU IOST board exam, 2074), TU BSc CSIT 2075 First Semester Physics (TU IOST board exam, 2075), TU BSc CSIT 2077 First Semester Physics (TU IOST board exam, 2077), TU BSc CSIT 2078 First Semester Physics (TU IOST board exam, 2078), TU BSc CSIT 2079 First Semester Physics (TU IOST board exam, 2079), TU BSc CSIT 2080 First Semester Physics (TU IOST board exam, 2080), TU BSc CSIT 2081 First Semester Physics (TU IOST board exam, 2081) and TU BSc CSIT 2082 First Semester Physics (TU IOST board exam, 2082). Answers are written for this site; check them against your class notes.