Important Questions

BIT102 · Exam intelligence

C Programming important questions

From 7 past TU papers: which questions keep coming back, how much they carry, and what is most likely to show up next. Every question links to a model answer.

Most likely in the next examStatistical

Ranked by how often a topic is asked, its marks weight, and whether it is due after skipping the 2081.2 paper. No guarantees; study the whole syllabus.

1asked 3xavg 7 marks · due (skipped 2081.2) · Loop control statements
Answer

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

Loop, Break vs Continue, and Sum of N Natural Numbers


What is a Loop?

A loop is a control structure that allows repeated execution of a block of statements as long as a given condition remains true. Loops are used to avoid writing the same code multiple times.

Types of Loops in C:

Loop TypeDescription
for loopUsed when the number of iterations is known
while loopEntry-controlled; checks condition before executing
do-while loopExit-controlled; executes at least once

Difference Between break and continue Statement

Featurebreakcontinue
FunctionTerminates the entire loop immediatelySkips the current iteration only
Control TransferTransfers control outside the loopTransfers control to the loop's condition check
Effect on LoopLoop stops completelyLoop continues with next iteration
Use CaseExit loop when a condition is metSkip specific values during iteration

Example of break:

for(int i = 1; i <= 10; i++) {
    if(i == 5)
        break;       // loop ends when i reaches 5
    printf("%d ", i);
}
// Output: 1 2 3 4

Example of continue:

for(int i = 1; i <= 10; i++) {
    if(i == 5)
        continue;    // skips i=5, loop keeps running
    printf("%d ", i);
}
// Output: 1 2 3 4 6 7 8 9 10

Conclusion: break exits the loop entirely, while continue only skips the current iteration and the loop keeps running.


Program to Find Sum of First N Natural Numbers

The sum of first N natural numbers means adding all integers from 1 to N.

#include <stdio.h>

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

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

    for(i = 1; i <= n; i++) {
        sum = sum + i;   // accumulate sum
    }

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

    return 0;
}

Sample Output:

Enter the value of N: 5
Sum of first 5 natural numbers = 15

Explanation (Dry Run for N = 5):

Iterationisum = sum + i
110 + 1 = 1
221 + 2 = 3
333 + 3 = 6
446 + 4 = 10
5510 + 5 = 15

The for loop runs from i = 1 to i = N, adding each value of i to the variable sum. After the loop ends, the final sum is displayed.

2asked 3xavg 7 marks · due (skipped 2081.2) · Similarity between arrays and pointers
Answer

What is pointer? How it differs from array?Write a program to add two 2D matrices.[4+6]

Pointer vs Array and 2D Matrix Addition


What is a Pointer? (4 marks)

A pointer is a variable that stores the memory address of another variable rather than storing a data value directly.

Declaration syntax:

data_type *pointer_name;

Example:

int x = 10;
int *ptr;
ptr = &x;   // ptr holds the address of x
printf("%d", *ptr);  // prints 10 (dereferencing)
  • & operator gives the address of a variable
  • * operator dereferences a pointer (accesses value at that address)

How Pointer Differs from Array

FeaturePointerArray
DefinitionVariable that stores address of another variableCollection of elements of same data type stored in contiguous memory
MemoryStores only an address (typically 4 or 8 bytes)Allocates memory for all elements at once
AssignmentCan be reassigned to point to different variablesArray name is a constant pointer; cannot be reassigned
InitializationMust be explicitly assigned an address before useMemory is allocated at declaration
ArithmeticPointer arithmetic moves to next memory locationArray index directly accesses elements
sizeofReturns size of pointer variable itselfReturns total size of all elements
Dynamic memoryCan use malloc()/calloc() for dynamic allocationSize is fixed at compile time (static)

Example showing difference:

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;

// arr = ptr;  // ERROR: array name is constant
ptr = ptr + 1;  // VALID: pointer can be moved

Program to Add Two 2D Matrices (6 marks)

#include <stdio.h>

int main() {
    int r, c, i, j;

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

    int A[r][c], B[r][c], C[r][c];

    // Input matrix A
    printf("\nEnter elements of Matrix A (%dx%d):\n", r, c);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("A[%d][%d]: ", i, j);
            scanf("%d", &A[i][j]);
        }
    }

    // Input matrix B
    printf("\nEnter elements of Matrix B (%dx%d):\n", r, c);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("B[%d][%d]: ", i, j);
            scanf("%d", &B[i][j]);
        }
    }

    // Add matrices A and B, store result in C
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    // Display result matrix C
    printf("\nResultant Matrix C = A + B:\n");
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Sample Output

Enter number of rows: 2
Enter number of columns: 2

Enter elements of Matrix A (2x2):
A[0][0]: 1
A[0][1]: 2
A[1][0]: 3
A[1][1]: 4

Enter elements of Matrix B (2x2):
B[0][0]: 5
B[0][1]: 6
B[1][0]: 7
B[1][1]: 8

Resultant Matrix C = A + B:
6    8
10   12

Logic Explanation

For two matrices A and B of same dimension (r x c):

$$C[i][j] = A[i][j] + B[i][j]$$

where i ranges from 0 to r-1 and j ranges from 0 to c-1.

Note: Matrix addition is only possible when both matrices have the same number of rows and columns.

3asked 3xavg 7 marks · due (skipped 2081.2) · Operator precedence and associativity
Answer

What is operator precedence? Explain assignment and logical operator. [1+4]

Operator Precedence, Assignment and Logical Operators


Operator Precedence [1 mark]

Operator precedence defines the order (priority) in which operators are evaluated in an expression when multiple operators appear together. An operator with higher precedence is evaluated before an operator with lower precedence.

Example:

2 + 3 * 4  =  2 + 12  =  14

Here, * has higher precedence than +, so multiplication is performed first.


Assignment Operator [2 marks]

The assignment operator is used to assign a value to a variable. The basic assignment operator is =.

Syntax:

variable = expression;

Simple Assignment

OperatorExampleMeaning
=a = 5Assigns 5 to a

Compound Assignment Operators

These combine an arithmetic operation with assignment:

OperatorExampleEquivalent To
+=a += 5a = a + 5
-=a -= 5a = a - 5
*=a *= 5a = a * 5
/=a /= 5a = a / 5
%=a %= 5a = a % 5

Key Points:

  • Assignment is right-to-left associative
  • Multiple assignments are possible: a = b = c = 10; (assigns 10 to all)
  • The right-hand side is evaluated first, then assigned to the left-hand side variable

Logical Operators [2 marks]

Logical operators are used to combine or negate boolean/conditional expressions. They return either true (1) or false (0).

Types of Logical Operators

OperatorNameExampleResult
&&Logical ANDa && bTrue only if both a and b are true
||Logical ORa || bTrue if at least one of a or b is true
!Logical NOT!aTrue if a is false, and vice versa

Truth Tables

AND (&&)

ABA && B
000
010
100
111

OR (||)

ABA || B
000
011
101
111

NOT (!)

A!A
01
10

Example in C:

int a = 5, b = 10, c = 0;

if (a > 0 && b > 0)       // true && true = true
    printf("Both positive");

if (a > 0 || c > 0)       // true || false = true
    printf("At least one positive");

if (!c)                    // !0 = true
    printf("c is zero");

Key Points:

  • && and || use short-circuit evaluation: if the result is determined from the first operand, the second is not evaluated
  • ! is a unary operator (operates on one operand)
  • Logical operators are commonly used in if, while, and for conditions
4asked 3xavg 7 marks · due (skipped 2081.2) · Basic data types and their ranges
Answer

What is constant? Explain basic data types in C programming along with their range. [1+4]

Constants and Basic Data Types in C Programming


What is a Constant? [1 Mark]

A constant is a fixed value that does not change during the execution of a program. Once defined, its value remains the same throughout the program.

Example:

const int x = 10;   // x is always 10
#define PI 3.14159  // PI is always 3.14159

Basic Data Types in C Programming [4 Marks]

C provides several fundamental (basic) data types to store different kinds of data. These are:


1. int (Integer Type)

  • Used to store whole numbers (positive, negative, or zero).
  • No decimal point.
TypeSizeRange
int2 or 4 bytes-32,768 to 32,767 (2 bytes) / -2,147,483,648 to 2,147,483,647 (4 bytes)
short int2 bytes-32,768 to 32,767
long int4 bytes-2,147,483,648 to 2,147,483,647
unsigned int2 or 4 bytes0 to 65,535 (2 bytes) / 0 to 4,294,967,295 (4 bytes)
int age = 20;

2. float (Floating Point Type)

  • Used to store real numbers (numbers with decimal points).
  • Single precision.
TypeSizeRange
float4 bytes3.4 x 10^-38 to 3.4 x 10^+38 (6 decimal digits precision)
float price = 99.99;

3. double (Double Precision Float)

  • Used to store large real numbers with more precision than float.
TypeSizeRange
double8 bytes1.7 x 10^-308 to 1.7 x 10^+308 (15 decimal digits precision)
long double10 bytes3.4 x 10^-4932 to 1.1 x 10^+4932
double pi = 3.14159265358979;

4. char (Character Type)

  • Used to store a single character (letter, digit, or symbol).
  • Stored as its ASCII value internally.
TypeSizeRange
char1 byte-128 to 127 (signed)
unsigned char1 byte0 to 255
char grade = 'A';

Summary Table

Data TypeSizeRange
int2/4 bytes-32,768 to 32,767 / -2,147,483,648 to 2,147,483,647
float4 bytes3.4e-38 to 3.4e+38
double8 bytes1.7e-308 to 1.7e+308
char1 byte-128 to 127

Note: The exact size may vary depending on the compiler and system architecture (32-bit or 64-bit).

5asked 3xavg 5 marks · due (skipped 2081.2) · Pattern generation using arrays
Answer

Write a program to display the following pattern using the string "NEPAL". NNNNENENENEPNEPNEPNEPANEPANEPANEPALNEPALNEPAL_[5]_

The pattern reaches us as the run-on string NNNNENENENEPNEPNEPNEPANEPANEPANEPALNEPALNEPAL, so the first job is to break it back into rows. Splitting it into consecutive prefixes of "NEPAL" gives and joining these five rows back together ...

Most repeated questions

Topics asked at least twice, most-asked first.

asked 3xavg 7 marks · 2081, 0
Answer

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

Loop, Break vs Continue, and Sum of N Natural Numbers


What is a Loop?

A loop is a control structure that allows repeated execution of a block of statements as long as a given condition remains true. Loops are used to avoid writing the same code multiple times.

Types of Loops in C:

Loop TypeDescription
for loopUsed when the number of iterations is known
while loopEntry-controlled; checks condition before executing
do-while loopExit-controlled; executes at least once

Difference Between break and continue Statement

Featurebreakcontinue
FunctionTerminates the entire loop immediatelySkips the current iteration only
Control TransferTransfers control outside the loopTransfers control to the loop's condition check
Effect on LoopLoop stops completelyLoop continues with next iteration
Use CaseExit loop when a condition is metSkip specific values during iteration

Example of break:

for(int i = 1; i <= 10; i++) {
    if(i == 5)
        break;       // loop ends when i reaches 5
    printf("%d ", i);
}
// Output: 1 2 3 4

Example of continue:

for(int i = 1; i <= 10; i++) {
    if(i == 5)
        continue;    // skips i=5, loop keeps running
    printf("%d ", i);
}
// Output: 1 2 3 4 6 7 8 9 10

Conclusion: break exits the loop entirely, while continue only skips the current iteration and the loop keeps running.


Program to Find Sum of First N Natural Numbers

The sum of first N natural numbers means adding all integers from 1 to N.

#include <stdio.h>

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

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

    for(i = 1; i <= n; i++) {
        sum = sum + i;   // accumulate sum
    }

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

    return 0;
}

Sample Output:

Enter the value of N: 5
Sum of first 5 natural numbers = 15

Explanation (Dry Run for N = 5):

Iterationisum = sum + i
110 + 1 = 1
221 + 2 = 3
333 + 3 = 6
446 + 4 = 10
5510 + 5 = 15

The for loop runs from i = 1 to i = N, adding each value of i to the variable sum. After the loop ends, the final sum is displayed.

asked 3xavg 7 marks · 2081, 2080, 2079
Answer

What is pointer? How it differs from array?Write a program to add two 2D matrices.[4+6]

Pointer vs Array and 2D Matrix Addition


What is a Pointer? (4 marks)

A pointer is a variable that stores the memory address of another variable rather than storing a data value directly.

Declaration syntax:

data_type *pointer_name;

Example:

int x = 10;
int *ptr;
ptr = &x;   // ptr holds the address of x
printf("%d", *ptr);  // prints 10 (dereferencing)
  • & operator gives the address of a variable
  • * operator dereferences a pointer (accesses value at that address)

How Pointer Differs from Array

FeaturePointerArray
DefinitionVariable that stores address of another variableCollection of elements of same data type stored in contiguous memory
MemoryStores only an address (typically 4 or 8 bytes)Allocates memory for all elements at once
AssignmentCan be reassigned to point to different variablesArray name is a constant pointer; cannot be reassigned
InitializationMust be explicitly assigned an address before useMemory is allocated at declaration
ArithmeticPointer arithmetic moves to next memory locationArray index directly accesses elements
sizeofReturns size of pointer variable itselfReturns total size of all elements
Dynamic memoryCan use malloc()/calloc() for dynamic allocationSize is fixed at compile time (static)

Example showing difference:

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;

// arr = ptr;  // ERROR: array name is constant
ptr = ptr + 1;  // VALID: pointer can be moved

Program to Add Two 2D Matrices (6 marks)

#include <stdio.h>

int main() {
    int r, c, i, j;

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

    int A[r][c], B[r][c], C[r][c];

    // Input matrix A
    printf("\nEnter elements of Matrix A (%dx%d):\n", r, c);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("A[%d][%d]: ", i, j);
            scanf("%d", &A[i][j]);
        }
    }

    // Input matrix B
    printf("\nEnter elements of Matrix B (%dx%d):\n", r, c);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("B[%d][%d]: ", i, j);
            scanf("%d", &B[i][j]);
        }
    }

    // Add matrices A and B, store result in C
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    // Display result matrix C
    printf("\nResultant Matrix C = A + B:\n");
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Sample Output

Enter number of rows: 2
Enter number of columns: 2

Enter elements of Matrix A (2x2):
A[0][0]: 1
A[0][1]: 2
A[1][0]: 3
A[1][1]: 4

Enter elements of Matrix B (2x2):
B[0][0]: 5
B[0][1]: 6
B[1][0]: 7
B[1][1]: 8

Resultant Matrix C = A + B:
6    8
10   12

Logic Explanation

For two matrices A and B of same dimension (r x c):

$$C[i][j] = A[i][j] + B[i][j]$$

where i ranges from 0 to r-1 and j ranges from 0 to c-1.

Note: Matrix addition is only possible when both matrices have the same number of rows and columns.

asked 3xavg 7 marks · 2081, 2079, 2078
Answer

What is operator precedence? Explain assignment and logical operator. [1+4]

Operator Precedence, Assignment and Logical Operators


Operator Precedence [1 mark]

Operator precedence defines the order (priority) in which operators are evaluated in an expression when multiple operators appear together. An operator with higher precedence is evaluated before an operator with lower precedence.

Example:

2 + 3 * 4  =  2 + 12  =  14

Here, * has higher precedence than +, so multiplication is performed first.


Assignment Operator [2 marks]

The assignment operator is used to assign a value to a variable. The basic assignment operator is =.

Syntax:

variable = expression;

Simple Assignment

OperatorExampleMeaning
=a = 5Assigns 5 to a

Compound Assignment Operators

These combine an arithmetic operation with assignment:

OperatorExampleEquivalent To
+=a += 5a = a + 5
-=a -= 5a = a - 5
*=a *= 5a = a * 5
/=a /= 5a = a / 5
%=a %= 5a = a % 5

Key Points:

  • Assignment is right-to-left associative
  • Multiple assignments are possible: a = b = c = 10; (assigns 10 to all)
  • The right-hand side is evaluated first, then assigned to the left-hand side variable

Logical Operators [2 marks]

Logical operators are used to combine or negate boolean/conditional expressions. They return either true (1) or false (0).

Types of Logical Operators

OperatorNameExampleResult
&&Logical ANDa && bTrue only if both a and b are true
||Logical ORa || bTrue if at least one of a or b is true
!Logical NOT!aTrue if a is false, and vice versa

Truth Tables

AND (&&)

ABA && B
000
010
100
111

OR (||)

ABA || B
000
011
101
111

NOT (!)

A!A
01
10

Example in C:

int a = 5, b = 10, c = 0;

if (a > 0 && b > 0)       // true && true = true
    printf("Both positive");

if (a > 0 || c > 0)       // true || false = true
    printf("At least one positive");

if (!c)                    // !0 = true
    printf("c is zero");

Key Points:

  • && and || use short-circuit evaluation: if the result is determined from the first operand, the second is not evaluated
  • ! is a unary operator (operates on one operand)
  • Logical operators are commonly used in if, while, and for conditions
asked 3xavg 7 marks · 2081, 2079, 2078
Answer

What is constant? Explain basic data types in C programming along with their range. [1+4]

Constants and Basic Data Types in C Programming


What is a Constant? [1 Mark]

A constant is a fixed value that does not change during the execution of a program. Once defined, its value remains the same throughout the program.

Example:

const int x = 10;   // x is always 10
#define PI 3.14159  // PI is always 3.14159

Basic Data Types in C Programming [4 Marks]

C provides several fundamental (basic) data types to store different kinds of data. These are:


1. int (Integer Type)

  • Used to store whole numbers (positive, negative, or zero).
  • No decimal point.
TypeSizeRange
int2 or 4 bytes-32,768 to 32,767 (2 bytes) / -2,147,483,648 to 2,147,483,647 (4 bytes)
short int2 bytes-32,768 to 32,767
long int4 bytes-2,147,483,648 to 2,147,483,647
unsigned int2 or 4 bytes0 to 65,535 (2 bytes) / 0 to 4,294,967,295 (4 bytes)
int age = 20;

2. float (Floating Point Type)

  • Used to store real numbers (numbers with decimal points).
  • Single precision.
TypeSizeRange
float4 bytes3.4 x 10^-38 to 3.4 x 10^+38 (6 decimal digits precision)
float price = 99.99;

3. double (Double Precision Float)

  • Used to store large real numbers with more precision than float.
TypeSizeRange
double8 bytes1.7 x 10^-308 to 1.7 x 10^+308 (15 decimal digits precision)
long double10 bytes3.4 x 10^-4932 to 1.1 x 10^+4932
double pi = 3.14159265358979;

4. char (Character Type)

  • Used to store a single character (letter, digit, or symbol).
  • Stored as its ASCII value internally.
TypeSizeRange
char1 byte-128 to 127 (signed)
unsigned char1 byte0 to 255
char grade = 'A';

Summary Table

Data TypeSizeRange
int2/4 bytes-32,768 to 32,767 / -2,147,483,648 to 2,147,483,647
float4 bytes3.4e-38 to 3.4e+38
double8 bytes1.7e-308 to 1.7e+308
char1 byte-128 to 127

Note: The exact size may vary depending on the compiler and system architecture (32-bit or 64-bit).

asked 3xavg 5 marks · 2079, 2078, 2077
Answer

Write a program to display the following pattern using the string "NEPAL". NNNNENENENEPNEPNEPNEPANEPANEPANEPALNEPALNEPAL_[5]_

The pattern reaches us as the run-on string NNNNENENENEPNEPNEPNEPANEPANEPANEPALNEPALNEPAL, so the first job is to break it back into rows. Splitting it into consecutive prefixes of "NEPAL" gives and joining these five rows back together ...

asked 3xavg 5 marks · 2078, 2077, 0
Answer

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

Basic Structure of a C Program


Basic Structure of a C Program

A C program is organized into several distinct sections. Below is the general template:

/* Documentation Section */
// Program description, author, date

/* Link Section (Header Files) */
#include <stdio.h>
#include <conio.h>

/* Definition Section (Macros/Constants) */
#define PI 3.14159

/* Global Declaration Section */
int globalVar;

/* Main Function */
int main()
{
    /* Local Declaration */
    int a, b;

    /* Executable Statements */
    printf("Hello, World!\n");

    return 0;
}

/* User-Defined Functions */
void myFunction()
{
    // function body
}

Explanation of Each Part

1. Documentation Section

  • Contains comments about the program such as program name, author, date, and purpose.
  • Written using /* ... */ (multi-line) or // (single-line).
  • Ignored by the compiler; meant for human readability.
  • Contains preprocessor directives that include standard library header files.
  • Syntax: #include <filename.h>
  • Example: #include <stdio.h> includes standard input/output functions like printf() and scanf().
  • These are processed before compilation.

3. Definition Section

  • Used to define symbolic constants or macros using #define.
  • Example: #define PI 3.14159
  • The preprocessor replaces every occurrence of PI with 3.14159 before compilation.

4. Global Declaration Section

  • Variables declared here are global variables, accessible throughout the entire program.
  • Declared outside all functions.
  • They retain their value for the entire lifetime of the program.

5. Main Function main()

  • Every C program must have exactly one main() function -- it is the entry point of execution.
  • Contains two parts:
    • Local Declaration: Variables declared inside main(), accessible only within it.
    • Executable Statements: The actual logic -- assignments, function calls, loops, etc.
  • Returns an integer value to the operating system (return 0 indicates successful execution).

6. User-Defined Functions

  • Functions written by the programmer to perform specific tasks.
  • Defined after (or before) main().
  • Promotes modularity and code reusability.

Summary Table

SectionPurpose
DocumentationComments and program description
Link SectionIncludes header/library files
Definition SectionDefines constants and macros
Global DeclarationDeclares global variables
main() FunctionEntry point; contains program logic
User-Defined FunctionsCustom functions for specific tasks
asked 3xavg 8 marks · 2081.2, 2080, 2077
Answer

What is union? Differentiate between pointer and array. [5]

--- A union is a user-defined data type in C that allows storing different data types in the same memory location. All members of a union share the same memory space, and the size of the union is equal to the size of its largest member. ...

asked 2xavg 8 marks · 2081, 0
Answer

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.[2+3+5]

String, String Functions, and Palindrome Check


1. What is String? [2 marks]

A string in C is a sequence of characters stored in a character array and terminated by a null character (\0). C does not have a built-in string data type; instead, strings are represented as arrays of type char.

Declaration:

char name[] = "Hello";
// Stored as: H e l l o \0

The null character \0 marks the end of the string and is automatically added when a string literal is used.


2. Three String Functions in string.h [3 marks]

i) strlen() - String Length

Returns the number of characters in a string, excluding the null character.

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "Hello";
    printf("Length = %d", strlen(str));  // Output: 5
    return 0;
}

ii) strcpy() - String Copy

Copies the content of one string (source) into another string (destination).

#include <stdio.h>
#include <string.h>
int main() {
    char src[] = "Nepal";
    char dest[20];
    strcpy(dest, src);
    printf("Copied string: %s", dest);  // Output: Nepal
    return 0;
}

iii) strcmp() - String Compare

Compares two strings lexicographically.

  • Returns 0 if both strings are equal
  • Returns a negative value if first string is less than second
  • Returns a positive value if first string is greater than second
#include <stdio.h>
#include <string.h>
int main() {
    char s1[] = "apple";
    char s2[] = "apple";
    if (strcmp(s1, s2) == 0)
        printf("Strings are equal");   // Output: Strings are equal
    else
        printf("Strings are not equal");
    return 0;
}

3. Program to Check Whether a Word is Palindrome or Not [5 marks]

Logic: A word is a palindrome if it reads the same forwards and backwards. Example: "madam", "level", "racecar"

We compare the string with its reverse. If they are equal, it is a palindrome.

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

int main() {
    char word[100], rev[100];
    int len, i, j;
    int isPalindrome = 1;  // Assume true initially

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

    len = strlen(word);

    // Reverse the word manually
    for (i = 0, j = len - 1; i < len; i++, j--) {
        rev[i] = word[j];
    }
    rev[len] = '\0';  // Add null terminator

    // Compare original and reversed word
    if (strcmp(word, rev) == 0) {
        printf("\"%s\" is a Palindrome.\n", word);
    } else {
        printf("\"%s\" is NOT a Palindrome.\n", word);
    }

    return 0;
}

Sample Output:

Case 1:

Enter a word: madam
"madam" is a Palindrome.

Case 2:

Enter a word: hello
"hello" is NOT a Palindrome.

Explanation of Key Steps:

StepDescription
strlen(word)Finds the length of the entered word
Reverse loopCopies characters from end to start into rev[]
rev[len] = '\0'Properly terminates the reversed string
strcmp(word, rev)Compares original and reversed; returns 0 if equal
asked 2xavg 5 marks · 2081, 2080
Answer

What are conversion specifiers? Explain the compilation of C program in brief. [2+3]

--- Conversion specifiers are special format codes used inside printf() and scanf() functions to specify the type and format of data to be printed or read. They always begin with a percent sign (%). Specifier Data Type Example ----------...

asked 2xavg 5 marks · 2081, 2078
Answer

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

Structure in C

What is Structure?

A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable inside a structure is called a member or field.

Syntax:

struct structure_name {
    data_type member1;
    data_type member2;
    ...
};

Program: Read and Display Records of 10 Students

#include <stdio.h>

// Define the structure
struct Student {
    int roll;
    char name[50];
    float marks;
};

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

    // Read records of 10 students
    printf("Enter details of 10 students:\n");
    for (i = 0; i < 10; i++) {
        printf("\nStudent %d:\n", i + 1);
        printf("Enter Roll No : ");
        scanf("%d", &s[i].roll);
        printf("Enter Name    : ");
        scanf(" %s", s[i].name);
        printf("Enter Marks   : ");
        scanf("%f", &s[i].marks);
    }

    // Display all records
    printf("\n\n--- Student Records ---\n");
    printf("%-10s %-20s %-10s\n", "Roll No", "Name", "Marks");
    printf("----------------------------------------\n");
    for (i = 0; i < 10; i++) {
        printf("%-10d %-20s %-10.2f\n", s[i].roll, s[i].name, s[i].marks);
    }

    return 0;
}

Sample Output

Enter details of 10 students:

Student 1:
Enter Roll No : 1
Enter Name    : Ram
Enter Marks   : 85.5
...

--- Student Records ---
Roll No    Name                 Marks
----------------------------------------
1          Ram                  85.50
2          Sita                 90.00
...

Key Points

FeatureDescription
Keywordstruct
MembersCan be of different data types
Array of structuresstruct Student s[10] stores 10 students
Member accessUsing dot operator (.)
asked 2xavg 5 marks · 2081, 2080
Answer

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

Program: Write N Numbers to File and Display Even Numbers

C Program

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

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

    // Step 1: Get N from user
    printf("Enter how many numbers to write: ");
    scanf("%d", &n);

    // Step 2: Open file for writing
    fp = fopen("number.txt", "w");
    if (fp == NULL) {
        printf("Error opening file for writing!\n");
        exit(1);
    }

    // Step 3: Write N numbers to file
    printf("Enter %d numbers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &num);
        fprintf(fp, "%d\n", num);
    }

    fclose(fp);
    printf("Numbers written to file successfully.\n");

    // Step 4: Open file for reading
    fp = fopen("number.txt", "r");
    if (fp == NULL) {
        printf("Error opening file for reading!\n");
        exit(1);
    }

    // Step 5: Read and display only even numbers
    printf("\nEven numbers from file:\n");
    while (fscanf(fp, "%d", &num) != EOF) {
        if (num % 2 == 0) {
            printf("%d\n", num);
        }
    }

    fclose(fp);
    return 0;
}

Sample Output

Enter how many numbers to write: 6
Enter 6 numbers:
3 8 15 22 7 10

Numbers written to file successfully.

Even numbers from file:
8
22
10

Key Points

StepOperationFunction Used
1Open file for writingfopen("number.txt", "w")
2Write numbers to filefprintf(fp, "%d\n", num)
3Close file after writingfclose(fp)
4Open file for readingfopen("number.txt", "r")
5Read numbers from filefscanf(fp, "%d", &num)
6Check even conditionnum % 2 == 0

Note: Always check if fopen() returns NULL to handle file errors, and always call fclose() after file operations to release resources.

asked 2xavg 5 marks · 2080, 0
Answer

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.[10]

--- An array is a collection of elements of the same data type stored in contiguous (adjacent) memory locations, all sharing a common name and accessed individually using an index (subscript). Declaration Syntax: Example: Key Properties:...

asked 2xavg 8 marks · 2079, 2078
Answer

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

Global Variables & File Merging Program

Part A: Advantages and Disadvantages of Global Variables

A global variable is a variable declared outside all functions, making it accessible to every function in the program.


Advantages

#AdvantageExplanation
1Universal AccessibilityAny function can read or modify the variable without receiving it as a parameter
2Reduced Parameter PassingFunction signatures stay simple; no need to pass shared data repeatedly
3Easy Data SharingMultiple functions can communicate through a common variable
4PersistenceThe variable retains its value for the entire lifetime of the program
5Convenient for ConstantsUseful for program-wide constants or configuration values

Disadvantages

#DisadvantageExplanation
1Uncontrolled AccessAny function can accidentally overwrite the value, causing hard-to-find bugs
2Namespace PollutionLarge programs with many globals risk naming conflicts
3Reduced ModularityFunctions depend on external state, making them difficult to reuse
4Violates Data HidingAll data is exposed, breaking the principle of encapsulation
5Difficult DebuggingTracking which function changed the value requires checking the entire program

Part B: Merge Two Files into a Third File in Sorted Order

Logic / Algorithm

1. Open num1.txt and read all integers into array a[]
2. Open num2.txt and read all integers into array b[]
3. Copy both arrays into a combined array c[]
4. Sort c[] using Bubble Sort (ascending order)
5. Open file3.txt for writing
6. Write every element of sorted c[] into file3.txt
7. Close all files

Complete C Program

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

int main()
{
    FILE *f1, *f2, *f3;
    int a[100], b[100], c[200];
    int n1 = 0, n2 = 0;
    int i, j, k = 0, temp;

    /* ---- Step 1: Read integers from num1.txt ---- */
    f1 = fopen("num1.txt", "r");
    if (f1 == NULL)
    {
        printf("Error: Cannot open num1.txt\n");
        exit(1);
    }
    while (fscanf(f1, "%d", &a[n1]) != EOF)
    {
        n1++;
    }
    fclose(f1);

    /* ---- Step 2: Read integers from num2.txt ---- */
    f2 = fopen("num2.txt", "r");
    if (f2 == NULL)
    {
        printf("Error: Cannot open num2.txt\n");
        exit(1);
    }
    while (fscanf(f2, "%d", &b[n2]) != EOF)
    {
        n2++;
    }
    fclose(f2);

    /* ---- Step 3: Combine both arrays into c[] ---- */
    for (i = 0; i < n1; i++)
        c[k++] = a[i];

    for (i = 0; i < n2; i++)
        c[k++] = b[i];

    /* ---- Step 4: Sort c[] using Bubble Sort ---- */
    for (i = 0; i < k - 1; i++)
    {
        for (j = 0; j < k - i - 1; j++)
        {
            if (c[j] > c[j + 1])
            {
                /* Swap */
                temp    = c[j];
                c[j]    = c[j + 1];
                c[j + 1] = temp;
            }
        }
    }

    /* ---- Step 5: Write sorted integers to file3.txt ---- */
    f3 = fopen("file3.txt", "w");
    if (f3 == NULL)
    {
        printf("Error: Cannot open file3.txt\n");
        exit(1);
    }
    for (i = 0; i < k; i++)
    {
        fprintf(f3, "%d\n", c[i]);
    }
    fclose(f3);

    printf("Merged and sorted successfully into file3.txt\n");
    return 0;
}

Dry Run Example

num1.txt contains: 5 2 8 num2.txt contains: 3 1 7

StepArray State
After readinga[] = {5, 2, 8}, b[] = {3, 1, 7}
After combiningc[] = {5, 2, 8, 3, 1, 7}
After Bubble Sortc[] = {1, 2, 3, 5, 7, 8}
Written to file3.txt1 2 3 5 7 8 (one per line)

Key File Handling Functions Used

FunctionPurpose
fopen(name, "r")Open file for reading
fopen(name, "w")Open file for writing
fscanf(fp, "%d", &x)Read an integer from file
fprintf(fp, "%d\n", x)Write an integer to file
fclose(fp)Close the file and flush buffer
exit(1)Terminate program on error

Conclusion

Global variables simplify data sharing but reduce modularity and security, so they should be used carefully. The file merging program demonstrates practical use of fopen(), fscanf(), fprintf() and fclose(), while the bubble sort applied to the combined array guarantees that every integer read from num1.txt and num2.txt is written into file3.txt in ascending order.

asked 2xavg 5 marks · 2079, 2077
Answer

Write short notes on:

a) Macro vs Function Write short notes on:

b) Break vs Continue [2.5+2.5]

Feature Macro Function --------- Definition Defined using define preprocessor directive Defined using return type, name, and body Processing Handled by preprocessor (before compilation) Handled by compiler at compile/run time Execution I...

asked 2xavg 5 marks · 2078, 2077
Answer

How break statement is different from continue statement. Explain with examples? [5]

The break statement is used to immediately terminate the loop (or switch) in which it appears. When break is executed, the program control jumps to the first statement after the loop. Output: The loop stops completely when i == 5. --- Th...

Study every one of these with model answers, flashcards, and MCQs.

Open BIT102 study modes