Skip to main content

Chapter 2

C Programming

TU BIT past exam questions

Past questions and answers

72 questions set from this chapter. Most repeated first.

  • 2077 · 5 marks

What is the basic structure of a C program? Explain each part.

Similar questions: Describe the basic structure of a (2078)

Answer

Basic structure of a C program

/* Documentation section */
#include <stdio.h>          /* Link section */
#define PI 3.1416           /* Definition section */

int total = 0;              /* Global declaration */

int square(int x);          /* Function prototype */

int main()                  /* Main function */
{
    int a = 5;              /* Declaration part */
    total = square(a);      /* Executable part */
    printf("%d", total);
    return 0;
}

int square(int x)           /* Sub-program section */
{
    return x * x;
}

Explanation of each part

  1. Documentation section: comments (/* ... */ or //) giving the program name, author and purpose. The compiler ignores them.
  2. Link section (preprocessor directives): #include lines that bring in header files such as stdio.h and math.h, so library functions can be used.
  3. Definition section: #define defines symbolic constants and macros.
  4. Global declaration section: variables declared outside all functions, usable by all functions, and user-defined function prototypes.
  5. main() function: every C program has exactly one main(), where execution begins and ends. It has two parts:
    • Declaration part: declares the local variables.
    • Executable part: the statements that do the work (input, processing, output). The braces { } mark its beginning and end, and each statement ends with a semicolon.
  6. Sub-program (user-defined function) section: functions written by the programmer, defined before or after main(), and called from it.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Describe the basic structure of a C program and explain each part.

Similar questions: What is the basic structure of (2077)

Answer

A C program is organised into the following sections.

/* 1. Documentation section */
/* Program to add two numbers */

#include <stdio.h>        /* 2. Link section */
#define PI 3.14159        /* 3. Definition section */

int total = 0;            /* 4. Global declaration section */

int add(int, int);        /* function prototype */

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

int add(int x, int y) {   /* 6. Subprogram (user-defined function) section */
    return x + y;
}
  1. Documentation section: comments giving the program name, author and purpose; ignored by the compiler.
  2. Link section: #include directives that link header files containing library functions (stdio.h, math.h).
  3. Definition section: symbolic constants and macros defined with #define.
  4. Global declaration section: variables and function prototypes visible to all functions.
  5. main() function section: every program must have exactly one main(), where execution starts. It has a declaration part and an executable part enclosed in { }.
  6. Subprogram section: user-defined functions called from main() or each other.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Why data file is needed? Write a program to write N numbers in file 'number.txt' and then read it and display only even numbers.

Similar questions: Write a program to write N (2081)

Answer

Need for data files

Variables and arrays live in RAM and their contents are lost when the program ends. A data file stores data permanently on disk so that it can be used again later, shared between programs, and used to handle large volumes of data that cannot be re-entered each time or kept in memory.

Program

#include <stdio.h>

int main()
{
    FILE *fp;
    int n, i, num;

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

    fp = fopen("number.txt", "w");
    if (fp == NULL)
    {
        printf("Cannot open file\n");
        return 1;
    }
    printf("Enter %d numbers:\n", n);
    for (i = 0; i < n; i++)
    {
        scanf("%d", &num);
        fprintf(fp, "%d\n", num);
    }
    fclose(fp);

    fp = fopen("number.txt", "r");
    if (fp == NULL)
    {
        printf("Cannot open file\n");
        return 1;
    }
    printf("Even numbers in the file:\n");
    while (fscanf(fp, "%d", &num) == 1)
    {
        if (num % 2 == 0)
            printf("%d ", num);
    }
    printf("\n");
    fclose(fp);
    return 0;
}

The file is first opened in write mode "w" and the numbers are written with fprintf(). It is then closed and reopened in read mode "r"; fscanf() reads each number and only those divisible by 2 are displayed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write a program to write N numbers in file "number.txt" and then read it and display only even numbers.

Similar questions: Why data file is needed? Write (2080)

Answer

#include <stdio.h>

int main() {
    FILE *fp;
    int n, i, num;

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

    fp = fopen("number.txt", "w");
    if (fp == NULL) {
        printf("Cannot open file");
        return 1;
    }
    printf("Enter %d numbers: ", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &num);
        fprintf(fp, "%d\n", num);
    }
    fclose(fp);

    fp = fopen("number.txt", "r");
    if (fp == NULL) {
        printf("Cannot open file");
        return 1;
    }
    printf("Even numbers in the file:\n");
    while (fscanf(fp, "%d", &num) == 1) {
        if (num % 2 == 0)
            printf("%d\n", num);
    }
    fclose(fp);

    return 0;
}

The file is first opened in write mode ("w") to store the numbers, closed, then reopened in read mode ("r"). Each number is read with fscanf() and displayed only if num % 2 == 0.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5+5 marks

Explain the role of function in programming. How function is declared, defined and called in C? Write a program to find factorial of 'n' using recursive function.

Answer

Role of function in programming

A function is a self-contained block of code that performs a specific task and can be called whenever needed. Its roles are:

  • Modularity: a large program is divided into small manageable parts.
  • Reusability: the code is written once and used many times, which avoids repetition.
  • Easy debugging and maintenance: each function can be tested and corrected separately.
  • Readability: the program is shorter and easier to understand.
  • Team development: different programmers can write different functions.

Declaration, definition and calling of a function in C

1. Function declaration (prototype) tells the compiler the name, return type and parameters of the function before it is used.

return_type function_name(parameter_type1, parameter_type2);
int add(int, int);

2. Function definition contains the actual body of the function.

return_type function_name(parameter list)
{
    // statements
    return value;
}

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

3. Function call transfers control to the function with the actual arguments.

int s = add(5, 3);

Complete example:

#include <stdio.h>

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

int main()
{
    int s = add(5, 3);          /* call */
    printf("%d", s);
    return 0;
}

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

Program to find the factorial of n using a recursive function

#include <stdio.h>

long int fact(int n);

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

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

For n = 5 the calls are 5×4×3×2×1=1205\times4\times3\times2\times1 = 120.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5+5 marks

What is an Identifier and keyword? Explain the rules for naming valid identifiers in C with example. Write a C program to find sum of digits of a 'n' digit number.

Answer

Identifier and keyword

  • Identifier: the name given by the programmer to a variable, function, array, structure or other program element, for example sum, total_marks, main.
  • Keyword: a reserved word that has a fixed meaning to the compiler and cannot be used as an identifier, for example int, float, if, else, while, for, return, struct.

Rules for naming identifiers in C

  1. It may contain only letters (A-Z, a-z), digits (0-9) and the underscore (_).
  2. It must begin with a letter or an underscore, not a digit.
  3. Blank spaces and special symbols (such as @, #, $, -) are not allowed.
  4. It cannot be a keyword.
  5. It is case sensitive, so Sum and sum are different.
  6. The length should be reasonable (the first 31 characters are significant in standard C).

Valid: roll_no, _count, student1, Total. Invalid: 1stNo (starts with a digit), my name (space), total-marks (hyphen), float (keyword).

Program to find the sum of the digits of a number

#include <stdio.h>

int main()
{
    long int n, num, rem, sum = 0;

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

    num = n;
    if (num < 0)
        num = -num;

    while (num > 0)
    {
        rem = num % 10;      /* last digit */
        sum = sum + rem;
        num = num / 10;      /* remove last digit */
    }

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

For example, with n = 4825, the digits give 5+2+8+4=195 + 2 + 8 + 4 = 19.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 10 marks

How structure is different from union? Write a program to store and display basic information (roll, name, address, email, and phone) of students of using a structure.

Answer

Difference between structure and union

BasisStructureUnion
Keywordstructunion
MemoryEach member has its own separate memoryAll members share the same memory location
SizeSum of the sizes of all members (plus padding)Size of the largest member
AccessAll members can be used at the same timeOnly one member holds a valid value at a time
ValueChanging one member does not affect othersChanging one member overwrites the others
UseWhen all values must be stored togetherWhen memory must be saved and only one value is needed at a time

Example: for int a; float b; char c; the structure needs about 4 + 4 + 1 bytes (9, usually padded to 12), while the union needs only 4 bytes.

Program to store and display student information using a structure

#include <stdio.h>

struct student
{
    int roll;
    char name[50];
    char address[50];
    char email[50];
    char phone[15];
};

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

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

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

    printf("\n%-6s %-20s %-15s %-25s %-12s\n", "Roll", "Name", "Address", "Email", "Phone");
    for (i = 0; i < n; i++)
    {
        printf("%-6d %-20s %-15s %-25s %-12s\n",
               s[i].roll, s[i].name, s[i].address, s[i].email, s[i].phone);
    }
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

What do you mean by multi-dimensional array? Write program logic to add and display the sum of two m x n matrices.

Answer

Multi-dimensional array

A multi-dimensional array is an array with more than one dimension, that is, an array of arrays. The most common is the two-dimensional array, which represents a table or matrix of rows and columns.

Syntax:

data_type array_name[size1][size2];
int a[3][4];        /* 3 rows, 4 columns */

An element is accessed as a[i][j] (row i, column j), with indexes starting from 0. Three-dimensional arrays such as int b[2][3][4]; are also possible.

Logic to add two m x n matrices

  1. Read the order m and n.
  2. Read the elements of matrices A and B.
  3. For each i from 0 to m-1 and each j from 0 to n-1, calculate C[i][j]=A[i][j]+B[i][j]C[i][j] = A[i][j] + B[i][j].
  4. Display matrix C.

Program

#include <stdio.h>

int main()
{
    int a[10][10], b[10][10], c[10][10];
    int m, n, i, j;

    printf("Enter rows and columns: ");
    scanf("%d %d", &m, &n);

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

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

    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            c[i][j] = a[i][j] + b[i][j];

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

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Find errors (if any) in the following program and rewrite it.
#define (studio,h)

float main < >

int m [ ] [ ] = 1,2,3,4;

for(i=4,I>=0;i--)

for(j=0,j<4;j++);

m[i] [j] = a[i][j] + b[i][j];

return 0. 0;

}

Answer

Errors in the program

  1. #define (studio,h) is wrong. The header file must be included with #include <stdio.h> (stdio, not studio, and .h with a dot).
  2. float main < > is wrong. main should be int main(), with parentheses () and not < >, and the function body must begin with {, which is missing.
  3. int m [ ] [ ] = 1,2,3,4; is wrong. The size of the second dimension must be given, the initializer must be in braces, and the arrays a and b used later are never declared. Also i and j are not declared.
  4. for(i=4,I>=0;i--) is wrong. Semicolons must separate the three parts, I should be i (C is case sensitive), and starting at 4 with >=0 goes outside a 4-element dimension.
  5. for(j=0,j<4;j++); is wrong. A comma is used in place of a semicolon, and the extra semicolon after the for makes the loop body empty, so the assignment is outside the loop.
  6. return 0. 0; is wrong. It should be return 0;.
  7. The closing brace } has no matching opening brace.

Corrected program

#include <stdio.h>

int main()
{
    int a[2][2] = {1, 2, 3, 4};
    int b[2][2] = {1, 2, 3, 4};
    int m[2][2];
    int i, j;

    for (i = 1; i >= 0; i--)
        for (j = 0; j < 2; j++)
            m[i][j] = a[i][j] + b[i][j];

    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Write a program to generate the following pattern of integers.
1
121 212
1231 2 3123
12341 2 3 41234
123451 2 3 4 512345

Answer

Logic: In row ii the output is three parts joined together: the digits 11 to ii printed together, then the digits 11 to ii printed with a space after each, then the digits 11 to ii printed together again. For example, row 3 is 123 + 1 2 3 + 123 = 1231 2 3123. The first row is just 1.

#include <stdio.h>

int main()
{
    int i, j, rows = 5;

    for (i = 1; i <= rows; i++)
    {
        if (i == 1)
        {
            printf("1\n");
            continue;
        }
        for (j = 1; j <= i; j++)        /* part 1: 1..i */
            printf("%d", j);
        for (j = 1; j <= i; j++)        /* part 2: 1..i spaced */
            printf("%d ", j);
        for (j = 1; j <= i; j++)        /* part 3: 1..i */
            printf("%d", j);
        printf("\n");
    }
    return 0;
}

Output:

1
121 212
1231 2 3 123
12341 2 3 4 1234
123451 2 3 4 5 12345

The outer loop selects the row, and three inner loops print the three parts. Spacing around the middle part can be adjusted to match the required layout exactly.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Write a C program to check whether a given string is palindrome or not.

Answer

A string is a palindrome if it reads the same forwards and backwards (e.g. "madam", "level").

Logic: Find the length nn of the string. Compare str[i] with str[n-1-i] for i=0i = 0 to n/2−1n/2 - 1. If all pairs match it is a palindrome; otherwise it is not.

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

int main()
{
    char str[100];
    int i, n, flag = 1;

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

    n = strlen(str);
    for (i = 0; i < n / 2; i++)
    {
        if (str[i] != str[n - 1 - i])
        {
            flag = 0;
            break;
        }
    }

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

Example: "madam" gives a palindrome; "hello" does not, since 'h' differs from 'o'.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

What is pointer? Illustrate the use of a double pointer with suitable example.

Answer

Pointer

A pointer is a variable that stores the memory address of another variable. It is declared with *, e.g. int *p;, and p = &x; stores the address of x. The value at that address is accessed with *p (dereferencing). Pointers allow dynamic memory allocation, efficient array and string handling, call by reference and data structures such as linked lists.

Double pointer (pointer to pointer)

A double pointer stores the address of another pointer. It is declared with two stars: int **pp;. With int x; int *p = &x; int **pp = &p; we have:

  • pp holds the address of p,
  • *pp is p (the address of x),
  • **pp is the value of x.
#include <stdio.h>

int main()
{
    int x = 10;
    int *p = &x;
    int **pp = &p;

    printf("Value of x          = %d\n", x);
    printf("Value using *p      = %d\n", *p);
    printf("Value using **pp    = %d\n", **pp);

    **pp = 25;      /* changes x through the double pointer */
    printf("New value of x      = %d\n", x);
    return 0;
}

Output: 10, 10, 10, 25. Double pointers are used for dynamic 2D arrays, arrays of strings, and to modify a pointer inside a function.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Why file is used in programming? Explain different file opening modes.

Answer

Why files are used

  • Variables and arrays lose their data when the program ends (RAM is volatile); a file stores data permanently on disk.
  • Large amounts of data can be handled that do not fit in memory.
  • Data can be shared between programs and transferred between computers.
  • Input can be given from a file and output saved, avoiding re-entry of data.

File opening modes (used in FILE *fp = fopen("name", "mode");)

ModeMeaning
rOpen an existing file for reading; returns NULL if the file does not exist
wOpen for writing; creates the file, or erases the old contents if it exists
aOpen for appending; writes are added at the end; creates the file if it does not exist
r+Open an existing file for both reading and writing
w+Open for reading and writing; creates the file or erases the existing contents
a+Open for reading and appending; creates the file if needed

Adding b (e.g. rb, wb, ab) opens the file in binary mode. After use, the file should be closed with fclose(fp);.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

Write short notes on: (a) Macros (b) Null Pointers

Answer

(a) Macros

A macro is a name defined with the #define preprocessor directive that is replaced by its value or code before compilation (text substitution).

Object-like macro (symbolic constant):

#define PI 3.1416

Function-like macro (with arguments):

#define SQUARE(x) ((x)*(x))

SQUARE(5) is replaced by ((5)*(5)), giving 25. Macros make code readable and easy to change, and avoid function call overhead, so they are fast. Drawbacks: no type checking, and arguments with side effects may be evaluated more than once. Parentheses should be used around parameters. #undef removes a definition.

(b) Null Pointers

A null pointer is a pointer that does not point to any valid memory location. It is assigned the constant NULL (defined in stdio.h, stdlib.h) whose value is 0.

int *p = NULL;

Uses:

  • To initialise a pointer that has no address yet, which avoids a dangling (wild) pointer.
  • To check for failure, e.g. fopen() and malloc() return NULL on failure.
  • To mark the end of linked lists and trees.

Dereferencing a null pointer (*p) is an error and causes a run-time crash (segmentation fault), so the pointer should be checked with if (p != NULL) before use.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2077 · 5 marks

How break statement is different from continue statement? Explain with suitable example.

Answer

break and continue both alter the normal flow of a loop, but in different ways.

breakcontinue
Terminates the loop (or switch) completely and transfers control to the statement after it.Skips the rest of the current iteration and moves to the next iteration.
Can be used in loops and switch.Can be used only in loops.
Loop ends even if the condition is still true.Loop continues; the condition (or update) is evaluated again.

Example

#include <stdio.h>
int main() {
    int i;
    for (i = 1; i <= 5; i++) {
        if (i == 3)
            break;          /* loop stops when i becomes 3 */
        printf("%d ", i);
    }
    printf("\n");
    for (i = 1; i <= 5; i++) {
        if (i == 3)
            continue;       /* only i = 3 is skipped */
        printf("%d ", i);
    }
    return 0;
}

Output:

1 2
1 2 4 5

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5+5 marks

Define expression and operator, and explain operator associativity in C. Write a recursive program to find the factorial of an integer.

Answer

Expression: A combination of constants, variables, operators and function calls that evaluates to a single value, e.g. a + b * 2.

Operator: A symbol that tells the compiler to perform a specific operation on operands, e.g. +, -, *, /, %, ==, &&, =. By number of operands, operators are unary, binary or ternary (?:).

Operator associativity: When operators of the same precedence appear together in an expression, associativity decides the order of evaluation: left-to-right or right-to-left.

  • Most binary operators (+ - * / %, relational, logical) associate left to right: a - b - c is (a - b) - c.
  • Assignment operators, unary operators and the conditional operator associate right to left: a = b = 5 is a = (b = 5).

For example, in 10 / 5 * 2, / and * have equal precedence, so evaluation goes left to right: (10/5)×2=4(10/5)\times 2 = 4.

Recursive program for factorial

#include <stdio.h>

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

int main() {
    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);
    if (n < 0)
        printf("Factorial is not defined for negative numbers\n");
    else
        printf("Factorial of %d = %ld\n", n, fact(n));
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5+5 marks

Define identifier and keyword, and explain the rules for valid identifier names with an example. Write a program to convert a string to lowercase without library functions.

Answer

Identifier: The name given by the programmer to a variable, function, array, structure, etc., e.g. sum, student_age.

Keyword: A reserved word with a fixed meaning to the compiler (e.g. int, float, if, while, return). Keywords cannot be used as identifiers. C has 32 keywords in C89.

Rules for valid identifier names

  1. It may contain only letters (a-z, A-Z), digits (0-9) and the underscore _.
  2. It must begin with a letter or an underscore, not a digit.
  3. No spaces or special characters (such as @, #, -) are allowed.
  4. It cannot be a keyword.
  5. It is case sensitive: Total and total are different.

Examples: valid: marks1, _count, total_sum; invalid: 1marks, total-sum, float.

Program: convert a string to lowercase without library functions

#include <stdio.h>

int main() {
    char s[100];
    int i;
    printf("Enter a string: ");
    gets(s);                       /* or fgets(s, 100, stdin) */
    for (i = 0; s[i] != '\0'; i++) {
        if (s[i] >= 'A' && s[i] <= 'Z')
            s[i] = s[i] + 32;      /* 'a' - 'A' = 32 */
    }
    printf("Lowercase: %s\n", s);
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5+5 marks

Describe the data types available in C and their ranges. Write a program to check whether an integer is a palindrome.

Answer

Data types in C

  1. Basic (primary) types: char, int, float, double, void.
  2. Derived types: arrays, pointers, functions.
  3. User-defined types: struct, union, enum, typedef.

Typical sizes and ranges (16-bit compiler such as Turbo C; modern compilers use 32-bit int):

TypeSizeRange
char1 byte-128 to 127
unsigned char1 byte0 to 255
int2 bytes-32,768 to 32,767
unsigned int2 bytes0 to 65,535
long int4 bytes-2,147,483,648 to 2,147,483,647
float4 bytesabout 3.4×10−383.4\times10^{-38} to 3.4×10383.4\times10^{38} (6 digits precision)
double8 bytesabout 1.7×10−3081.7\times10^{-308} to 1.7×103081.7\times10^{308} (15 digits precision)
long double10 bytesabout 3.4×10−49323.4\times10^{-4932} to 1.1×1049321.1\times10^{4932}

Program: palindrome integer

#include <stdio.h>

int main() {
    int n, original, rev = 0, digit;
    printf("Enter an integer: ");
    scanf("%d", &n);
    original = n;
    while (n > 0) {
        digit = n % 10;
        rev = rev * 10 + digit;
        n /= 10;
    }
    if (rev == original)
        printf("%d is a palindrome\n", original);
    else
        printf("%d is not a palindrome\n", original);
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain how the break statement differs from the continue statement, with examples.

Answer

break terminates the nearest enclosing loop or switch immediately and passes control to the statement following it. continue skips the remaining statements of the current iteration and goes to the next iteration of the loop (in a for loop, to the update expression).

breakcontinue
Exits the loop entirely.Only skips the current iteration.
Used in loops and switch.Used only in loops.
Useful to stop early, e.g. when a value is found.Useful to ignore particular cases.

Example of break

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

Output: 1 2 3 4

Example of continue

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

Output: 1 3 5 (even numbers are skipped, the loop keeps running).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain multi-dimensional arrays. Write a program to display the sum of two m x n matrices.

Answer

Multi-dimensional arrays: 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][cols];, e.g. int a[3][4]; creates 3 rows and 4 columns (12 elements). Elements are accessed as a[i][j] and stored in row-major order. Initialisation: int a[2][3] = {{1,2,3},{4,5,6}};. Arrays with three or more dimensions, e.g. int b[2][3][4], are also allowed.

Program: sum of two m x n matrices

#include <stdio.h>

int main() {
    int a[10][10], b[10][10], sum[10][10];
    int m, n, i, j;

    printf("Enter rows and columns: ");
    scanf("%d %d", &m, &n);

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

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

    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            sum[i][j] = a[i][j] + b[i][j];

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

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write a program that creates a file "duplicate" containing an exact copy of the file "original".

Answer

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

int main() {
    FILE *fo, *fd;
    int ch;

    fo = fopen("original", "rb");
    if (fo == NULL) {
        printf("Cannot open file \"original\"\n");
        exit(1);
    }
    fd = fopen("duplicate", "wb");
    if (fd == NULL) {
        printf("Cannot create file \"duplicate\"\n");
        fclose(fo);
        exit(1);
    }

    while ((ch = fgetc(fo)) != EOF)
        fputc(ch, fd);

    fclose(fo);
    fclose(fd);
    printf("File copied successfully\n");
    return 0;
}

The program opens "original" for reading and "duplicate" for writing in binary mode (so the copy is exact), copies it one character at a time until EOF, and closes both files.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain any four input/output functions in C with suitable examples.

Answer

Input/output functions are declared in <stdio.h>.

  1. printf() - formatted output to the screen.
    int a = 10; float f = 2.5;
    printf("a = %d, f = %.1f\n", a, f);
    
  2. scanf() - formatted input from the keyboard; arguments need the address operator &.
    int age;
    scanf("%d", &age);
    
  3. getchar() / putchar() - read and write a single character.
    char c = getchar();
    putchar(c);
    
  4. gets() / puts() - read a whole line (including spaces) into a string and print a string followed by a newline.
    char name[30];
    gets(name);        /* e.g. "Ram Sharma" */
    puts(name);
    
    (fgets(name, 30, stdin) is the safer modern alternative to gets.)

Other functions include getch(), getche(), fprintf(), fscanf(), fgets(), fputs().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write a program that generates a number pattern of integers.

Answer

The following program prints a right-angled number pattern of nn rows, where row ii contains the numbers 11 to ii.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include <stdio.h>

int main() {
    int n, i, j;
    printf("Enter number of rows: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= i; j++)
            printf("%d ", j);
        printf("\n");
    }
    return 0;
}

The outer loop controls the rows and the inner loop prints the numbers in each row.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write a program to find the smallest element of an array using a pointer.

Answer

#include <stdio.h>

int main() {
    int a[100], n, i, *p, min;

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

    p = a;               /* pointer to first element */
    min = *p;
    for (i = 1; i < n; i++) {
        if (*(p + i) < min)
            min = *(p + i);
    }
    printf("Smallest element = %d\n", min);
    return 0;
}

The pointer p holds the base address of the array; *(p + i) accesses the ii-th element through pointer arithmetic, and the smallest value is tracked in min.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write a program that stores and displays student information (roll, name, address, email, phone) using a structure.

Answer

#include <stdio.h>

struct student {
    int roll;
    char name[30];
    char address[40];
    char email[40];
    char phone[15];
};

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

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

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

    printf("\nRoll\tName\tAddress\tEmail\tPhone\n");
    for (i = 0; i < n; i++)
        printf("%d\t%s\t%s\t%s\t%s\n", s[i].roll, s[i].name,
               s[i].address, s[i].email, s[i].phone);
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write short notes on: (a) escape sequences (b) null pointer

Answer

(a) Escape sequences

Escape sequences are special character combinations beginning with a backslash \ that represent non-printable or special characters inside strings and character constants. Each is treated as a single character.

SequenceMeaning
\nnew line
\thorizontal tab
\bbackspace
\rcarriage return
\aalert (beep)
\\backslash
\'single quote
\"double quote
\0null character

Example: printf("Name:\t\"Ram\"\n"); prints Name: "Ram" and moves to a new line.

(b) Null pointer

A null pointer is a pointer that does not point to any valid memory location. It is created by assigning NULL (defined in stdio.h, stdlib.h) to it: int *p = NULL;. It is used to initialise pointers that are not yet assigned, to mark the end of linked structures, and as the return value of functions such as malloc() or fopen() on failure. Dereferencing a null pointer causes a runtime error, so it should be checked first: if (p != NULL) { ... }.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 10 marks

List the advantages and disadvantages of global variable. Assume the two data files "num1.txt" and "num2.txt" containing integers. Merge these two files to the third file named "file3.txt". Here, the integers of "file3.txt" must be written in sorted order.

Answer

Global variables

Advantages:

  • Accessible from every function, so data can be shared without passing arguments or returning values.
  • Exist for the whole program run, so values persist between function calls.
  • Convenient for constants/data needed by many functions.

Disadvantages:

  • Any function can change them, so bugs are hard to trace (side effects).
  • Reduce modularity and reusability of functions.
  • Occupy memory for the entire execution.
  • Make programs harder to debug and maintain.

Program: merge num1.txt and num2.txt into sorted file3.txt

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

int main() {
    FILE *f1, *f2, *f3;
    int a[1000], n = 0, i, j, t;

    f1 = fopen("num1.txt", "r");
    f2 = fopen("num2.txt", "r");
    if (f1 == NULL || f2 == NULL) {
        printf("Cannot open input files\n");
        exit(1);
    }
    while (n < 1000 && fscanf(f1, "%d", &a[n]) == 1) n++;
    while (n < 1000 && fscanf(f2, "%d", &a[n]) == 1) n++;
    fclose(f1);
    fclose(f2);

    /* sort in ascending order (bubble sort) */
    for (i = 0; i < n - 1; i++)
        for (j = 0; j < n - i - 1; j++)
            if (a[j] > a[j + 1]) {
                t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
            }

    f3 = fopen("file3.txt", "w");
    if (f3 == NULL) {
        printf("Cannot create file3.txt\n");
        exit(1);
    }
    for (i = 0; i < n; i++)
        fprintf(f3, "%d\n", a[i]);
    fclose(f3);

    printf("Files merged into file3.txt in sorted order\n");
    return 0;
}

All integers from both files are read into one array, sorted in ascending order, and then written to file3.txt.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 4+6 marks

How nested Structure is defined and initialized? Explain with an example. Write a program, using structure, to input records of 10 students. Members include name, roll number, marks obtained in math, C program and English. Display the records of students who have passed in C Program.

Answer

Nested structure

A structure that contains another structure as a member is a nested structure. The inner structure must be defined before it is used (or defined inside the outer one). Members are accessed with repeated dot operators.

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

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

struct student s = {1, "Ram", {15, 6, 2005}};   /* initialisation */

printf("%d/%d/%d", s.dob.day, s.dob.month, s.dob.year);

Initialisation uses nested braces: inner values are enclosed in their own { }.

Program: records of 10 students, display those who passed in C Program

Assume pass mark is 40.

#include <stdio.h>

struct student {
    char name[30];
    int roll;
    float math, c, english;
};

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

    for (i = 0; i < 10; i++) {
        printf("\nStudent %d\n", i + 1);
        printf("Name: ");        scanf(" %[^\n]", s[i].name);
        printf("Roll number: "); scanf("%d", &s[i].roll);
        printf("Marks in Math, C Program, English: ");
        scanf("%f %f %f", &s[i].math, &s[i].c, &s[i].english);
    }

    printf("\nStudents who passed in C Program:\n");
    printf("Name\tRoll\tMath\tC\tEnglish\n");
    for (i = 0; i < 10; i++)
        if (s[i].c >= 40)
            printf("%s\t%d\t%.1f\t%.1f\t%.1f\n", s[i].name, s[i].roll,
                   s[i].math, s[i].c, s[i].english);
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 4+6 marks

When do we use for loop and while loop? Compare the while and do while loop with suitable example. Write a program to find average, minimum and maximum age in a class of 20 students.

Answer

for loop vs while loop

  • Use a for loop when the number of iterations is known in advance (counter-controlled), e.g. processing 20 students. Initialisation, condition and update are written together: for (i = 0; i < 20; i++).
  • Use a while loop when the number of iterations is not known and depends on a condition, e.g. reading input until the user enters 0.

while vs do-while

whiledo-while
Entry-controlled: condition tested before the body.Exit-controlled: condition tested after the body.
Body may execute zero times.Body executes at least once.
No semicolon after while(condition).Semicolon required after while(condition);.
int i = 5;
while (i < 5)   printf("while ");     /* prints nothing */
do { printf("do-while "); } while (i < 5);   /* prints once */

Program: average, minimum and maximum age of 20 students

#include <stdio.h>

int main() {
    int age[20], i, min, max, sum = 0;
    float avg;

    for (i = 0; i < 20; i++) {
        printf("Enter age of student %d: ", i + 1);
        scanf("%d", &age[i]);
    }
    min = max = age[0];
    for (i = 0; i < 20; i++) {
        sum += age[i];
        if (age[i] < min) min = age[i];
        if (age[i] > max) max = age[i];
    }
    avg = (float)sum / 20;
    printf("Average age = %.2f\nMinimum age = %d\nMaximum age = %d\n", avg, min, max);
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

What do you mean by flowchart? Draw a Flowchart to find the largest among three numbers entered by user.

Answer

Flowchart: A flowchart is a diagrammatic representation of an algorithm or program logic using standard symbols (oval for start/stop, parallelogram for input/output, rectangle for process, diamond for decision) connected by arrows showing the flow of control. It helps in planning, understanding and documenting a solution.

Flowchart to find the largest of three numbers (A, B, C)

        ( Start )
            |
      /Input A, B, C/
            |
        < A > B ? >-- No --------+
            | Yes                |
        < A > C ? >              < B > C ? >
         Yes |   | No             Yes |   | No
             |   |                    |   |
 /Print A is/  /Print C is/   /Print B is/  /Print C is/
 / largest /   / largest /    / largest /   / largest /
             \   |                /   |
              \  |               /    |
               ( Stop ) <--------+-----+

Steps:

  1. Start.
  2. Read A, B, C.
  3. If A > B: if A > C, largest = A, else largest = C.
  4. Otherwise (A <= B): if B > C, largest = B, else largest = C.
  5. Print largest.
  6. Stop.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Why array and pointer is similar? Write a program to show the similarity between an array and pointer.

Answer

Similarity between array and pointer

  • The name of an array is a constant pointer to its first element: a is equivalent to &a[0].
  • Array elements can be accessed using pointer arithmetic: a[i] is the same as *(a + i), and &a[i] is the same as a + i.
  • A pointer can be assigned the array name (p = a;) and then indexed like an array (p[i]).
  • Arrays are passed to functions as pointers (the base address).
  • Both refer to memory locations by address.

(They still differ: an array name cannot be reassigned, and sizeof gives the whole array size, while for a pointer it gives the pointer size.)

Program

#include <stdio.h>

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

    for (i = 0; i < 5; i++) {
        printf("a[%d] = %d, *(a+%d) = %d, p[%d] = %d, *(p+%d) = %d\n",
               i, a[i], i, *(a + i), i, p[i], i, *(p + i));
        printf("address a+%d = %p, p+%d = %p\n", i, (void *)(a + i), i, (void *)(p + i));
    }
    return 0;
}

Both notations give identical values and addresses for every element.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Write a program to find the sum of diagonal elements of n*n matrix.

Answer

A square matrix has a main diagonal (elements aiia_{ii}) and a secondary diagonal (elements ai,n−1−ia_{i,n-1-i}). The program below finds the sum of the main diagonal and also of the secondary diagonal.

#include <stdio.h>

int main() {
    int a[10][10], n, i, j;
    int main_sum = 0, sec_sum = 0;

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

    for (i = 0; i < n; i++) {
        main_sum += a[i][i];
        sec_sum  += a[i][n - 1 - i];
    }
    printf("Sum of main diagonal = %d\n", main_sum);
    printf("Sum of secondary diagonal = %d\n", sec_sum);
    return 0;
}

For example, for [123456789]\begin{bmatrix}1&2&3\\4&5&6\\7&8&9\end{bmatrix} the main diagonal sum is 1+5+9=151+5+9=15 and the secondary diagonal sum is 3+5+7=153+5+7=15.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

How keyword is different from Variables? Discuss Basic data types with its ranges.

Answer

Keyword vs variable

KeywordVariable
Reserved word with a predefined meaning to the compiler (int, if, while, return).Named memory location chosen by the programmer to store data.
Fixed by the language; cannot be changed or redefined.Its name is user-defined and its value can change during execution.
Cannot be used as an identifier.Must follow identifier rules and must not be a keyword.
32 keywords in C (C89).Unlimited number.

Basic data types and ranges (16-bit compiler; modern compilers use 4-byte int)

TypeSizeRange
char1 byte-128 to 127
int2 bytes-32,768 to 32,767
float4 bytesabout 3.4×10−383.4\times10^{-38} to 3.4×10383.4\times10^{38}
double8 bytesabout 1.7×10−3081.7\times10^{-308} to 1.7×103081.7\times10^{308}
void0no value

Modifiers short, long, signed and unsigned change the size/range, e.g. unsigned int is 0 to 65,535 and long int is -2,147,483,648 to 2,147,483,647.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

What is operator associativity? Explain conditional and Logical operators in brief.

Answer

Operator associativity decides the order in which operators of the same precedence are evaluated in an expression. It is either left-to-right or right-to-left. For example, a - b - c is evaluated as (a - b) - c because - associates left to right, while a = b = c is evaluated as a = (b = c) because = associates right to left. The unary operators, the conditional operator ?: and the assignment operators also associate right to left.

Conditional (ternary) operator ?:

It is the only operator in C that takes three operands.

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

If the condition is true (non-zero), expression1 is evaluated and becomes the result; otherwise expression2 is. It is a compact form of if-else.

max = (a > b) ? a : b;

Logical operators

They combine or invert conditions and give 1 (true) or 0 (false).

OperatorNameMeaning
&&Logical ANDtrue only if both operands are true
||Logical ORtrue if at least one operand is true
!Logical NOTreverses the truth value of its operand

Example: (age >= 18 && age <= 60) is true only when age lies between 18 and 60. && and || use short-circuit evaluation: in a && b, if a is false then b is not evaluated.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Write a program with a function that takes an array as an argument and returns its sum to the main function.

Answer

An array is passed to a function by giving its name (the address of its first element) together with its size. The function receives a pointer to the array, adds the elements and returns the sum to main().

#include <stdio.h>

int arraySum(int arr[], int n)
{
    int i, sum = 0;
    for (i = 0; i < n; i++)
        sum = sum + arr[i];
    return sum;
}

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

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

    total = arraySum(a, n);
    printf("Sum of array elements = %d\n", total);
    return 0;
}

For input 5 and 2 4 6 8 10, the output is Sum of array elements = 30.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

How do you include a file to another file? Illustrate with an example.

Answer

A file is included in another file with the preprocessor directive #include. Before compilation, the preprocessor replaces the directive with the entire contents of the named file.

Two forms

  • #include <filename> searches the standard system directories; used for library headers such as <stdio.h>.
  • #include "filename" searches the current directory first, then the standard directories; used for user-defined files.

Example

File myfunc.h:

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

File main.c:

#include <stdio.h>
#include "myfunc.h"

int main()
{
    printf("Square of 5 = %d\n", square(5));
    return 0;
}

When main.c is compiled, the contents of myfunc.h are copied in place of the #include "myfunc.h" line, so square() becomes available. Output: Square of 5 = 25.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Write a program to display the following pattern using the string "NEPAL".
NNN
NENENE
NEPNEPNEP
NEPANEPANEPA
NEPALNEPALNEPAL

Answer

Row ii (for i=1i = 1 to 55) consists of the first ii characters of "NEPAL" printed 33 times.

#include <stdio.h>

int main()
{
    char s[] = "NEPAL";
    int i, j, k;

    for (i = 1; i <= 5; i++)
    {
        for (k = 1; k <= 3; k++)
        {
            for (j = 0; j < i; j++)
                printf("%c", s[j]);
        }
        printf("\n");
    }
    return 0;
}

Output:

NNN
NENENE
NEPNEPNEP
NEPANEPANEPA
NEPALNEPALNEPAL

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Write short notes on: (a) Macro vs Function (b) Break vs Continue

Answer

(a) Macro vs Function

A macro is defined with #define and is expanded by the preprocessor by simple text substitution, e.g. #define SQUARE(x) ((x)*(x)). A function is compiled code that is called at run time.

MacroFunction
Expanded before compilation by text replacementCompiled and executed by a call at run time
No type checking of argumentsArguments are type checked
Faster (no call overhead) but increases code sizeSlower due to call/return overhead but code size is smaller
Side effects possible, e.g. SQUARE(i++) evaluates i++ twiceArguments are evaluated once
No return type and no recursionHas a return type and can be recursive

(b) Break vs Continue

breakcontinue
Terminates the nearest enclosing loop or switch immediatelySkips the rest of the current iteration only
Control moves to the statement after the loopControl moves to the next iteration (to the update/condition check)
Used in loops and switchUsed only in loops

Example: in for(i=1;i<=5;i++){ if(i==3) break; printf("%d ",i); } the output is 1 2; with continue instead it is 1 2 4 5.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

What is an array? How an array can be passed as function argument? Write a program to arrange an array having 10 integer numbers in ascending order using function.

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 with an index (starting from 0). Declaration: int a[10];

Passing an array to a function

The array name represents the address of the first element, so passing an array passes its address (call by reference). The function parameter is written as int arr[] or int *arr, usually with the size as another argument. Changes made inside the function affect the original array.

void sortArray(int arr[], int n);   /* prototype */
sortArray(a, 10);                   /* call: only the name is given */

Program: sort 10 integers in ascending order using a function

#include <stdio.h>

void sortArray(int arr[], int n)
{
    int i, j, temp;
    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - 1 - i; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

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

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

    sortArray(a, 10);

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

The function uses bubble sort: adjacent elements are compared and swapped if out of order, so the largest element moves to the end in each pass. Since the array is passed by address, main() sees the sorted array.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

Explain different control structures in C. Write a program in C to perform different arithmetic operations on two integers and display the result based on choice made by user using switch statement.

Answer

Control structures in C

Control structures determine the order in which statements are executed. They are of three types.

  1. Sequence: statements execute one after another in the order written (the default).

  2. Selection (decision making): one of several paths is chosen depending on a condition.

    • if, if-else, nested if-else, else-if ladder
    • switch-case
    • conditional operator ?:
    if (marks >= 40) printf("Pass"); else printf("Fail");
    
  3. Iteration (loops): a block is repeated while a condition holds.

    • while (entry controlled), do-while (exit controlled), for
    for (i = 1; i <= 5; i++) printf("%d ", i);
    

Jump statements (break, continue, goto, return) transfer control unconditionally.

Program: arithmetic operations using switch

#include <stdio.h>

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

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);
    printf("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Modulus\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    switch (choice)
    {
        case 1: printf("Sum = %d\n", a + b); break;
        case 2: printf("Difference = %d\n", a - b); break;
        case 3: printf("Product = %d\n", a * b); break;
        case 4:
            if (b != 0) printf("Quotient = %.2f\n", (float)a / b);
            else printf("Division by zero is not possible\n");
            break;
        case 5:
            if (b != 0) printf("Remainder = %d\n", a % b);
            else printf("Division by zero is not possible\n");
            break;
        default: printf("Invalid choice\n");
    }
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

Differentiate between structure and union? Write a program to read employ id, name, post and salary of employee and display detail of those employee whose post is 'clerk'.

Answer

Structure vs Union

StructureUnion
Declared with the keyword structDeclared with the keyword union
Each member gets its own separate memoryAll members share the same memory location
Size is the sum of sizes of all members (plus padding)Size is the size of the largest member
All members can be used at the same timeOnly one member holds a valid value at a time
Changing one member does not affect the othersChanging one member overwrites the others

Program

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

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

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("Enter id, name, post and salary of employee %d: ", i + 1);
        scanf("%d %s %s %f", &e[i].id, e[i].name, e[i].post, &e[i].salary);
    }

    printf("\nEmployees whose post is clerk:\n");
    printf("ID\tName\tPost\tSalary\n");
    for (i = 0; i < n; i++)
    {
        if (strcmp(e[i].post, "clerk") == 0)
        {
            printf("%d\t%s\t%s\t%.2f\n", e[i].id, e[i].name, e[i].post, e[i].salary);
            found = 1;
        }
    }
    if (!found)
        printf("No clerk found.\n");
    return 0;
}

strcmp() returns 0 when the two strings are equal, so only records with post "clerk" are displayed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

What is recursion? Write a program to find the factorial of a given integer using recursion.

Answer

Recursion is the technique in which a function calls itself, directly or indirectly, to solve a problem by reducing it to a smaller instance of the same problem. A recursive function must have a base case that stops the calls and a recursive case that moves toward the base case.

For factorial: n!=n×(n−1)!n! = n \times (n-1)! with base case 0!=1!=10! = 1! = 1.

#include <stdio.h>

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

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("Factorial of %d = %ld\n", n, factorial(n));
    return 0;
}

For n=4n = 4: 4!=4×3×2×1=244! = 4 \times 3 \times 2 \times 1 = 24, so the output is Factorial of 4 = 24.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

What are conversion specifiers? Explain the basic structure of a C program.

Answer

Conversion specifiers

Conversion (format) specifiers begin with % and tell printf() and scanf() the type of data to be printed or read.

SpecifierData type
%d / %iint
%ffloat
%lfdouble
%cchar
%sstring
%uunsigned int
%ldlong int
%xhexadecimal
%ooctal

Example: printf("%d %f %c", 5, 2.5, 'A');

Basic structure of a C program

/* 1. Documentation section */
#include <stdio.h>        /* 2. Link section */
#define PI 3.14159        /* 3. Definition section */
int total;                /* 4. Global declaration section */

int main()                /* 5. main function section */
{
    int a, b;             /* declaration part */
    a = 5; b = 10;        /* executable part */
    printf("%d\n", a + b);
    return 0;
}

int add(int x, int y)     /* 6. Subprogram (user-defined function) section */
{
    return x + y;
}
  • Documentation section: comments describing the program.
  • Link section: header files included with #include.
  • Definition section: macros and symbolic constants.
  • Global declaration section: variables and function prototypes visible to all functions.
  • main() function: execution always starts here; it has a declaration part and an executable part enclosed in braces.
  • Subprogram section: user-defined functions.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Explain nested if else ladder with suitable example.

Answer

A nested if-else (also called an if-else-if ladder) is used when a decision depends on several conditions tested in sequence. The conditions are checked from top to bottom; the statement of the first true condition is executed and the rest of the ladder is skipped. If none is true, the final else block runs.

Syntax

if (condition1)
    statement1;
else if (condition2)
    statement2;
else if (condition3)
    statement3;
else
    default_statement;

An if may also be placed inside another if or else block (nesting):

if (condition1)
{
    if (condition2)
        statement_a;
    else
        statement_b;
}
else
    statement_c;

Example: grade from marks

#include <stdio.h>

int main()
{
    int marks;
    printf("Enter marks: ");
    scanf("%d", &marks);

    if (marks >= 80)
        printf("Distinction\n");
    else if (marks >= 60)
        printf("First division\n");
    else if (marks >= 45)
        printf("Second division\n");
    else if (marks >= 40)
        printf("Third division\n");
    else
        printf("Fail\n");
    return 0;
}

For marks = 65, the first condition is false and the second is true, so "First division" is printed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Explain structure of for loop. Write a program to reverse a number entered by user.

Answer

Structure of the for loop

for (initialization; condition; update)
{
    statements;
}
  1. Initialization is executed once at the start (e.g. i = 1).
  2. Condition is tested before each iteration; if true the body executes, if false the loop ends.
  3. Update (increment/decrement) is executed after each iteration, then the condition is tested again.

Program: reverse a number

#include <stdio.h>

int main()
{
    int n, rev, digit;

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

    for (rev = 0; n != 0; n = n / 10)
    {
        digit = n % 10;
        rev = rev * 10 + digit;
    }

    printf("Reversed number = %d\n", rev);
    return 0;
}

For n=1234n = 1234: the digits 4, 3, 2, 1 are extracted in turn, so rev becomes 4, 43, 432, 4321. Output: Reversed number = 4321.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

What is DMA? Write a program to read N numbers and find largest and smallest number using DMA.

Answer

DMA (Dynamic Memory Allocation) is the allocation of memory at run time from the heap, using the functions of <stdlib.h>:

  • malloc(size) allocates a block of size bytes (uninitialized).
  • calloc(n, size) allocates n blocks of size bytes, initialized to zero.
  • realloc(ptr, newsize) changes the size of a previously allocated block.
  • free(ptr) releases the allocated memory.

It lets a program use exactly the memory needed (e.g. an array whose size N is known only at run time).

Program

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

int main()
{
    int *p, n, i, large, small;

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

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

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

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

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

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

List out different operators in C. Explain Logical and relational operator.

Answer

Operators in C

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

Relational operators

They compare two operands and give 1 (true) or 0 (false).

OperatorMeaningExample (a=5, b=3)Result
<less thana < b0
>greater thana > b1
<=less than or equala <= b0
>=greater than or equala >= b1
==equal toa == b0
!=not equal toa != b1

Logical operators

They combine relational expressions.

  • && (AND): true only if both operands are true.
  • || (OR): true if at least one operand is true.
  • ! (NOT): reverses the truth value.

Example: (a > 2 && b > 5) is 0 because b > 5 is false; (a > 2 || b > 5) is 1; !(a > b) is 0.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

What is pointer? Explain the similarity between array and pointer in brief.

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 * (dereferencing).

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

Similarity between array and pointer

  • The name of an array is a constant pointer to its first element: a is the same as &a[0].
  • Array elements can be accessed through pointer arithmetic: a[i] is equivalent to *(a + i), and &a[i] is equivalent to (a + i).
  • A pointer can be assigned the array name (int *p = a;) and then used like the array: p[i] is the same as a[i].
  • When an array is passed to a function, it is actually passed as a pointer to its first element.
  • Both refer to memory addresses; incrementing p moves to the next element of the array.

Difference in brief: an array name is a fixed address and cannot be changed (a++ is illegal), whereas a pointer variable can be reassigned (p++ is legal).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write short notes on: (a) Macro (b) Opening and closing file

Answer

(a) Macro

A macro is a name defined with the preprocessor directive #define that is replaced by its value or expression before compilation (macro expansion).

  • Object-like macro (symbolic constant): #define PI 3.14159
  • Function-like macro: #define SQUARE(x) ((x)*(x))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
printf("%d", MAX(4, 9));   /* prints 9 */

Macros make code readable and faster (no function call overhead), but they have no type checking and can cause side effects, so arguments should be parenthesized.

(b) Opening and closing a file

A file is accessed through a file pointer of type FILE *.

Opening uses fopen():

FILE *fp;
fp = fopen("data.txt", "r");
if (fp == NULL)
    printf("File cannot be opened");

Common modes: "r" read (file must exist), "w" write (creates or overwrites), "a" append, "r+", "w+", "a+" for both reading and writing. fopen() returns NULL if it fails.

Closing uses fclose(fp);. It flushes the buffered data to the disk, releases the file and the resources used. It returns 0 on success. Every opened file should be closed before the program ends.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 6+4 marks

What is loop? Differentiate between break and continue statement. Write a program to find sum of first N natural numbers.

Answer

Loop

A loop is a control structure that repeats a block of statements as long as a given condition remains true. C provides three loops: while, do-while and for. A loop avoids writing the same code repeatedly.

while (condition) { statements; }

Break vs Continue

breakcontinue
Terminates the nearest enclosing loop or switch completelySkips the remaining statements of the current iteration only
Control passes to the statement after the loopControl passes to the next iteration (condition check/update)
Can be used in loops and switchCan be used only in loops

Example: for i = 1..5 with the test if (i == 3), break prints 1 2 while continue prints 1 2 4 5.

Program: sum of first N natural numbers

#include <stdio.h>

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

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

    for (i = 1; i <= n; i++)
        sum = sum + i;

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

For N=10N = 10, the sum is 10×112=55\dfrac{10 \times 11}{2} = 55.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 4+6 marks

What is pointer? How it differs from array? Write a program to add two 2D matrices.

Answer

Pointer

A pointer is a variable that stores the address of another variable. It is declared as int *p;, assigned with p = &x;, and the value is accessed by *p.

Pointer vs Array

PointerArray
Variable that stores an addressCollection of elements of the same type in contiguous memory
Can be reassigned to point elsewhere (p++, p = &y)Name is a constant address and cannot be reassigned
sizeof(p) gives the size of the pointer itselfsizeof(a) gives the size of the whole array
Memory for the data is allocated separately (statically or dynamically)Memory for all elements is allocated when it is declared
Can point to any variable or to dynamically allocated memoryFixed size set at declaration

Program: add two 2D matrices

#include <stdio.h>

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

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

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

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

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

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

Both matrices must have the same order; each element of the result is sij=aij+bijs_{ij} = a_{ij} + b_{ij}.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 2+3+5 marks

What is string? Explain any three string function in "string.h" header file in C with example. Write a program to check whether a word is palindrome or not.

Answer

String

A string is a sequence of characters terminated by the null character '\0'. In C it is stored in a char array, e.g. char name[] = "Nepal"; (6 bytes including '\0').

Three functions of <string.h>

  1. strlen(s) returns the number of characters in s, excluding '\0'.
    strlen("Nepal");   /* 5 */
    
  2. strcpy(dest, src) copies the string src (with '\0') into dest.
    char a[20]; strcpy(a, "Kathmandu");   /* a = "Kathmandu" */
    
  3. strcmp(s1, s2) compares two strings; returns 0 if equal, a negative value if s1 < s2, a positive value if s1 > s2.
    strcmp("abc", "abc");   /* 0 */
    

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

Program: palindrome check

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

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

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

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

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

The first and last characters are compared and the indices move toward the middle; any mismatch shows the word is not a palindrome. "madam" is a palindrome; "nepal" is not.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 2+3 marks

What are conversion specifiers? Explain the compilation of C program in brief.

Answer

Conversion specifiers

Conversion (format) specifiers are character sequences beginning with % used in printf() and scanf() to specify the type of the data being printed or read, e.g. %d for int, %f for float, %c for char, %s for string, %lf for double, %ld for long int.

printf("Age = %d, Height = %f", 20, 5.6);

Compilation of a C program

A C source file (.c) goes through the following stages to become an executable:

  1. Preprocessing: the preprocessor handles directives beginning with #: it includes header files, expands macros and removes comments. Output: expanded source code.
  2. Compilation: the compiler checks syntax and translates the preprocessed code into assembly code and then into machine instructions, producing an object file (.obj / .o). Errors are reported here.
  3. Linking: the linker combines the object file with the library code (e.g. the code for printf) and other object files to produce the executable file (.exe / a.out).
  4. Loading and execution: the loader places the executable into memory and the CPU runs it.

Example with GCC: gcc prog.c -o prog compiles and links; ./prog runs it.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 1+4 marks

What is structure? Write a program to read roll, name and marks of 10 students using structure and then display all records.

Answer

A structure is a user-defined data type that groups variables of different data types under a single name. Its members are accessed with the dot operator.

#include <stdio.h>

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

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

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

    printf("\nRoll\tName\tMarks\n");
    for (i = 0; i < 10; i++)
        printf("%d\t%s\t%.2f\n", s[i].roll, s[i].name, s[i].marks);
    return 0;
}

An array of 10 structures stores the records; the first loop reads them and the second displays all of them.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 2+3 marks

Explain if else ladder with syntax and semantic. Write a program to find largest among 3 different numbers.

Answer

If-else ladder

It is used to choose one block from several alternatives. Conditions are tested from top to bottom; as soon as one is true its statement is executed and the remaining ladder is skipped. If none is true, the final else executes.

Syntax

if (condition1)
    statement1;
else if (condition2)
    statement2;
else if (condition3)
    statement3;
else
    statement_default;

Semantics: condition1 is evaluated first; if non-zero, statement1 runs and control leaves the ladder. Otherwise condition2 is evaluated, and so on. At most one statement block executes.

Program: largest of 3 different numbers

#include <stdio.h>

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

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

    if (a > b && a > c)
        printf("%d is the largest\n", a);
    else if (b > a && b > c)
        printf("%d is the largest\n", b);
    else
        printf("%d is the largest\n", c);
    return 0;
}

For 12, 45, 30: the first two tests, 12 > 45 (false) and 45 > 12 && 45 > 30 (true), select 45 as the largest.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write a program to check whether a given number is Armstrong number or not.

Answer

An Armstrong number is a number that equals the sum of its digits each raised to the power of the number of digits. For a 3-digit number: 153=13+53+33=1+125+27=153153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.

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

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

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

    for (temp = n; temp != 0; temp /= 10)
        count++;                      /* number of digits */

    for (temp = n; temp != 0; temp /= 10)
    {
        digit = temp % 10;
        sum += (int)(pow(digit, count) + 0.5);
    }

    if (sum == original)
        printf("%d is an Armstrong number\n", original);
    else
        printf("%d is not an Armstrong number\n", original);
    return 0;
}

For n=153n = 153: count = 3 and sum = 153, so it is an Armstrong number. For n=123n = 123: 1+8+27=36≠1231 + 8 + 27 = 36 \ne 123, so it is not. (The program treats 0 as having no digits and so is meant for positive integers.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 1+4 marks

What is operator precedence? Explain assignment and logical operator.

Answer

Operator precedence

Operator precedence defines the order in which different operators are evaluated in an expression: operators with higher precedence are evaluated first. For example, in 2 + 3 * 4, * has higher precedence than +, so the result is 2+12=142 + 12 = 14. Parentheses can be used to override precedence. (When operators have equal precedence, associativity decides the order.)

Approximate order from highest to lowest: (), unary (! ++ -- sizeof), * / %, + -, relational (< > <= >=), equality (== !=), &&, ||, ?:, assignment (= += ...), comma.

Assignment operators

They store the value of the right-hand expression in the variable on the left. They associate right to left.

  • Simple: = as in x = 10;
  • Compound: +=, -=, *=, /=, %=. x += 5 means x = x + 5.

Example: with x = 10, x *= 3 gives 30; a = b = 4 assigns 4 to both.

Logical operators

They combine conditions and yield 1 (true) or 0 (false).

  • && (AND): true if both operands are true.
  • || (OR): true if either operand is true.
  • ! (NOT): inverts the truth value.

Example: (x > 5 && x < 20) is true for x = 10. && and || use short-circuit evaluation: the right operand is evaluated only if needed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Explain call by reference of a function with suitable example.

Answer

Call by reference

In call by reference, the addresses of the actual arguments are passed to the function and received in pointer parameters. The function accesses the original variables through these pointers, so changes made inside the function affect the caller's variables.

#include <stdio.h>

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

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

Output:

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

Here &a and &b pass addresses; *x and *y refer to the original a and b, so the values are really swapped. Advantages: a function can modify several variables and large data (arrays, structures) is passed without copying.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 1+4 marks

What is constant? Explain basic data types in C programming along with their range.

Answer

Constant

A constant is a fixed value that does not change during program execution. Types: integer (25), real (3.14), character ('A'), string ("Nepal"). Named constants are declared with const (e.g. const float PI = 3.14;) or #define PI 3.14.

Basic data types in C (typical 32/64-bit compiler, 2-byte int in older Turbo C)

TypeSizeRange
char1 byte-128 to 127
unsigned char1 byte0 to 255
short int2 bytes-32,768 to 32,767
int4 bytes-2,147,483,648 to 2,147,483,647
unsigned int4 bytes0 to 4,294,967,295
long long8 bytesabout −9.2×1018-9.2\times10^{18} to 9.2×10189.2\times10^{18}
float4 bytesabout 3.4×10−383.4\times10^{-38} to 3.4×10383.4\times10^{38} (6 decimal digits precision)
double8 bytesabout 1.7×10−3081.7\times10^{-308} to 1.7×103081.7\times10^{308} (15 digits precision)
long double10-16 byteslarger range and precision

int holds whole numbers, char holds single characters, float and double hold real numbers, and void represents no value.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write short notes on: (a) Union (b) Switch statement

Answer

(a) Union

A union is a user-defined data type, declared with the union keyword, in which all members share the same memory location. The size of a union equals the size of its largest member, and only one member can hold a value at a time; assigning a new member overwrites the previous one.

union data {
    int i;
    float f;
    char c;
};
union data d;
d.i = 10;      /* uses the shared memory */
d.f = 2.5;     /* overwrites d.i */

Here sizeof(union data) is 4 bytes. Unions save memory when only one of several values is needed at a time. Members are accessed with the dot operator.

(b) Switch statement

switch is a multi-way selection statement that compares the value of an integer or character expression with a set of constant case labels.

switch (expression) {
    case value1: statements; break;
    case value2: statements; break;
    default:     statements;
}

The matching case executes; break exits the switch, otherwise control falls through to the following cases. default runs when no case matches. Case labels must be unique constants; floats and strings are not allowed. It is used for menu-driven programs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 10 marks

Explain goto and label. Write a C program that prints a number pattern.

Answer

goto and label

goto is an unconditional jump statement that transfers control to a labelled statement elsewhere in the same function. A label is an identifier followed by a colon.

Syntax:

goto label;
...
label: statement;

The jump may be forward or backward. Overuse makes programs hard to read (spaghetti code), so structured loops are preferred; goto is mainly useful to leave deeply nested loops or handle errors.

Example:

int i = 1;
loop:
    printf("%d ", i);
    i++;
    if (i <= 5) goto loop;

Program: number pattern

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include <stdio.h>

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

    for (i = 1; i <= n; i++) {
        for (j = 1; j <= i; j++)
            printf("%d ", j);
        printf("\n");
    }
    return 0;
}

The same pattern using goto:

#include <stdio.h>

int main() {
    int i = 1, j, n = 5;
row:
    if (i > n) goto end;
    for (j = 1; j <= i; j++)
        printf("%d ", j);
    printf("\n");
    i++;
    goto row;
end:
    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 3+7 marks

When do we need external functions? Illustrate swapping the values of two variables using (a) pass by value and (b) pass by reference.

Answer

Need for external functions

External functions are functions defined in a different source file (or library) from the one that calls them, declared with extern or a prototype/header file. They are needed when:

  • a large program is divided into several files/modules developed separately;
  • the same function must be reused by many programs (library functions such as printf, sqrt);
  • compile time and maintenance are reduced, since only the changed file is recompiled;
  • data hiding and organisation are needed in big projects.

(a) Swapping by pass by value

Copies of the arguments are passed, so the original variables are unchanged.

#include <stdio.h>

void swap(int x, int y) {
    int t = x;
    x = y;
    y = t;
    printf("Inside swap: x = %d, y = %d\n", x, y);
}

int main() {
    int a = 10, b = 20;
    swap(a, b);
    printf("In main: a = %d, b = %d\n", a, b);  /* still 10, 20 */
    return 0;
}

Output: inside swap x = 20, y = 10, but in main a = 10, b = 20. The swap is local only.

(b) Swapping by pass by reference

Addresses are passed and changed through pointers.

#include <stdio.h>

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

int main() {
    int a = 10, b = 20;
    swap(&a, &b);
    printf("a = %d, b = %d\n", a, b);   /* a = 20, b = 10 */
    return 0;
}

Because the function works on the original memory locations, the values in main() are actually exchanged.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 10 marks

Differentiate between fgets() and fgetc(). State the task of typedef. Write a program that defines a structure Book with members name, price, and author, and displays the names of books priced above 1000.

Answer

fgets() vs fgetc()

fgetc()fgets()
Reads a single character from a fileReads a string (line) from a file
int fgetc(FILE *fp)char *fgets(char *str, int n, FILE *fp)
Returns the character (or EOF)Returns the string pointer (or NULL)
Called repeatedly in a loop for textStops at newline or after n-1 characters and adds '\0'

typedef

typedef creates a new name (alias) for an existing data type, making code shorter and more readable, e.g. typedef unsigned long int ulong; or typedef struct book Book;. It does not create a new type.

Program

#include <stdio.h>

typedef struct {
    char name[50];
    float price;
    char author[50];
} Book;

int main() {
    Book b[100];
    int n, i;

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

    for (i = 0; i < n; i++) {
        printf("Enter name, price and author of book %d: ", i + 1);
        scanf("%s %f %s", b[i].name, &b[i].price, b[i].author);
    }

    printf("Books priced above 1000:\n");
    for (i = 0; i < n; i++)
        if (b[i].price > 1000)
            printf("%s\n", b[i].name);

    return 0;
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

Write an algorithm and flowchart to test whether a given integer is odd or even.

Answer

Algorithm

  1. Start
  2. Read an integer n
  3. Compute r = n mod 2
  4. If r = 0, print "Even"; otherwise print "Odd"
  5. Stop

Flowchart

        ( Start )
            |
        [ Read n ]
            |
        [ r = n mod 2 ]
            |
          < r == 0 ? >
         Yes /    \ No
   [Print "Even"]  [Print "Odd"]
            \      /
            ( Stop )

Symbols: oval for Start/Stop, parallelogram for input/output (Read, Print), rectangle for the process, diamond for the decision.

Example: n = 7 gives r = 1, so the output is Odd; n = 10 gives r = 0, so Even.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

Define token. Describe any three types of statements.

Answer

Token

A token is the smallest individual unit of a C program that has meaning to the compiler. Types of tokens: keywords, identifiers, constants, strings, operators and special symbols (punctuators).

Types of statements (any three)

  1. Expression statement - an expression ended with a semicolon, such as an assignment or function call: sum = a + b;, printf("Hi");.
  2. Selection (decision) statement - chooses between paths depending on a condition: if, if-else, else-if ladder and switch.
  3. Iteration (loop) statement - repeats a block while a condition holds: for, while, do-while.
  4. Jump statement - transfers control: break, continue, goto, return.
  5. Compound statement (block) - a group of statements enclosed in { } treated as one statement.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

List any five string manipulation functions and state their uses.

Answer

String functions are declared in <string.h>.

FunctionUse
strlen(s)returns the length of the string (without '\0')
strcpy(d, s)copies string s into d
strcat(d, s)appends string s at the end of d
strcmp(s1, s2)compares two strings; returns 0 if equal, negative if s1 < s2, positive if s1 > s2
strrev(s)reverses the string (non-standard, in Turbo C)
strupr(s) / strlwr(s)converts to upper / lower case (non-standard)
strchr(s, c)finds the first occurrence of a character
strstr(s1, s2)finds the first occurrence of substring s2 in s1

Example: strlen("Nepal") gives 5; strcmp("abc","abc") gives 0.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

State the task of the sizeof and comma operators. Discuss type conversion.

Answer

sizeof operator

sizeof is a compile-time unary operator that returns the size in bytes of a data type or variable. Example: sizeof(int) gives 4 on most systems; sizeof(arr) gives the total bytes of an array.

Comma operator

The comma operator , evaluates its operands left to right and gives the value of the right-most operand. It has the lowest precedence. Example: x = (a = 2, b = 3, a + b); gives x = 5. It is commonly used in for (i = 0, j = 10; i < j; i++, j--).

Type conversion

Type conversion is changing a value from one data type to another.

  • Implicit (automatic) conversion - the compiler converts the lower type to the higher type in mixed expressions, in the order char -> int -> long -> float -> double. Example: int a = 5; float f = a + 2.5; converts a to float.
  • Explicit conversion (type casting) - done by the programmer using (type) expression. Example: float r = (float) 7 / 2; gives 3.5, whereas 7 / 2 gives 3.

Converting a higher type to a lower one (e.g. float to int) truncates the fractional part.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

What is a union? Differentiate between a pointer and an array.

Answer

Union

A union is a user-defined data type, declared with union, whose members share the same memory location. Its size equals that of the largest member and only one member holds a valid value at a time.

union item { int i; float f; char c; };

Pointer vs array

PointerArray
A variable that stores the address of another variableA collection of elements of the same type in contiguous memory
Declared int *p;Declared int a[5];
Size is that of an address (4 or 8 bytes)Size is number of elements times element size
Can be reassigned to point elsewhere (p = &x;)Name is a constant address and cannot be reassigned
Memory can be allocated dynamically (malloc)Size fixed at compile time
sizeof(p) gives size of pointersizeof(a) gives size of whole array

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

Differentiate between a switch statement and an if-else-if ladder.

Answer

switch statementif-else-if ladder
Tests one expression against constant case valuesTests any number of different conditions
Works only with integer and character valuesWorks with int, float, relational and logical expressions
Cannot test ranges or use relational/logical operators in casesCan test ranges, e.g. marks >= 40 && marks < 60
Uses break to stop fall-through; has defaultUses else for the default case
Faster and cleaner for many fixed choices (menus)Slower when the ladder is long, since conditions are checked one by one
Case labels must be unique constantsConditions may be any expression

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

Give any two types of logical operators. What do formatted and unformatted I/O mean?

Answer

Logical operators (any two)

  • && (logical AND) - result is 1 only when both operands are true. (a > 0 && b > 0).
  • || (logical OR) - result is 1 when at least one operand is true. (a > 0 || b > 0).
  • ! (logical NOT) - reverses the truth value. !(a > 0).

Formatted and unformatted I/O

  • Formatted I/O lets the programmer control the format (type, width, precision) of data using conversion specifiers. Functions: printf(), scanf(), fprintf(), fscanf(). Example: printf("%5.2f", x);.
  • Unformatted I/O reads or writes data without any format control, as raw characters or strings. Functions: getchar(), putchar(), gets(), puts(), getch(), fgetc(), fputc().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

Define pre-processor. How do you pass a pointer as an argument?

Answer

Pre-processor

The pre-processor is a program that processes the source code before actual compilation. It handles directives that begin with #, such as #include (file inclusion), #define (macro definition), #undef, and conditional compilation (#if, #ifdef, #ifndef, #endif). Example: #define PI 3.1416.

Passing a pointer as an argument

The address of a variable is passed in the call, and the function parameter is declared as a pointer. The function accesses the original value through the dereference operator *.

#include <stdio.h>

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

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

Here &n is passed to p, and *p modifies n itself. An array name can also be passed as a pointer argument.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081.2 · 5 marks

Write a program to add two 3x3 matrices.

Answer

#include <stdio.h>

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

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

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

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

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

Corresponding elements are added: sumij=aij+bijsum_{ij} = a_{ij} + b_{ij}.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BIT 2077 First Semester Introduction to Information Technology (TU IOST semester board exam, 2077 (BS), via StudyNp), TU BIT 2078 First Semester Introduction to Information Technology (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 First Semester Introduction to Information Technology (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 First Semester Introduction to Information Technology (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 First Semester Introduction to Information Technology (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081.2 First Semester Introduction to Information Technology (TU IOST semester board exam, 2081.2 (BS), via StudyNp), TU BIT 2077 First Semester C Programming (TU IOST semester board exam, 2077 (BS), via StudyNp), TU BIT 2078 First Semester C Programming (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 First Semester C Programming (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 First Semester C Programming (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 First Semester C Programming (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081.2 First Semester C Programming (TU IOST semester board exam, 2081.2 (BS), via StudyNp), TU BIT 2077 First Semester Digital Logic (TU IOST semester board exam, 2077 (BS), via StudyNp), TU BIT 2078 First Semester Digital Logic (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 First Semester Digital Logic (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 First Semester Digital Logic (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 First Semester Digital Logic (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081.2 First Semester Digital Logic (TU IOST semester board exam, 2081.2 (BS), via StudyNp), TU BIT 2077 First Semester Basic Mathematics (TU IOST semester board exam, 2077 (BS), via StudyNp), TU BIT 2078 First Semester Basic Mathematics (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 First Semester Basic Mathematics (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 First Semester Basic Mathematics (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 First Semester Basic Mathematics (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081.2 First Semester Basic Mathematics (TU IOST semester board exam, 2081.2 (BS), via StudyNp), TU BIT 2077 First Semester Sociology (TU IOST semester board exam, 2077 (BS), via StudyNp), TU BIT 2078 First Semester Sociology (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 First Semester Sociology (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 First Semester Sociology (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 First Semester Sociology (TU IOST semester board exam, 2081 (BS), via StudyNp) and TU BIT 2081.2 First Semester Sociology (TU IOST semester board exam, 2081.2 (BS), via StudyNp). Answers are written for this site; check them against your class notes.