Skip to main content

Chapter 1

Programming in C

PU BCA past exam questions

Past questions and answers

62 questions set from this chapter, 5 of them more than once; 1 is most repeated (set, or a close variant set, in 3 or more exams). Most repeated first.

  • Most repeated · 3 of 5 exams
  • Asked 3 times
  • 2025 Spring · 5 marks
  • 2024 Spring · 5 marks
  • 2023 Spring · 5 marks

Write short notes on: Continue statement and Break statement

Answer

Break statement

break immediately terminates the nearest enclosing loop (for, while, do-while) or switch, and control passes to the statement after it. It is used to exit a loop early when a condition is met, and to end each case of a switch.

for (i = 1; i <= 10; i++) {
    if (i == 5)
        break;
    printf("%d ", i);
}

Output: 1 2 3 4

Continue statement

continue skips the remaining statements of the current iteration and moves to the next iteration of the loop. In a for loop the update expression is executed, and in while/do-while the condition is tested again.

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

Output: 1 2 4 5

Difference

breakcontinue
Ends the loop completelySkips only the current iteration
Works in loops and switchWorks only in loops
Control goes outside the loopControl goes to the next iteration

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Asked 2 times
  • 2025 Spring · 8 marks
  • 2024 Spring · 7 marks
  • 2024 Spring · 7 marks

What are the advantages of using function? Discuss local and global variables with examples.

Answer

Function

A function is a self-contained block of code that performs a specific task and can be called whenever needed. C programs consist of main() and other user-defined and library functions.

Advantages of using functions

  1. Modularity: a large program is divided into small, manageable parts.
  2. Reusability: the same code is written once and called many times, which avoids repetition.
  3. Easy debugging and testing: an error can be isolated in one function.
  4. Easy maintenance: a change is made in one place only.
  5. Readability: the program is shorter and easier to understand.
  6. Team work: different programmers can develop different functions.
  7. Smaller program size: repeated code is not duplicated.

Local variables

A variable declared inside a function or block. It is created when the function is entered and destroyed on exit; it is visible only within that function and gets garbage value if not initialised.

Global variables

A variable declared outside all functions, usually at the top of the program. It is visible to all functions that follow, exists for the whole execution, and is initialised to zero by default.

Example

#include <stdio.h>

int total = 100;              /* global variable */

void show() {
    int x = 5;                /* local to show() */
    total = total + x;
    printf("In show: x = %d, total = %d\n", x, total);
}

int main() {
    int x = 20;               /* local to main(), different from x in show() */
    show();
    printf("In main: x = %d, total = %d\n", x, total);
    return 0;
}

Output:

In show: x = 5, total = 105
In main: x = 20, total = 105

The two local variables x are separate and do not interfere, while the global total is changed by show() and the new value is seen in main(). Global variables should be used sparingly because any function can change them, which makes bugs harder to find.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Asked 2 times
  • 2024 Spring · 5 marks
  • 2024 Spring · 5 marks
  • 2023 Spring · 5 marks

Write short notes on: Multidimensional Arrays

Answer

A multidimensional array is an array with more than one subscript. The most common is the two dimensional array, which stores data in rows and columns like a matrix.

Declaration

data_type name[rows][columns];
int a[3][3];     // 3 rows, 3 columns, 9 elements

Initialisation

int a[2][3] = { {1, 2, 3}, {4, 5, 6} };

Elements are accessed as a[i][j], where ii is the row index and jj the column index, both starting from 0. The total number of elements is rows ×\times columns. In memory they are stored row by row.

Example: reading and printing

int a[2][3], i, j;
for (i = 0; i < 2; i++)
    for (j = 0; j < 3; j++)
        scanf("%d", &a[i][j]);

for (i = 0; i < 2; i++) {
    for (j = 0; j < 3; j++)
        printf("%d ", a[i][j]);
    printf("\n");
}

Uses include matrices, tables and game boards. Arrays of three or more dimensions, such as int b[2][3][4];, are declared in the same way.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Asked 2 times
  • 2024 Spring · 7 marks
  • 2024 Spring · 8 marks
  • 2023 Spring · 8 marks

Write a program to read a line text and print each character in reverse case. (Print lower case if upper case and vice versa).

Answer

The program reads a line of text and checks each character. Upper case letters are converted to lower case and lower case letters to upper case; other characters are left unchanged. The ASCII difference between a lower case letter and its upper case form is 32.

#include <stdio.h>
#include <ctype.h>

int main() {
    char text[200];
    int i;

    printf("Enter a line of text: ");
    fgets(text, sizeof(text), stdin);

    for (i = 0; text[i] != '\0'; i++) {
        if (isupper(text[i]))
            text[i] = tolower(text[i]);
        else if (islower(text[i]))
            text[i] = toupper(text[i]);
    }

    printf("Reversed case: %s", text);
    return 0;
}

Sample: input Hello World 123 gives hELLO wORLD 123.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • Asked 2 times
  • 2024 Spring · 5 marks
  • 2024 Spring · 5 marks
  • 2023 Spring · 5 marks

Write short notes on: Call by Reference

Answer

In call by reference, the addresses of the actual arguments are passed to the function, and the formal parameters are pointers. The function works on the original variables through these addresses, so any change made inside the function affects the caller's variables.

#include <stdio.h>

void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main() {
    int x = 5, y = 10;
    swap(&x, &y);
    printf("x = %d, y = %d", x, y);   /* x = 10, y = 5 */
    return 0;
}

Advantages: the original values can be modified, more than one value can be returned, and no copy of large data is made.

Difference from call by value: in call by value only copies of the values are passed, so the original variables remain unchanged.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 7 marks

Write an algorithm and flowchart to print whether a given number is even or odd.

Answer

Algorithm

  1. Start.
  2. Read a number nn.
  3. Compute the remainder r=n mod 2r = n \bmod 2.
  4. If r=0r = 0, print "n is even"; otherwise print "n is odd".
  5. Stop.

Flowchart

        +---------+
        |  Start  |
        +----+----+
             |
        /----v-----\
       /  Read n    \
       \------------/
             |
        +----v----------+
        |  r = n % 2    |
        +----+----------+
             |
        +----v----+
       / r == 0 ?  \
       \           /
        +--+----+-+
      Yes  |    | No
   +-------v-+ +v----------+
   | Print   | | Print     |
   | "Even"  | | "Odd"     |
   +-----+---+ +----+------+
         |          |
         +----+-----+
              |
         +----v----+
         |  Stop   |
         +---------+

Check: for n=8n = 8, 8 mod 2=08 \bmod 2 = 0, so the output is "even"; for n=7n = 7, 7 mod 2=17 \bmod 2 = 1, so the output is "odd".

Program

#include <stdio.h>

int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n % 2 == 0)
        printf("%d is even\n", n);
    else
        printf("%d is odd\n", n);
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 8 marks

What is variable? Explain datatypes available in c with suitable example.

Answer

Variable

A variable is a named memory location used to store a value that can change during execution of a program. Every variable must be declared with a data type, which tells the compiler how much memory to reserve and what kind of values may be stored.

Syntax: datatype variable_name; For example, int age = 20;

Rules for names: they may contain letters, digits and underscore, must not start with a digit, must not be a keyword, and are case sensitive.

Data types in C

1. Primary (basic) data types

TypeSize (typical)FormatExample
char1 byte%cchar grade = 'A';
int4 bytes (2 in old compilers)%dint roll = 25;
float4 bytes%ffloat pi = 3.14;
double8 bytes%lfdouble d = 3.14159265;
voidno valuevoid main(), functions returning nothing

Modifiers short, long, signed, unsigned change the size or range, for example unsigned int, long int, long double. A 4-byte signed int stores values from −231-2^{31} to 231−12^{31}-1.

2. Derived data types: arrays, pointers, functions. Example: int marks[5];

3. User-defined data types: struct, union, enum and typedef. Example:

struct student { int roll; char name[20]; };
enum day { SUN, MON, TUE };
typedef unsigned int uint;

Example program

#include <stdio.h>

int main() {
    int age = 20;
    float height = 5.8;
    double pi = 3.14159265;
    char grade = 'A';
    printf("%d %.1f %.8lf %c\n", age, height, pi, grade);
    return 0;
}

Output: 20 5.8 3.14159265 A

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 7 marks

List out the different types of operators. Explain with expression.

Answer

An operator is a symbol that tells the compiler to perform a specific operation on operands. An expression is a combination of operands and operators that produces a value.

1. Arithmetic operators: +, -, *, /, %. Expression: a = 10 % 3; gives a=1a = 1; 10 / 3 gives 3 for integers.

2. Relational operators: <, >, <=, >=, ==, !=. The result is 1 (true) or 0 (false). Expression: x = (5 > 3); gives x=1x = 1.

3. Logical operators: && (AND), || (OR), ! (NOT). Expression: (a > 0 && b > 0) is true only when both conditions are true.

4. Assignment operators: =, +=, -=, *=, /=, %=. Expression: a += 5; is the same as a = a + 5;

5. Increment and decrement operators: ++, --, in prefix and postfix form. With a=5a = 5: b = a++; gives b=5,a=6b = 5, a = 6; b = ++a; gives b=6,a=6b = 6, a = 6.

6. Bitwise operators: &, |, ^, ~, <<, >>. Expression: 5 & 3 gives 1 (binary 101 AND 011 = 001); 5 << 1 gives 10.

7. Conditional (ternary) operator: ? : Expression: max = (a > b) ? a : b;

8. Special operators: sizeof, comma ,, address-of &, pointer *, member operators . and ->. Expression: sizeof(int) gives 4 on most systems.

Example

#include <stdio.h>

int main() {
    int a = 10, b = 3;
    printf("%d %d %d\n", a + b, a - b, a % b);      /* 13 7 1 */
    printf("%d\n", (a > b) && (b > 0));              /* 1 */
    printf("%d\n", (a > b) ? a : b);                 /* 10 */
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 8 marks

What is while loop? Explain for loop and do-while loop with suitable example.

Answer

A loop repeats a block of statements as long as a condition is true.

while loop

It is an entry-controlled loop: the condition is tested before each iteration, so the body may execute zero times.

while (condition) {
    statements;
}

Example: print 1 to 5.

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

Output: 1 2 3 4 5

for loop

Also entry-controlled; initialisation, condition and update are written together in one line, which is best when the number of repetitions is known.

for (initialization; condition; update) {
    statements;
}

Example: sum of the first 5 natural numbers.

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

Output: 15, since 1+2+3+4+5=151+2+3+4+5 = 15.

do-while loop

It is an exit-controlled loop: the body runs first and the condition is tested afterwards, so the body executes at least once. Note the semicolon after the condition.

do {
    statements;
} while (condition);

Example:

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

Output: 1 2 3 4 5. If i started at 10, the body would still print 10 once, whereas a while loop would print nothing.

Difference: while and for check the condition first; do-while checks it last and always runs at least once.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 7 marks

Write a program that will read a number n and print the even series up to n.

Answer

The even series up to nn is 2,4,6,…2, 4, 6, \dots up to the largest even number not exceeding nn.

Program

#include <stdio.h>

int main() {
    int n, i;
    printf("Enter n: ");
    scanf("%d", &n);
    printf("Even series up to %d:\n", n);
    for (i = 2; i <= n; i += 2)
        printf("%d ", i);
    printf("\n");
    return 0;
}

Sample run: for n=10n = 10 the output is 2 4 6 8 10; for n=9n = 9 it is 2 4 6 8.

Explanation: the loop starts at 2 and increases by 2 on each pass, so every value printed is even, and it stops when i>ni > n. If n<2n < 2 nothing is printed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 7 marks

What is an array? WAP to read n elements in an 1D array and find sum of all elements on an array and display sum and average of that sum.

Answer

Array

An array is a collection of a fixed number of elements of the same data type stored in contiguous memory locations and accessed by a common name and an index. In C the index starts from 0. A one-dimensional array is declared as int a[10];, whose elements are a[0] to a[9].

Program

#include <stdio.h>

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

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

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

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

Sample run: for n=5n = 5 and elements 10,20,30,40,5010, 20, 30, 40, 50:

sum=10+20+30+40+50=150,average=1505=30.00\text{sum} = 10+20+30+40+50 = 150,\qquad \text{average} = \frac{150}{5} = 30.00

The cast (float)sum prevents integer division from discarding the fractional part.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 8 marks

Write a program that will read a array of character and reverse the characters in an array without using string function.

Answer

The characters are reversed in place by swapping the first with the last, the second with the second last, and so on. The length is found with a loop, since no string function is allowed.

#include <stdio.h>

int main() {
    char str[100], temp;
    int i, len = 0;

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

    while (str[len] != '\0')       /* find length without strlen */
        len++;

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

    printf("Reversed: %s\n", str);
    return 0;
}

Sample run: input Nepal has length 5. The loop runs ⌊5/2⌋=2\lfloor 5/2 \rfloor = 2 times: swap N and l, then e and a; p stays in the middle. Output: lapeN.

To read a line with spaces, fgets(str, 100, stdin) can be used instead of scanf, removing the trailing newline before reversing.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 8 marks

Write a program to sort array elements ascending and descending order.

Answer

The program uses bubble sort: adjacent elements are compared and swapped, so the largest value moves to the end on each pass. The array is sorted in ascending order and then the same sorted array is printed backward for descending order.

#include <stdio.h>

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

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

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

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

    printf("\nDescending order: ");
    for (i = n - 1; i >= 0; i--)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Sample run: input 5,2,9,1,75, 2, 9, 1, 7 gives

  • Ascending order: 1 2 5 7 9
  • Descending order: 9 7 5 2 1

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 8 marks

What is String? Explain 5 string functions available in c with suitable example.

Answer

String

A string is a sequence of characters terminated by the null character '\0'. In C it is stored in a character array, for example char name[20] = "Nepal"; (6 bytes are used, including '\0'). Input can be taken with scanf("%s", name) or gets/fgets, output with printf("%s", name). The string functions are declared in <string.h>.

1. strlen(s): returns the number of characters, not counting '\0'.

printf("%d", strlen("Nepal"));   /* 5 */

2. strcpy(dest, src): copies src into dest.

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

3. strcat(s1, s2): appends s2 to the end of s1.

char s1[20] = "Good ", s2[] = "Morning";
strcat(s1, s2);                  /* s1 = "Good Morning" */

4. strcmp(s1, s2): compares two strings; returns 0 if equal, a negative value if s1 < s2, and a positive value if s1 > s2 (alphabetical order).

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

5. strrev(s) (non-standard, available in some compilers) reverses a string; the portable alternative is strstr(s1, s2), which finds the first occurrence of s2 in s1 and returns a pointer to it or NULL.

char *p = strstr("computer", "put");   /* p points to "puter" */

Example program

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

int main() {
    char s1[30] = "Edu", s2[] = "cation";
    strcat(s1, s2);
    printf("%s has length %lu\n", s1, strlen(s1));  /* Education has length 9 */
    printf("%d\n", strcmp(s1, "Education"));        /* 0 */
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 7 marks

What is pointer? Explain the pointer arithmetic with suitable example.

Answer

Pointer

A pointer is a variable that stores the memory address of another variable. It is declared with *, and the address-of operator & gives the address; *p (dereferencing) gives the value stored at that address.

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

Pointer arithmetic

Only some arithmetic operations are valid on pointers, and they are scaled by the size of the type pointed to.

  1. Increment p++: moves to the next element. If p is an int * holding address 1000 and int is 4 bytes, p++ gives 1004. In general new address = old address + n×sizeof(type)+\ n \times \text{sizeof(type)}.
  2. Decrement p--: moves to the previous element (1000 becomes 996).
  3. Addition of an integer p + n: points nn elements ahead; *(p + n) is the same as p[n].
  4. Subtraction of an integer p - n: points nn elements back.
  5. Subtraction of two pointers p2 - p1: gives the number of elements between them (both must point into the same array).
  6. Comparison using <, >, == tells which element comes first.

Not allowed: adding two pointers, multiplying or dividing a pointer.

Example

#include <stdio.h>

int main() {
    int a[5] = {10, 20, 30, 40, 50};
    int *p = a;                  /* points to a[0] */

    printf("%d\n", *p);           /* 10 */
    p++;
    printf("%d\n", *p);           /* 20 */
    printf("%d\n", *(p + 2));     /* 40 */
    printf("%ld\n", (a + 4) - p); /* 3 */
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 8 marks

Create the structure of employee, input 50 records and display the name of those employee whose salary is above 50000.

Answer

A structure groups items of different types under one name. Here struct employee holds the id, name and salary, and an array of 50 such structures stores all the records.

#include <stdio.h>

struct employee {
    int id;
    char name[30];
    float salary;
};

int main() {
    struct employee emp[50];
    int i;

    for (i = 0; i < 50; i++) {
        printf("Enter details of employee %d (id name salary): ", i + 1);
        scanf("%d %29s %f", &emp[i].id, emp[i].name, &emp[i].salary);
    }

    printf("\nEmployees with salary above 50000:\n");
    for (i = 0; i < 50; i++) {
        if (emp[i].salary > 50000)
            printf("%s\n", emp[i].name);
    }
    return 0;
}

Explanation: the first loop reads the 50 records using the dot operator to reach each member (emp[i].salary). The second loop checks the condition salary > 50000 for each record and prints only the names that satisfy it. For example, a salary of Rs 50,000 is not printed, while Rs 50,001 is.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 7 marks

What is a File? How can a file be handled in C programming? Explain file opening modes used in C program.

Answer

File

A file is a named collection of related data stored permanently on a secondary storage device such as a disk. Unlike variables in RAM, its contents remain after the program ends. C supports text files (human readable characters) and binary files (raw bytes).

Handling a file in C

Files are handled using a file pointer of type FILE * and the functions of <stdio.h>, in four steps.

  1. Declare a file pointer: FILE *fp;
  2. Open the file: fp = fopen("data.txt", "w"); It returns NULL if opening fails, so check it.
  3. Read or write: fprintf, fscanf, fputc, fgetc, fputs, fgets, fwrite, fread.
  4. Close the file: fclose(fp);

Example

#include <stdio.h>

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

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

    fp = fopen("data.txt", "r");
    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);
    fclose(fp);
    return 0;
}

File opening modes

ModeMeaning
rOpen an existing file for reading; fails if the file does not exist
wCreate a file for writing; an existing file is erased
aOpen for appending; data is added at the end; file is created if absent
r+Open an existing file for both reading and writing
w+Create a file for reading and writing; existing contents are erased
a+Open for reading and appending
rb, wb, abSame as r, w, a but for binary files
rb+, wb+, ab+Binary files for update (reading and writing)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 5 marks

Write short notes on: Macros

Answer

A macro is a name defined with the preprocessor directive #define that is replaced by its value or code before compilation. The preprocessor does simple text substitution, so no memory is allocated and there is no function-call overhead.

1. Object-like macros (symbolic constants)

#define PI 3.14159
#define MAX 100

Every occurrence of PI is replaced by 3.14159. Using names makes the program readable and a value can be changed in one place.

2. Function-like macros (with arguments)

#define SQUARE(x) ((x) * (x))
#define MAX2(a, b) ((a) > (b) ? (a) : (b))

SQUARE(5) becomes ((5) * (5)), which is 25. The parentheses are important: without them SQUARE(a+1) would expand incorrectly.

Example

#include <stdio.h>
#define PI 3.14159
#define AREA(r) (PI * (r) * (r))

int main() {
    printf("%.2f\n", AREA(2));   /* 12.57 */
    return 0;
}

Here AREA(2)=3.14159×2×2=12.56636≈12.57\text{AREA}(2) = 3.14159 \times 2 \times 2 = 12.56636 \approx 12.57.

Advantages: faster execution than functions, improved readability, easy maintenance. Disadvantages: no type checking, arguments may be evaluated more than once (e.g. SQUARE(i++)), and the code size increases with each expansion.

A macro definition does not end with a semicolon and can be removed with #undef.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 Spring · 5 marks

Write short notes on: Context Diagram (DFD-0)

Answer

A context diagram, also called the level-0 data flow diagram (DFD-0), shows the whole system as a single process and its interaction with the outside world. It gives the broadest, highest-level view of the system and defines its boundary.

Components

  • One process (bubble) representing the entire system, usually numbered 0 and named after the system.
  • External entities (rectangles), the sources and destinations of data, such as customers, suppliers or management, that lie outside the system.
  • Data flows (arrows) labelled with the data moving between the entities and the system.

There are no data stores and no internal processes in a context diagram; those appear in lower-level DFDs (level 1, 2, ...).

Example: library system

 [Member] --- book request ---------> (        ) --- issued book, receipt ---> [Member]
                                      (   0    )
 [Librarian] --- new book details --> ( Library ) --- reports --------------> [Librarian]
                                      ( System  )

Purpose and uses

  • Shows the scope and boundary of the system.
  • Identifies all external entities and the main data they exchange.
  • Is easily understood by non-technical users and management.
  • Forms the starting point for decomposing the system into level-1 DFD and further levels, where the inputs and outputs must remain balanced with the context diagram.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

What are the key features that make C a popular and widely used programming language? Explain the basic structure of a C program with an example.

Answer

Key features of C

  1. Simple and efficient: a small set of keywords and a clear syntax make it easy to learn, yet programs run fast.
  2. Portable: C programs written on one machine can be compiled and run on others with few or no changes.
  3. Structured language: programs are divided into functions, which makes them modular and easy to maintain.
  4. Rich set of operators and data types, including arrays, pointers, structures and unions.
  5. Low-level access: pointers and bitwise operations allow direct memory and hardware manipulation, so C is called a middle-level language (high-level features with assembly-like control).
  6. Fast and efficient execution: compiled code is close to machine code with little overhead.
  7. Rich library: a large standard library (stdio.h, string.h, math.h) and the ability to create user-defined functions.
  8. Dynamic memory allocation using malloc, calloc, realloc and free.
  9. Extensible: new functions can be added to the library, and C is the base of C++, Java and other languages; it is widely used for operating systems (UNIX, Linux), compilers and embedded systems.

Basic structure of a C program

  1. Documentation section (comments)
  2. Link section (#include header files)
  3. Definition section (#define macros)
  4. Global declaration section (global variables, function prototypes)
  5. main() function section (declaration part and executable part)
  6. Subprogram section (user-defined functions)

Example

/* Program to find the sum of two numbers */        /* documentation */
#include <stdio.h>                                    /* link section */
#define MSG "Sum is "                                 /* definition */

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

int main() {                                          /* main section */
    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 */
    return x + y;
}

Output: Sum is 12

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks
  • 2024 Spring · 8 marks

WAP to calculate prime numbers between 1 to 50.

Answer

A prime number is greater than 1 and divisible only by 1 and itself. A number nn is tested by trying divisors from 2 to n\sqrt{n} (equivalently i×i≤ni \times i \le n); if none divides it, it is prime.

#include <stdio.h>

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

    printf("Prime numbers between 1 and 50:\n");
    for (n = 2; n <= 50; n++) {
        isPrime = 1;
        for (i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                isPrime = 0;
                break;
            }
        }
        if (isPrime)
            printf("%d ", n);
    }
    printf("\n");
    return 0;
}

Output:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

There are 15 primes in this range. Check: for n=49n = 49 the divisor i=7i = 7 satisfies 7×7≤497 \times 7 \le 49 and 49 mod 7=049 \bmod 7 = 0, so 49 is rejected; for n=47n = 47 the divisors 2 to 6 all leave a remainder, so 47 is prime.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

Differentiate between single line and block comments in C with an example. Why are comments important in program? Explain.

Answer

Comments are non-executable notes written in the source code. The compiler ignores them completely during compilation. C supports two kinds.

Difference between single line and block comments

BasisSingle line commentBlock (multi-line) comment
SymbolStarts with //Enclosed between /* and */
ExtentRuns from // to the end of that lineCan span one or many lines
StandardIntroduced in C99 (from C++)Available in all versions of C
NestingNot applicableCannot be nested
UseShort remark beside a statementLong description of a function or program

Example

#include <stdio.h>

/* Program to add two numbers.
   Author: Student
   Date: 2025 */
int main() {
    int a = 10, b = 20;   // two input values
    int sum = a + b;      // add the values
    printf("Sum = %d", sum);
    return 0;
}

Here the text between /* and */ is a block comment over several lines, while the text after // is a single line comment.

Importance of comments

  1. They make the program easier to read and understand, for the author and for others.
  2. They document the purpose, inputs, outputs and logic of functions.
  3. They make debugging and maintenance easier, because the intention of the code is visible.
  4. A part of the code can be temporarily disabled for testing by commenting it out, without deleting it.
  5. They help team members work on the same code and help beginners follow the algorithm.
  6. They add no cost to the executable, as they are removed before compilation.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks

Define switch statement with syntax. Write a program to display following Pattern.
*
**
***
****
*****

Answer

Switch statement

The switch statement is a multi-way selection statement. It compares the value of an expression with a list of constant case labels and executes the block of the matching case. If no case matches, the default block runs. The break statement ends a case so that execution does not fall through to the next one.

Syntax

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

The expression must evaluate to an integer or character value, and each case label must be a unique constant.

Program to display the pattern

#include <stdio.h>

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

The outer loop controls the row (1 to 5) and the inner loop prints ii stars in row ii, so the output is

*
**
***
****
*****

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks

What is a looping statement? Explain while loop and do-while loop using suitable example.

Answer

Looping statement

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

while loop

It is an entry-controlled loop: the condition is tested first, and the body executes only if it is true. If the condition is false at the start, the body never runs.

while (condition) {
    statements;
}

Example: print 1 to 5.

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

Output: 1 2 3 4 5

do-while loop

It is an exit-controlled loop: the body is executed first and the condition is tested afterwards. So the body runs at least once, even when the condition is false. Note the semicolon after the condition.

do {
    statements;
} while (condition);

Example: sum of digits entered until the user enters 0.

#include <stdio.h>
int main() {
    int n, sum = 0;
    do {
        printf("Enter a number (0 to stop): ");
        scanf("%d", &n);
        sum += n;
    } while (n != 0);
    printf("Sum = %d", sum);
    return 0;
}

Difference

whiledo-while
Condition tested before the bodyCondition tested after the body
May execute zero timesExecutes at least once
No semicolon after the conditionSemicolon after the condition

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

What is array? Write a program to input any 10 numbers and find maximum and minimum among them.

Answer

Array

An array is a collection of a fixed number of elements of the same data type stored in contiguous memory locations and referred to by a common name. Each element is accessed by an index, which starts from 0. For example, int a[10]; declares an array of 10 integers, a[0] to a[9].

Program to find maximum and minimum of 10 numbers

#include <stdio.h>

int main() {
    int a[10], i, max, min;

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

    max = min = a[0];
    for (i = 1; i < 10; i++) {
        if (a[i] > max)
            max = a[i];
        if (a[i] < min)
            min = a[i];
    }

    printf("Maximum = %d\n", max);
    printf("Minimum = %d\n", min);
    return 0;
}

Working: the first element is taken as both maximum and minimum. Each later element is compared with them; if it is larger than max it replaces max, and if it is smaller than min it replaces min.

Sample: for input 5 12 3 9 27 1 8 14 6 20, the output is Maximum = 27 and Minimum = 1.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

Write a program to get 20 numbers from user and sort them in ascending order.

Answer

The program reads 20 numbers into an array and sorts them in ascending order using bubble sort. In each pass, adjacent elements are compared and swapped if they are in the wrong order, so the largest remaining element moves to the end.

#include <stdio.h>

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

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

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

    printf("Numbers in ascending order:\n");
    for (i = 0; i < 20; i++)
        printf("%d ", a[i]);
    return 0;
}

The outer loop makes 19 passes and the inner loop compares the unsorted part only. For example, 5 2 9 1 becomes 2 5 1 9, then 2 1 5 9, then 1 2 5 9.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks

Define String. Explain six string handling functions with example.

Answer

String

A string is a sequence of characters terminated by the null character '\0'. In C it is stored in a character array, for example char name[20] = "Nepal";. The standard library <string.h> provides functions to handle strings.

Six string handling functions

  1. strlen(s) returns the number of characters in s, excluding '\0'.
strlen("Nepal");   // 5
  1. strcpy(dest, src) copies the string src into dest.
char a[20];
strcpy(a, "Hello");   // a = "Hello"
  1. strcat(s1, s2) appends s2 at the end of s1.
char s1[20] = "Good ";
strcat(s1, "Day");    // s1 = "Good Day"
  1. strcmp(s1, s2) compares two strings. It returns 0 if equal, a negative value if s1 < s2 and a positive value if s1 > s2.
strcmp("abc", "abc");   // 0
  1. strrev(s) reverses the string (available in some compilers such as Turbo C, not in standard C).
char s[] = "abc";
strrev(s);              // s = "cba"
  1. strupr(s) converts the string to upper case (and strlwr(s) to lower case). These are also compiler specific.
char s[] = "nepal";
strupr(s);              // s = "NEPAL"

Example program

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

int main() {
    char a[30] = "Hello", b[30] = "World";
    printf("Length of a = %d\n", (int)strlen(a));
    strcat(a, b);
    printf("After strcat: %s\n", a);
    strcpy(b, a);
    printf("After strcpy: %s\n", b);
    printf("Compare: %d\n", strcmp(a, b));
    return 0;
}

Output: length 5, HelloWorld, HelloWorld, and compare result 0.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks
  • 2024 Spring · 7 marks

Write a program to generate a Fibonacci series of n numbers using a recursive function.

Answer

The Fibonacci series is 0,1,1,2,3,5,8,…0, 1, 1, 2, 3, 5, 8, \ldots in which every term is the sum of the previous two terms:

F(n)=F(n−1)+F(n−2),F(0)=0, F(1)=1F(n) = F(n-1) + F(n-2), \qquad F(0)=0,\ F(1)=1

A recursive function calls itself with smaller arguments until it reaches the base cases n=0n=0 and n=1n=1.

#include <stdio.h>

int fib(int n) {
    if (n == 0)
        return 0;
    if (n == 1)
        return 1;
    return fib(n - 1) + fib(n - 2);
}

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

    printf("Fibonacci series: ");
    for (i = 0; i < n; i++)
        printf("%d ", fib(i));
    return 0;
}

Sample run: for n=7n = 7 the output is 0 1 1 2 3 5 8.

For example, F(4)=F(3)+F(2)=2+1=3F(4) = F(3) + F(2) = 2 + 1 = 3.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks
  • 2024 Spring · 8 marks

Create the following structure of the student.
NameAddressEmailDate of Birth (dd, mm, yy)
Input the n number of student and display the name of those students whose address is "Pokhara".

Answer

A structure groups items of different types under one name. Here a nested structure is used for the date of birth.

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

struct date {
    int dd, mm, yy;
};

struct student {
    char name[30];
    char address[30];
    char email[40];
    struct date dob;
};

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

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

    for (i = 0; i < n; i++) {
        printf("\nStudent %d\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", s[i].name);
        printf("Address: ");
        scanf(" %[^\n]", s[i].address);
        printf("Email: ");
        scanf("%s", s[i].email);
        printf("Date of birth (dd mm yy): ");
        scanf("%d %d %d", &s[i].dob.dd, &s[i].dob.mm, &s[i].dob.yy);
    }

    printf("\nStudents from Pokhara:\n");
    for (i = 0; i < n; i++) {
        if (strcmp(s[i].address, "Pokhara") == 0) {
            printf("%s\n", s[i].name);
            found = 1;
        }
    }
    if (!found)
        printf("No student from Pokhara.\n");
    return 0;
}

strcmp() returns 0 when the address equals "Pokhara", and only then is the name displayed. The array holds up to 100 students, so n≤100n \le 100.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks
  • 2024 Spring · 8 marks

What are pointers? Explain Dynamic memory allocation and deallocation using pointer.

Answer

Pointer

A pointer is a variable that stores the memory address of another variable. It is declared with * and the address is obtained with &.

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

Dynamic memory allocation (DMA)

Normally the size of arrays is fixed at compile time. DMA allows memory to be allocated and released at run time from the heap, using functions of <stdlib.h>. The memory is accessed through pointers.

  1. malloc(size) allocates size bytes and returns a pointer to the first byte; the memory is uninitialised.
  2. calloc(n, size) allocates space for n elements of size bytes each and initialises them to zero.
  3. realloc(ptr, newsize) changes the size of an already allocated block.
  4. free(ptr) releases (deallocates) the memory so that it can be reused.

If allocation fails, malloc and calloc return NULL, so the pointer should be checked.

Example

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

int main() {
    int *p, n, i, sum = 0;
    printf("How many numbers? ");
    scanf("%d", &n);

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

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

    free(p);     // deallocation
    return 0;
}

The memory for nn integers is obtained at run time with malloc and returned to the system with free. Forgetting free causes a memory leak.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

Why file handling is necessary in C program? Explain various file opening modes in C program.

Answer

Why file handling is necessary

Variables and arrays live in RAM, and their data is lost when the program ends. Files store data permanently on disk, so file handling is needed because:

  1. Data is stored permanently and can be used again later.
  2. Large amounts of data can be handled that would not fit in memory or be typed repeatedly.
  3. Data can be shared between different programs.
  4. Input can be read from a file and output written to a file instead of the keyboard and screen.
  5. Records can be added, updated and searched, as in a database.

A file is accessed through a pointer of type FILE *, opened with fopen(filename, mode) and closed with fclose().

File opening modes

ModeMeaning
"r"Open an existing file for reading. Returns NULL if the file does not exist.
"w"Open for writing. Creates the file, or erases existing contents.
"a"Open for appending. Data is added at the end; file is created if absent.
"r+"Open an existing file for reading and writing.
"w+"Open for reading and writing. Creates the file or erases existing contents.
"a+"Open for reading and appending.

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

Example

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

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

Write a program to open a file named "teachers.txt" to keep the records of faculty members (eid, name, address, Department, mobile) and insert records into a file and display all records of teachers on screen.

Answer

The program defines a structure for a faculty member, writes the records into teachers.txt and then reads the file back to display all records.

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

struct teacher {
    int eid;
    char name[30];
    char address[30];
    char department[30];
    char mobile[15];
};

int main() {
    FILE *fp;
    struct teacher t;
    int n, i;

    fp = fopen("teachers.txt", "w");
    if (fp == NULL) {
        printf("Cannot open file");
        exit(1);
    }

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

    for (i = 0; i < n; i++) {
        printf("\nTeacher %d\n", i + 1);
        printf("EID: ");
        scanf("%d", &t.eid);
        printf("Name: ");
        scanf(" %[^\n]", t.name);
        printf("Address: ");
        scanf(" %[^\n]", t.address);
        printf("Department: ");
        scanf(" %[^\n]", t.department);
        printf("Mobile: ");
        scanf("%s", t.mobile);
        fprintf(fp, "%d,%s,%s,%s,%s\n", t.eid, t.name, t.address, t.department, t.mobile);
    }
    fclose(fp);

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

    printf("\nEID\tName\tAddress\tDepartment\tMobile\n");
    while (fscanf(fp, "%d,%29[^,],%29[^,],%29[^,],%14[^\n]\n",
                  &t.eid, t.name, t.address, t.department, t.mobile) == 5) {
        printf("%d\t%s\t%s\t%s\t%s\n", t.eid, t.name, t.address, t.department, t.mobile);
    }
    fclose(fp);
    return 0;
}

The first fopen in "w" mode creates the file for inserting records; the second in "r" mode reads them back until fscanf can no longer read five fields.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 5 marks

Write short notes on: Data types in C

Answer

A data type specifies the kind of value a variable can hold, the memory it needs and the operations allowed on it. C data types are in three groups.

  1. Basic (primitive) types
TypeSize (typical)Example
char1 byte'A'
int4 bytes25
float4 bytes3.14f
double8 bytes3.14159265
voidno valuefunction returning nothing

Modifiers short, long, signed and unsigned change the size or range, for example unsigned int or long int.

  1. Derived types: array, pointer, function.

  2. User-defined types: structure (struct), union, enumeration (enum) and types created with typedef.

Example: int age = 20; float marks = 85.5; char grade = 'A';

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 5 marks

Write short notes on: Recursive function

Answer

A recursive function is a function that calls itself, directly or indirectly, to solve a problem by reducing it to smaller instances of the same problem. Every recursive function needs:

  1. a base case that stops the recursion, and
  2. a recursive case that calls the function with a smaller argument.

Without a base case the function calls itself endlessly and the stack overflows.

Example: factorial

n!=n×(n−1)!,0!=1n! = n \times (n-1)!, \qquad 0! = 1

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

For fact(3): 3×2×1×1=63 \times 2 \times 1 \times 1 = 6.

Merits: code is short and natural for problems such as factorial, Fibonacci, Tower of Hanoi and tree traversal. Demerits: each call uses stack memory and time, so it is slower than iteration and can overflow the stack for deep recursion.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 2+5 marks

Why C is called middle level language? Explain C program execution with suitable diagram.

Answer

Why C is called a middle level language

C combines features of both high level and low level languages.

  • Like high level languages, it has functions, structured control statements, data types, and is portable and English-like.
  • Like low level languages, it can access memory directly through pointers, supports bitwise operations, and can be used to write operating systems and device drivers (UNIX is written in C).

Because it joins the readability of high level languages with the hardware control of assembly language, it is called middle level.

Execution of a C program

A C program passes through the following stages.

Source code (.c)
      |
      v
Preprocessor      -- expands #include, #define, removes comments
      |
      v
Expanded source
      |
      v
Compiler          -- checks syntax, produces assembly/object code
      |
      v
Object code (.obj / .o)
      |
      v
Linker            -- combines object code with library functions
      |
      v
Executable file (.exe / a.out)
      |
      v
Loader -> Execution by CPU -> Output
  1. Editing: the program is written and saved as a .c file.
  2. Preprocessing: directives such as #include and #define are processed.
  3. Compilation: syntax errors are reported; error-free code is converted to object code.
  4. Linking: library code (for example printf) is linked to produce the executable.
  5. Loading and execution: the loader places the program in memory and the CPU runs it, giving the output.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks

What is Datatype? List out datatypes available in c. Explain Assignment and ternary operator with suitable example.

Answer

Data type

A data type tells the compiler what kind of data a variable will store, how much memory to reserve for it and which operations are valid.

Data types in C

  • Basic: char, int, float, double, void
  • Modifiers: short, long, signed, unsigned
  • Derived: array, pointer, function
  • User-defined: struct, union, enum, typedef

Assignment operators

They assign a value to a variable. The simple assignment operator is =; compound operators combine an arithmetic operation with assignment.

OperatorExampleSame as
=a = 5store 5 in a
+=a += 3a = a + 3
-=a -= 3a = a - 3
*=a *= 3a = a * 3
/=a /= 3a = a / 3
%=a %= 3a = a % 3
int a = 10;
a += 5;     // a becomes 15

Ternary (conditional) operator

It is the only C operator with three operands and is a short form of if-else.

variable = (condition) ? value_if_true : value_if_false;

If the condition is true the first value is used, otherwise the second.

#include <stdio.h>
int main() {
    int a = 12, b = 20, max;
    max = (a > b) ? a : b;
    printf("Larger = %d", max);
    return 0;
}

Output: Larger = 20, because a > b is false so b is selected.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks

What is function? Write a program to find factorial of given number using user defined function.

Answer

Function

A function is a named, self-contained block of statements that performs a specific task. It is written once and can be called many times. It helps to divide a big program into smaller modules, avoids repetition and makes the program easier to test and maintain. Functions are of two kinds: library functions (such as printf) and user defined functions.

Program: factorial using a user defined function

The factorial of nn is

n!=n×(n−1)×⋯×2×1,0!=1n! = n \times (n-1) \times \cdots \times 2 \times 1, \qquad 0! = 1

#include <stdio.h>

long factorial(int n) {
    long f = 1;
    int i;
    for (i = 1; i <= n; i++)
        f = f * i;
    return f;
}

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

    if (n < 0)
        printf("Factorial is not defined for negative numbers.");
    else
        printf("Factorial of %d = %ld", 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 Factorial of 5 = 120.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

WAP Program to calculate the following structure
*
**
***
****
*****

Answer

The pattern has 5 rows, and row ii contains ii stars. Two nested loops are used: the outer loop for rows and the inner loop for stars in each row.

#include <stdio.h>

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

Output:

*
**
***
****
*****

The total number of stars printed is 1+2+3+4+5=151+2+3+4+5 = 15.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks
  • 2024 Spring · 8 marks

Write a program to find the smallest and largest number in an array.

Answer

The first element is assumed to be both smallest and largest. The array is then scanned, and small or large is updated whenever a smaller or larger element is found.

#include <stdio.h>

int main() {
    int a[100], n, i, small, large;

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

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

    small = large = a[0];
    for (i = 1; i < n; i++) {
        if (a[i] < small)
            small = a[i];
        if (a[i] > large)
            large = a[i];
    }

    printf("Smallest = %d\n", small);
    printf("Largest = %d\n", large);
    return 0;
}

Sample: for 7 3 15 9 2, the smallest is 2 and the largest is 15.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 2+6 marks

Define String. Explain String handling function with example

Answer

String

A string is a sequence of characters ending with the null character '\0'. It is stored in a character array, for example char s[10] = "Hello";, which occupies 6 bytes including '\0'.

String handling functions (declared in <string.h>)

FunctionPurposeExample
strlen(s)Length of string, without '\0'strlen("Hello") gives 5
strcpy(d, s)Copy s into dstrcpy(d, "Hi")
strcat(s1, s2)Append s2 to the end of s1"Good " + "Day" gives "Good Day"
strcmp(s1, s2)Compare; 0 if equal, negative if s1 < s2, positive if s1 > s2strcmp("a", "b") is negative
strrev(s)Reverse the string (compiler specific)"abc" becomes "cba"
strlwr(s) / strupr(s)Convert to lower / upper case (compiler specific)"Ab" becomes "ab" / "AB"

Example

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

int main() {
    char s1[30] = "Hello", s2[30] = "World", s3[30];

    printf("Length = %d\n", (int)strlen(s1));
    strcpy(s3, s1);
    strcat(s3, s2);
    printf("Joined = %s\n", s3);
    if (strcmp(s1, s2) == 0)
        printf("Equal\n");
    else
        printf("Not equal\n");
    return 0;
}

Output: Length = 5, Joined = HelloWorld, Not equal.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 2+5 marks

Write the importance of pointer? Explain DMA with example.

Answer

Importance of pointers

A pointer is a variable that holds the address of another variable. It is important because:

  1. It allows dynamic memory allocation at run time.
  2. It lets functions change the actual arguments (call by reference) and return more than one value.
  3. It gives fast and efficient access to array elements and strings.
  4. It is the basis for data structures such as linked lists, stacks, queues and trees.
  5. It reduces memory use and execution time, since addresses are passed instead of copying large data.
  6. It allows direct access to memory, hardware and system resources.

Dynamic Memory Allocation (DMA)

DMA is the process of allocating memory during program execution rather than at compile time, so the size can depend on user input. The functions in <stdlib.h> are:

  • malloc(size) allocates a block of size bytes.
  • calloc(n, size) allocates n blocks and sets them to zero.
  • realloc(ptr, newsize) resizes a block.
  • free(ptr) releases the memory.

Example

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

int main() {
    int *p, n, i;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    p = (int *)calloc(n, sizeof(int));
    if (p == NULL) {
        printf("Allocation failed");
        return 1;
    }

    for (i = 0; i < n; i++) {
        printf("Enter element %d: ", i + 1);
        scanf("%d", &p[i]);
    }
    printf("You entered: ");
    for (i = 0; i < n; i++)
        printf("%d ", p[i]);

    free(p);
    return 0;
}

The array size nn is not known until the program runs; calloc reserves exactly n×sizeof(int)n \times \text{sizeof(int)} bytes and free returns it afterwards.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks
  • 2024 Spring · 7 marks

Define a multidimensional array. How is it declared and initialized? WAP to transpose 3x3 Matrix.

Answer

Multidimensional array

A multidimensional array is an array with two or more subscripts. A two dimensional array represents a table or matrix of rows and columns, and all elements have the same type.

Declaration

data_type array_name[rows][columns];
int a[3][3];

Initialisation

int a[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

Elements are accessed as a[i][j] with indices starting from 0.

Program to transpose a 3x3 matrix

The transpose BB of a matrix AA is obtained by interchanging rows and columns:

Bji=AijB_{ji} = A_{ij}

#include <stdio.h>

int main() {
    int a[3][3], t[3][3], i, j;

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

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

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

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

Sample: the matrix 1 2 3 / 4 5 6 / 7 8 9 has transpose 1 4 7 / 2 5 8 / 3 6 9.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks

Write a menu driven program to perform following task:
Menu (i) Check the given number is even or odd. (ii) Find the area of circle. (iii) Area of rectangle. (iv) exit from program.

Answer

The program shows the menu repeatedly inside a do-while loop, reads the choice and uses a switch statement to run the selected task, until the user chooses 4.

Formulas: area of circle =πr2= \pi r^2 (with π=3.14159\pi = 3.14159), area of rectangle =l×b= l \times b.

#include <stdio.h>

#define PI 3.14159

int main() {
    int choice, n;
    float r, l, b;

    do {
        printf("\n----- Menu -----\n");
        printf("1. Check even or odd\n");
        printf("2. Area of circle\n");
        printf("3. Area of rectangle\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter a number: ");
                scanf("%d", &n);
                if (n % 2 == 0)
                    printf("%d is even\n", n);
                else
                    printf("%d is odd\n", n);
                break;
            case 2:
                printf("Enter radius: ");
                scanf("%f", &r);
                printf("Area of circle = %.2f\n", PI * r * r);
                break;
            case 3:
                printf("Enter length and breadth: ");
                scanf("%f %f", &l, &b);
                printf("Area of rectangle = %.2f\n", l * b);
                break;
            case 4:
                printf("Exiting program\n");
                break;
            default:
                printf("Invalid choice\n");
        }
    } while (choice != 4);

    return 0;
}

Check: for radius 2, area =3.14159×4=12.57= 3.14159 \times 4 = 12.57; for length 5 and breadth 3, area =15.00= 15.00.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

Write a program to input data of 10 student's name, roll and address in a file 'University.txt' and display the records from file.

Answer

The program writes the name, roll and address of 10 students into University.txt and then reopens the file to read and display the records.

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

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

int main() {
    FILE *fp;
    struct student s;
    int i;

    fp = fopen("University.txt", "w");
    if (fp == NULL) {
        printf("Cannot open file");
        exit(1);
    }

    for (i = 0; i < 10; i++) {
        printf("\nStudent %d\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", s.name);
        printf("Roll: ");
        scanf("%d", &s.roll);
        printf("Address: ");
        scanf(" %[^\n]", s.address);
        fprintf(fp, "%s,%d,%s\n", s.name, s.roll, s.address);
    }
    fclose(fp);

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

    printf("\nName\tRoll\tAddress\n");
    while (fscanf(fp, "%29[^,],%d,%29[^\n]\n", s.name, &s.roll, s.address) == 3)
        printf("%s\t%d\t%s\n", s.name, s.roll, s.address);
    fclose(fp);
    return 0;
}

Mode "w" creates the file for writing, and mode "r" reads the stored records back. Each record is written as one line with comma separated fields.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 2+6 marks

What is Top-Down Analysis? Why decomposition of project in different modules is necessary in Programming.

Answer

Top-down analysis: Top-down analysis (top-down design) is an approach in which a large problem is first stated as a whole and then repeatedly divided into smaller, simpler sub-problems (modules) until each can be solved easily. The design goes from the general to the specific, for example main() calls functions for input, processing and output.

Payroll system
 |-- Input employee data
 |-- Calculate salary
 |     |-- Basic pay
 |     |-- Allowances / deductions
 |-- Print report

Why decomposition into modules is necessary

  • Simplicity: a complex problem becomes small manageable parts.
  • Reusability: a module (function) can be used many times and in other programs.
  • Easy debugging and testing: each module can be tested separately, and errors are located quickly.
  • Team work: different programmers can develop different modules at the same time.
  • Easy maintenance and modification: a change in one module does not disturb the others.
  • Readability and less repeated code.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 5 marks

Write short notes on: Nested Loop

Answer

A nested loop is a loop placed inside the body of another loop. The inner loop completes all its iterations for each single iteration of the outer loop. If the outer loop runs mm times and the inner loop nn times, the inner body executes m×nm \times n times.

Any loops (for, while, do-while) can be nested.

for (i = 1; i <= 3; i++) {          /* outer loop */
    for (j = 1; j <= 3; j++) {      /* inner loop */
        printf("%d ", i * j);
    }
    printf("\n");
}

Output:

1 2 3
2 4 6
3 6 9

Uses: printing patterns, processing matrices (two-dimensional arrays), multiplication tables and sorting algorithms such as bubble sort.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

What do you mean by Variable and keywords? Give examples.

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.

Rules for naming: it may contain letters, digits and underscore; it must begin with a letter or underscore; it cannot contain spaces or special symbols; it cannot be a keyword; and C is case sensitive.

int age = 20;
float salary = 45000.50;
char grade = 'A';

Keywords: Keywords are reserved words with a fixed meaning for the compiler. They cannot be used as variable names. They are written in lowercase. C has 32 keywords (in the original standard).

Examples: int, float, char, double, if, else, for, while, do, switch, case, break, continue, return, void, struct, union, static, const, sizeof.

int main() {      /* int, return are keywords */
    int count = 0; /* count is a variable */
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 8 marks

List out the different types of operators. Illustrate bitwise operators with the example.

Answer

Types of operators in C

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

Bitwise operators: They work on the individual bits of integer operands.

OperatorNameRule
&AND1 only if both bits are 1
|OR1 if at least one bit is 1
^XOR1 if the bits differ
~NOTinverts every bit
<<left shiftshifts bits left (multiplies by 2 per shift)
>>right shiftshifts bits right (divides by 2 per shift)

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

int a = 12, b = 10;
printf("%d", a & b);    /* 1000 = 8  */
printf("%d", a | b);    /* 1110 = 14 */
printf("%d", a ^ b);    /* 0110 = 6  */
printf("%d", ~a);       /* -13       */
printf("%d", a << 1);   /* 24        */
printf("%d", a >> 1);   /* 6         */

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

Explain file handling functions and mode with examples.

Answer

File handling in C means storing data permanently on disk and reading it back later. A file is accessed through a pointer of type FILE * declared in <stdio.h>. The usual steps are: declare a file pointer, open the file, read or write, and close the file.

(a) Common file handling functions

FunctionPurpose
fopen(name, mode)Opens a file and returns a FILE * (NULL on failure)
fclose(fp)Closes the file and flushes the buffer
fprintf(fp, ...) / fscanf(fp, ...)Formatted write / read
fputc(c, fp) / fgetc(fp)Write / read one character
fputs(s, fp) / fgets(s, n, fp)Write / read a string
fwrite() / fread()Write / read blocks (records) in binary form
fseek(fp, offset, origin)Move the file position
ftell(fp) / rewind(fp)Get the current position / go to the start
feof(fp)Tests end of file

(b) File modes

ModeMeaning
"r"Open an existing file for reading; fails if the file does not exist
"w"Create a file for writing; an existing file is erased
"a"Open or create a file and append at the end
"r+"Read and write an existing file
"w+"Read and write; creates a new file or erases the old one
"a+"Read and append
"rb", "wb", "ab"Binary versions of the modes above

(c) Example

#include <stdio.h>

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

    fp = fopen("data.txt", "w");      /* write mode */
    if (fp == NULL) {
        printf("Cannot open file");
        return 1;
    }
    fprintf(fp, "%s %d\n", "Ram", 20);
    fclose(fp);

    fp = fopen("data.txt", "r");      /* read mode */
    fscanf(fp, "%s %d", name, &age);
    printf("Name: %s, Age: %d", name, age);
    fclose(fp);
    return 0;
}

The program first writes one record into data.txt using mode "w" and then reads it back using mode "r".

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 7 marks

What are character arrays? How is it different from an integer array? Explain 5 string functions with example.

Answer

Character array

A character array is a collection of characters stored in consecutive memory locations. It is used to store strings. A string ends with the null character '\0', so an array holding a string of nn characters needs n+1n+1 elements.

char name[10] = "Nepal";   /* stores N e p a l \0 */

Difference from an integer array

Character arrayInteger array
Elements are of type char (1 byte each)Elements are of type int (usually 2 or 4 bytes each)
Normally ends with the null character '\0'Has no terminator
Can be read and printed as a whole with %s, gets(), puts()Must be read and printed element by element in a loop
Can be initialised with a string literalInitialised with a list of numbers
String library functions work on itNo such functions

Five string functions (header <string.h>)

  1. strlen(s) returns the number of characters, excluding '\0'. strlen("Nepal") gives 5.
  2. strcpy(dest, src) copies src into dest. strcpy(a, "Ram") makes a equal to "Ram".
  3. strcat(s1, s2) appends s2 to the end of s1. If s1 = "Hello " and s2 = "World", s1 becomes "Hello World".
  4. strcmp(s1, s2) compares two strings. It returns 0 if they are equal, a negative value if s1 < s2 and a positive value if s1 > s2. strcmp("abc", "abc") gives 0.
  5. strrev(s) reverses a string (available in some compilers such as Turbo C). strrev("abc") gives "cba". An alternative is strupr()/strlwr() for case conversion.
#include <stdio.h>
#include <string.h>

int main() {
    char a[30] = "Hello ", b[30] = "World", c[30];
    printf("%d\n", (int)strlen(a));   /* 6 */
    strcpy(c, b);                     /* c = World */
    strcat(a, b);                     /* a = Hello World */
    printf("%s\n", a);
    printf("%d\n", strcmp(b, c));     /* 0 */
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 Spring · 5 marks

Write short notes on: History of C

Answer

C is a general purpose, structured programming language developed by Dennis Ritchie at AT&T Bell Laboratories in 1972.

  • ALGOL (1960) was the ancestor of structured languages. It was too abstract for system work.
  • BCPL (1967) was developed by Martin Richards for writing system software.
  • B (1970) was developed by Ken Thompson at Bell Labs, based on BCPL. It was typeless and was used on the first UNIX.
  • C (1972) was developed by Dennis Ritchie, who added data types and other features to B. It was used to rewrite the UNIX operating system, and most of UNIX is written in C.
  • K&R C (1978): Brian Kernighan and Dennis Ritchie published the book The C Programming Language, which served as an informal standard.
  • ANSI C (1989): the American National Standards Institute standardised the language (C89). ISO adopted it as C90.
  • C99, C11, C17 are later revisions that added features such as // comments, long long, inline functions and better library support.

C is the base for many later languages such as C++, Java and C#. It is still widely used for system software, embedded systems and compilers.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 8 marks

List the features of C. Write an algorithm and draw the flowchart to find the smallest number among any three number entered by user.

Answer

(a) Features of C

  1. Simple and efficient: it has a small set of keywords and produces fast executable code.
  2. Structured language: programs are divided into functions (modules), which makes them easy to understand and debug.
  3. Portable: a C program written for one machine can run on another with little or no change.
  4. Rich set of operators and data types, including arrays, structures, unions and pointers.
  5. Middle level language: it combines the features of high level languages with the low level access (memory, bits) of assembly.
  6. Pointers and dynamic memory allocation give direct control of memory.
  7. Extensible: programmers can add their own functions to the library.
  8. Case sensitive and supports recursion and a rich standard library.

(b) Algorithm to find the smallest of three numbers

  1. Start
  2. Read three numbers aa, bb, cc
  3. If a<ba < b and a<ca < c, then smallest = aa
  4. Else if b<cb < c, then smallest = bb
  5. Else smallest = cc
  6. Print smallest
  7. Stop

Flowchart

        ( Start )
            |
      /Read a, b, c/
            |
     < a<b AND a<c ? >--Yes--> [small = a] --+
            |No                               |
        < b < c ? >-----Yes--> [small = b] ---+
            |No                               |
        [small = c] --------------------------+
                                              |
                                      /Print small/
                                              |
                                          ( Stop )

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 7 marks

What is Operator? List out operators available in c. Explain increment and decrement operator with suitable example.

Answer

Operator

An operator is a symbol that tells the compiler to perform a specific mathematical, logical or relational operation on operands. For example, in a + b, + is the operator and a, b are operands.

Operators available in C

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

Increment and decrement operators

++ increases the value of a variable by 1 and -- decreases it by 1. Each has a prefix and a postfix form.

  • Prefix (++x, --x): the value is changed first, then used in the expression.
  • Postfix (x++, x--): the current value is used in the expression first, then the variable is changed.
#include <stdio.h>
int main() {
    int x = 5, y;
    y = ++x;      /* x = 6, y = 6 */
    printf("%d %d\n", x, y);
    y = x++;      /* y = 6, x = 7 */
    printf("%d %d\n", x, y);
    y = --x;      /* x = 6, y = 6 */
    printf("%d %d\n", x, y);
    y = x--;      /* y = 6, x = 5 */
    printf("%d %d\n", x, y);
    return 0;
}

Output:

6 6
7 6
6 6
5 6

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 8 marks

Write a program to open a file named "students.txt" and insert record of 10 students (age, name, address, roll). Also display all records of students on screen.

Answer

#include <stdio.h>

struct student {
    int age;
    char name[30];
    char address[30];
    int roll;
};

int main() {
    FILE *fp;
    struct student s;
    int i;

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

    for (i = 1; i <= 10; i++) {
        printf("Enter record of student %d\n", i);
        printf("Age: ");
        scanf("%d", &s.age);
        printf("Name: ");
        scanf(" %[^\n]", s.name);
        printf("Address: ");
        scanf(" %[^\n]", s.address);
        printf("Roll: ");
        scanf("%d", &s.roll);
        fprintf(fp, "%d,%s,%s,%d\n", s.age, s.name, s.address, s.roll);
    }
    fclose(fp);

    fp = fopen("students.txt", "r");
    if (fp == NULL) {
        printf("File cannot be opened\n");
        return 1;
    }
    printf("\nAge\tName\t\tAddress\t\tRoll\n");
    while (fscanf(fp, "%d,%29[^,],%29[^,],%d\n",
                  &s.age, s.name, s.address, &s.roll) == 4) {
        printf("%d\t%-15s %-15s %d\n", s.age, s.name, s.address, s.roll);
    }
    fclose(fp);
    return 0;
}

The file is first opened in write mode "w" and the 10 records are written with fprintf(). It is then closed and reopened in read mode "r", and each record is read with fscanf() and displayed until no more records can be read.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 7 marks

What is loop? WAP to display the following pattern
P O K H A R A
 O K H A R
  K H A
   H

Answer

Loop

A loop is a control structure that repeats a block of statements as long as a given condition is true. C provides three loops: for, while and do...while. Loops avoid writing the same code many times.

Program

For row ii (starting at 0) we print ii spaces and then the letters of "POKHARA" from index ii to 6−i6-i, each followed by a space.

#include <stdio.h>

int main() {
    char word[] = "POKHARA";
    int n = 7, i, j;

    for (i = 0; i < 4; i++) {
        for (j = 0; j < i; j++)
            printf(" ");
        for (j = i; j <= n - 1 - i; j++)
            printf("%c ", word[j]);
        printf("\n");
    }
    return 0;
}

Output:

P O K H A R A 
 O K H A R 
  K H A 
   H 

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 7 marks

What is function? List its components. Write a program to display Fibonacci series up to N terms using recursive method.

Answer

Function

A function is a self-contained block of statements that performs a specific task. It can be called from other parts of the program, which avoids repetition and makes a program modular.

Components of a function

  1. Function declaration (prototype): tells the compiler the name, return type and parameters, e.g. int fib(int n);
  2. Function definition: the body containing the statements, with a header of the form return_type name(parameter list).
  3. Function call: the statement that invokes the function, e.g. fib(5);
  4. Parameters: formal parameters in the definition and actual arguments in the call.
  5. Return statement: sends a value back to the caller, e.g. return n;

Program: Fibonacci series using recursion

The series is F0=0F_0 = 0, F1=1F_1 = 1, Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}.

#include <stdio.h>

int fib(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    return fib(n - 1) + fib(n - 2);
}

int main() {
    int n, i;
    printf("Enter number of terms: ");
    scanf("%d", &n);
    printf("Fibonacci series: ");
    for (i = 0; i < n; i++)
        printf("%d ", fib(i));
    return 0;
}

For n=7n = 7 the output is 0 1 1 2 3 5 8.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 8 marks

Write a program to input name, address, roll and age of 100 students and display the information of students whose age are less or equal to 18 in proper format using the structure.

Answer

#include <stdio.h>

struct student {
    char name[30];
    char address[30];
    int roll;
    int age;
};

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

    for (i = 0; i < 100; i++) {
        printf("Enter details of student %d\n", i + 1);
        printf("Name: ");
        scanf(" %[^\n]", s[i].name);
        printf("Address: ");
        scanf(" %[^\n]", s[i].address);
        printf("Roll: ");
        scanf("%d", &s[i].roll);
        printf("Age: ");
        scanf("%d", &s[i].age);
    }

    printf("\nStudents whose age is 18 or less\n");
    printf("%-6s %-20s %-20s %-4s\n", "Roll", "Name", "Address", "Age");
    printf("--------------------------------------------------------\n");
    for (i = 0; i < 100; i++) {
        if (s[i].age <= 18)
            printf("%-6d %-20s %-20s %-4d\n",
                   s[i].roll, s[i].name, s[i].address, s[i].age);
    }
    return 0;
}

A structure student groups the four fields. An array of 100 such structures stores the records. The second loop prints only those records with age <= 18, in a tabular format.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 7 marks

Write a program to input elements of 3 * 3 Matrix and find the sum of diagonal elements using array and pointer.

Answer

The matrix is stored in row-major order, so the element at row ii, column jj is at offset i×3+ji \times 3 + j from the first element. A pointer to the first element, p = &a[0][0], can reach every element as *(p + i*3 + j).

#include <stdio.h>

int main() {
    int a[3][3], i, j;
    int *p;
    int main_sum = 0, sec_sum = 0;

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

    p = &a[0][0];

    /* using array */
    for (i = 0; i < 3; i++) {
        main_sum += a[i][i];
        sec_sum += a[i][2 - i];
    }
    printf("Using array: main diagonal = %d, other diagonal = %d\n",
           main_sum, sec_sum);

    /* using pointer */
    main_sum = 0;
    sec_sum = 0;
    for (i = 0; i < 3; i++) {
        main_sum += *(p + i * 3 + i);
        sec_sum += *(p + i * 3 + (2 - i));
    }
    printf("Using pointer: main diagonal = %d, other diagonal = %d\n",
           main_sum, sec_sum);
    return 0;
}

For the matrix 1 2 3 / 4 5 6 / 7 8 9, the main diagonal sum is 1+5+9=151+5+9 = 15 and the other diagonal sum is 3+5+7=153+5+7 = 15.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 8 marks

Why do we declare a variable? List out the rules we need to follow while giving the name to a variable. Also provide the data type and declare variables for the following:
(i) Age of the student (ii) Distance covered by the vehicle. (iii) Area of city (iv) Name of country

Answer

Why we declare a variable

A variable is a named memory location that holds data which may change during execution. Declaring it tells the compiler the variable's name and data type, so the compiler can reserve the right amount of memory, decide which operations are valid, and check for errors.

Rules for naming a variable

  1. It may contain letters, digits and the underscore _ only.
  2. It must begin with a letter or an underscore, not a digit.
  3. No spaces or special symbols (such as @, #, -) are allowed.
  4. A keyword (e.g. int, float, while) cannot be used as a name.
  5. Names are case sensitive: Age and age are different.
  6. A name should be meaningful and unique within its scope.

Declarations

ItemData typeDeclaration
(i) Age of the studentintint age;
(ii) Distance covered by the vehiclefloatfloat distance;
(iii) Area of cityfloat (or double)float area;
(iv) Name of countrychar arraychar country[30];

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 7 marks

Define data flow diagram. Explain the importance of decomposing a project into various modules?

Answer

Data flow diagram (DFD)

A data flow diagram is a graphical tool that shows how data moves through a system: where it comes from, how it is processed, where it is stored and where it goes. It shows what the system does, not how or in what order. The main symbols are:

  • Process (circle or rounded rectangle): transforms data.
  • Data flow (arrow): the movement of data.
  • Data store (open rectangle or two parallel lines): where data is kept.
  • External entity (rectangle): a source or destination of data outside the system.

A DFD is drawn at levels: the context diagram (level 0) shows the whole system as one process, and lower levels break it into more detail.

Importance of decomposing a project into modules

  1. Reduces complexity: a large problem is split into small, manageable parts that are easier to understand.
  2. Easier development: different modules can be developed by different programmers at the same time.
  3. Easier testing and debugging: each module can be tested separately, so errors are found and fixed quickly.
  4. Reusability: a module such as a sorting routine can be used in other programs.
  5. Easier maintenance: a change in one module has little effect on the others.
  6. Better planning and control: the time and cost of each module can be estimated and tracked.
  7. Clarity: it gives a clear structure of the system, which helps documentation.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 Spring · 8 marks

Write a menu driven program to perform following task:
Menu (i) Check the given number is even or odd. (ii) Check the given number is prime or composite. (iii) Check the given number is positive or negative. (iv) Exit from program.

Answer

#include <stdio.h>

int main() {
    int choice, n, i, prime;

    do {
        printf("\n----- MENU -----\n");
        printf("1. Check even or odd\n");
        printf("2. Check prime or composite\n");
        printf("3. Check positive or negative\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
        case 1:
            printf("Enter a number: ");
            scanf("%d", &n);
            if (n % 2 == 0)
                printf("%d is even\n", n);
            else
                printf("%d is odd\n", n);
            break;

        case 2:
            printf("Enter a number: ");
            scanf("%d", &n);
            if (n < 2) {
                printf("%d is neither prime nor composite\n", n);
            } else {
                prime = 1;
                for (i = 2; i * i <= n; i++) {
                    if (n % i == 0) {
                        prime = 0;
                        break;
                    }
                }
                if (prime)
                    printf("%d is prime\n", n);
                else
                    printf("%d is composite\n", n);
            }
            break;

        case 3:
            printf("Enter a number: ");
            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 4:
            printf("Exiting program\n");
            break;

        default:
            printf("Invalid choice\n");
        }
    } while (choice != 4);

    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from PU BCA 2025 Spring Business and Technical Communication (New) (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall Business and Technical Communication (New) (Pokhara University BCA, Fall 2024), PU BCA 2025 Spring Programming in C (Pokhara University BCA semester exam, Spring 2025), PU BCA 2024 Spring (New) Programming in C (Pokhara University BCA semester exam, Spring 2024, new syllabus), PU BCA 2024 Spring Programming in C (Pokhara University BCA semester exam, Spring 2024), PU BCA 2024 Pre-University Examination (Spring) Programming in C (Pokhara University BCA semester exam, Pre-university exam, Semester II Spring 2024), PU BCA 2023 Spring Programming in C (Pokhara University BCA semester exam, Spring 2023), PU BCA 2025 Spring (New) Financial Accounting (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall (New) Financial Accounting (Pokhara University BCA, Fall 2024), PU BCA 2024 Spring (New) Financial Accounting (Pokhara University BCA, Spring 2024), PU BCA 2024 Pre-University Examination (Semester II Spring), NAST Financial Accounting (Pokhara University BCA, Pre-university exam at National Academy of Science and Technology, Dhangadhi (affiliated to Pokhara University), Semester II Spring 2024), PU BCA 2024 Spring (Financial Accounting I) Financial Accounting (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring (Financial Accounting I) Financial Accounting (Pokhara University BCA, Spring 2023), PU BCA 2025 Spring (New) Mathematics II (Pokhara University BCA semester exam), PU BCA 2024 Fall (New) Mathematics II (Pokhara University BCA semester exam), PU BCA 2024 Spring (New) Mathematics II (Pokhara University BCA semester exam), PU BCA 2024 Pre-University Examination (Semester II Spring) Mathematics II (Pre-university exam, Semester II Spring 2024), PU BCA 2023 Spring Mathematics II (Pokhara University BCA semester exam), PU BCA 2025 Spring Microprocessor and Computer Architecture (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall (New) Microprocessor and Computer Architecture (Pokhara University BCA, Fall 2024, new syllabus), PU BCA 2024 Pre-University Examination (Semester II Spring) Microprocessor and Computer Architecture (Pokhara University BCA, Pre-university exam, Semester II Spring 2024), PU BCA 2024 Spring (Microprocessor) Microprocessor and Computer Architecture (Pokhara University BCA, Spring 2024, Microprocessor (SAP) paper), PU BCA 2024 Spring Microprocessor and Computer Architecture (Pokhara University BCA, Spring 2024), PU BCA 2024 First Terminal Exam (Set B) Microprocessor and Computer Architecture (Pokhara University BCA, First terminal examination 2024, Set B, college-level exam), PU BCA 2024 First Terminal Exam Microprocessor and Computer Architecture (Pokhara University BCA, First terminal examination, college-level exam (year as listed on source page: 2024)) and PU BCA 2023 Spring Microprocessor and Computer Architecture (Pokhara University BCA, Spring 2023). Answers are written for this site; check them against your class notes.