0% found this document useful (0 votes)
39 views18 pages

Sample Questions and Answers in C Programming 2

My sample questions in C Programming Language at UniMak, Computer Science Year One.

Uploaded by

abubakarrabk992
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views18 pages

Sample Questions and Answers in C Programming 2

My sample questions in C Programming Language at UniMak, Computer Science Year One.

Uploaded by

abubakarrabk992
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

SAMPLE QUESTIONS AND ANSWERS IN C PROGRAMMING

Q1. Role of printf and scanf in C Programming:

In C programming, printf and scanf are two fundamental functions used for input and
output operations.

 printf:

 The printf function is used to display output on the screen. It allows the
programmer to format and print data on the standard output device
(usually the console). The syntax of printf includes a format string followed
by variables or values to be displayed. For example, %d is used to display
integers, %f for floating-point numbers, %c for characters, etc.

 scanf:

 The scanf function is used to read input from the user. It allows the
programmer to accept input from the standard input device (usually the
keyboard). The syntax of scanf includes format specifiers that correspond to
the type of data being read. For example, %d is used to read integers, %f for
floating-point numbers, %c for characters, etc.

Simple C Program using printf and scanf:

Here is a simple C program that takes an integer input from the user and prints it:

#include

int main() {

int num;

printf("Enter an integer: ");

scanf("%d", &num);

printf("You entered: %d\n", num);

return 0;

In this program: Page: 1

 We include the necessary header file which contains declarations for input/output
functions.
 Declare an integer variable num.

 Use printf to prompt the user to enter an integer.

 Use scanf to read an integer from the user and store it in the variable num.

 Finally, use another printf statement to display the entered integer back to the
user.

Q2. Discuss the different data types available in C. Provide examples of how to
declare variables of each data type.

Data Types in C

In C programming language, data types specify the type of data that a variable can hold.
There are several data types available in C, each designed to store different types of
values. Here are some of the common data types in C:

1. Integer Data Types : Integers are whole numbers without any decimal points. In C,
there are different integer data types based on the range of values they can store.
Examples of integer data types in C include:

 int: Used to store integers within a specific range.

int num = 10;

 short: Used to store smaller integers than int.

short count = 5;

 long: Used to store larger integers than int.

long population = 1000000L;

2. Floating-Point Data Types : Floating-point data types are used to represent numbers
with decimal points. Examples of floating-point data types in C include:

 float: Used to store single-precision floating-point numbers.

float pi = 3.14f; Page: 2


 double: Used to store double-precision floating-point numbers.

double price = 19.99;

3. Character Data Type: The character data type is used to store individual characters or
small integers. In C, the character data type is represented by char.

char grade = 'A';

4. Void Data Type: The void data type is used to indicate that a function does not return
any value or a pointer that points to a value of unknown type.

5. void displayMessage() {

6. printf("Hello, World!\n");

7. Derived Data Types : Derived data types in C include arrays, pointers, structures, and
unions.

8. Enumerated Data Type: Enumerated data types allow you to define your own set of
values with symbolic names.

9. User-Defined Data Types: In C, you can create your own custom data types using
structures and typedef.

These are some of the common data types available in C programming language, each
serving a specific purpose in storing and manipulating different kinds of data.

Q3. Explain the use of conditional statements in C programming. Compare and


contrast the if-else and switch-case statements with suitable examples.

Conditional Statements in C Programming:

Conditional statements in C programming are used to make decisions based on certain


conditions. These statements allow the program to execute different blocks of code based
on whether a specified condition evaluates to true or false. The two main types of
conditional statements in C are the if-else statement and the switch-case statement.
Page: 3
If-Else Statement:

The if-else statement is one of the most commonly used conditional statements in C
programming. It allows the program to execute a block of code if a specified condition is
true, and another block of code if the condition is false. The general syntax of an if-
else statement in C is as follows:

if (condition) {

// code to be executed if the condition is true

} else {

// code to be executed if the condition is false

Here is an example of how an if-else statement can be used in C programming:

#include

int main() {

int num = 10;

if (num > 0) {

printf("The number is positive\n");

} else {

printf("The number is not positive\n");

return 0;

In this example, if the value of num is greater than 0, it will print “The number is
positive”; otherwise, it will print “The number is not positive”.

Switch-Case Statement:

The switch-case statement is another type of conditional statement in C that allows for
multi-way branching based on a variable’s value. It provides a more efficient way to
handle multiple conditions compared to using multiple if-else statements. The general
syntax of a switch-case statement in C is as follows:

switch (expression) {

case constant1:
Page: 4
// code to be executed if expression equals constant1
break;

case constant2:

// code to be executed if expression equals constant2

break;

...

default:

// code to be executed if expression doesn't match any case

Here is an example of how a switch-case statement can be used in C programming:

#include

int main() {

char grade = 'B';

switch (grade) {

case 'A':

printf("Excellent!\n");

break;

case 'B':

printf("Good job!\n");

break;

case 'C':

printf("Passing grade\n");

break;

default:

printf("Invalid grade\n");

return 0;
Page: 5
}

In this example, based on the value of the variable grade, different messages will be
printed using the switch-case statement.
Comparison between If-Else and Switch-Case Statements:

1. Use Cases:

 The if-else statement is suitable when there are only two possible outcomes
based on a single condition.

 The switch-case statement is more appropriate when there are multiple


possible outcomes based on the value of an expression.

2. Readability:

 In some cases, using multiple nested if-else statements can make the code
less readable.

 The switch-case statement can provide better readability when dealing


with multiple conditions.

3. Performance:

 In terms of performance, both statements have their advantages and


disadvantages depending on the specific scenario.

 Generally, compilers can optimize both types of statements for efficiency.

4. Expression Type:

 The if-else statement works with any expression that evaluates to a


boolean value (true/false).

 The switch-case statement works with expressions that evaluate to


integral types like integers or characters.

In conclusion, both the if-else and switch-case statements are essential tools for
implementing conditional logic in C programming, each with its own strengths and best
use cases.

Q4. Describe the three types of loops in C. Write a C program using a for loop to
print thefirst 10 natural numbers.

Types of Loops in C:

In C programming, there are three main types of loops: for, while, and do-while loops.
Each type of loop serves a specific purpose and can be used based on the requirements of
the program.

1. For Loop: The for loop is used when the number of iterations is known
beforehand. It consists of three parts: initialization, condition, and
increment/decrement. The syntax of a for loop in C is as follows:

for (initialization; condition; increment/decrement) {


Page: 6
// code to be executed
}

The for loop will execute the code block repeatedly as long as the condition remains true.
It is commonly used when you know exactly how many times you want to iterate.

2. While Loop: The while loop is used when the number of iterations is not known
beforehand, and it continues to execute until the specified condition becomes false.
The syntax of a while loop in C is as follows:

while (condition) {

// code to be executed

The while loop checks the condition before entering the loop body. If the condition is true,
it executes the code block.

3. Do-While Loop: The do-while loop is similar to the while loop, but it guarantees
that the code block will be executed at least once before checking the condition. The
syntax of a do-while loop in C is as follows:

do {

// code to be executed

} while (condition);

The do-while loop first executes the code block and then checks the condition. If the
condition is true, it continues to execute.

C Program Using For Loop to Print First 10 Natural Numbers:

Here’s a simple C program that uses a for loop to print the first 10 natural numbers:

#include

int main() {

int i;

printf("First 10 natural numbers:\n");

for (i = 1; i <= 10; i++) {

printf("%d\n", i);

return 0;

}
Page: 7
In this program:
 We initialize an integer variable i.

 We use a for loop that starts from 1 and goes up to 10.

 Inside the loop, we print each number from 1 to 10.

When you run this program, it will output:

First 10 natural numbers:

10

Q5. Define what a function is in C programming. Explain the difference between


function prototypes and function definitions with examples.

Definition of a Function in C Programming:

In C programming, a function is a block of code that performs a specific task. Functions


provide modularity to the program by breaking it into smaller, manageable pieces. They
help in organizing code, improving readability, and reusability. Functions in C have a
name, return type, parameters (optional), and a body containing the code to be executed.

Difference between Function Prototypes and Function Definitions:

Function Prototype: A function prototype in C is a declaration of the function that tells


the compiler about the function’s name, return type, and parameters it expects. It
provides information to the compiler about the existence of the function before its actual
definition. Function prototypes are usually placed at the beginning of the program or in
header files.

Example of a Function Prototype:

#include

// Function prototype Page: 8


int add(int num1, int num2);

int main() {

int result = add(5, 3);

printf("Result: %d\n", result);

return 0;

// Function definition

int add(int num1, int num2) {

return num1 + num2;

In this example, int add(int num1, int num2); is the function prototype for
the add function. It informs the compiler about the existence of the add function with its
signature.

Function Definition: A function definition in C provides the actual implementation or


body of the function. It contains the executable code that defines what the function does
when called. The function definition includes the return type, name, parameters list, and
statements inside curly braces {}.

Example of a Function Definition:

#include

// Function prototype

int multiply(int num1, int num2);

int main() {

int result = multiply(4, 6);

printf("Result: %d\n", result);

return 0;

// Function definition

int multiply(int num1, int num2) {

return num1 * num2;

} Page: 9
In this example, int multiply(int num1, int num2) { return num1 * num2; } is the
function definition for the multiply function. It specifies how to perform multiplication
when this function is called.

5. Discuss the concept of passing arguments to functions by value and by


reference. Provide code examples to illustrate both methods.

Passing Arguments to Functions by Value and by Reference

When passing arguments to functions in programming languages, there are two common
methods: passing by value and passing by reference.

Passing by Value:

 When passing by value, a copy of the actual parameter’s value is passed to the
function. This means that any changes made to the parameter inside the function
do not affect the original value outside the function.

 In languages like C++, Java, and Python, primitive data types (integers, floats,
characters) are typically passed by value.

 Here is an example in C++:

#include

using namespace std;

void increment(int num) {

num++;

int main() {

int x = 5;

increment(x);

cout << x; // Output will be 5, as x remains unchanged

return 0;

In this example, the increment function receives a copy of x, increments it within the
function, but the original x in main remains unchanged.

Passing by Reference: Page: 10

 When passing by reference, instead of passing a copy of the value, a reference or


memory address of the actual parameter is passed. This allows changes made to
the parameter inside the function to reflect on the original value outside the
function.

 In languages like C++, C#, and Python (using pointers), objects and non-primitive
data types are typically passed by reference.

 Here is an example in C++:

#include

using namespace std;

void increment(int &num) {

num++;

int main() {

int x = 5;

increment(x);

cout << x; // Output will be 6, as x is modified inside the function

return 0;

In this example, increment receives a reference to x, so any changes made to num inside
the function directly affect x.

Q6. What are arrays in C programming? Explain how to declare and initialize a
one-dimensional and a two-dimensional array with examples.

Arrays in C Programming

In C programming, an array is a collection of elements of the same data type that are
stored in contiguous memory locations. Arrays provide a way to store multiple values
under a single name, making it easier to manage and manipulate large sets of data.

Declaring and Initializing a One-Dimensional Array

To declare and initialize a one-dimensional array in C, you can follow these steps:

1. Declaration: You need to specify the data type of the elements in the array and
the size of the array.

2. Initialization: You can initialize the elements of the array at the time of
declaration or later using loops or individual assignments.

Here is an example of declaring and initializing a one-dimensional array in C: Page: 11


#include

int main() {

// Declaration and initialization of a one-dimensional array

int arr[5] = {10, 20, 30, 40, 50};

// Accessing elements of the array

for (int i = 0; i < 5; i++) {

printf("Element at index %d: %d\n", i, arr[i]);

return 0;

In this example, we declared an integer array arr with a size of 5 elements and initialized
it with values {10, 20, 30, 40, 50}. We then accessed and printed each element using a
loop.

Declaring and Initializing a Two-Dimensional Array

To declare and initialize a two-dimensional array in C, you can use nested square
brackets to represent rows and columns.

Here is an example of declaring and initializing a two-dimensional array in C:

#include

int main() {

// Declaration and initialization of a two-dimensional array

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

// Accessing elements of the two-dimensional array

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

printf("%d ", matrix[i][j]);

printf("\n");

} Page: 12
return 0;

In this example, we declared a two-dimensional integer array matrix with


dimensions 3x3 and initialized it with values {1,2,3},{4,5,6},{7,8,9}. We then accessed and
printed each element by iterating over rows and columns using nested loops.

Q8. Describe the methods to access and manipulate elements of an array. Write
a C program that finds the sum of all elements in a given integer array.

Accessing Elements of an Array

Arrays in C programming language are a collection of elements of the same data


type stored in contiguous memory locations. Each element of the array can be
accessed using its index or subscript.

To access an element of an array, we use the array name followed by the index of the
element in square brackets []. For example, if we have an array int arr[5];, we can access
the first element of the array using arr[0].

Manipulating Elements of an Array

We can manipulate elements of an array by assigning a new value to the element


using the assignment operator (=).

For example, if we want to assign the value 10 to the first element of the array arr, we
can use the statement arr[0] = 10;.

Finding the Sum of All Elements in an Array

To find the sum of all elements in an array, we can use a loop to iterate over
each element of the array and add it to a sum variable.

Here is a C program that finds the sum of all elements in a given integer array:

#include

int main() {

int arr[5] = {1, 2, 3, 4, 5}; // declare and initialize an array

int sum = 0; // declare a sum variable

int i; // declare a loop variable

**for (i = 0; i < 5; i++) {**

**sum += arr[i];** // add each element to the sum


Page: 13
**}**
printf("The sum of all elements in the array is: %d\n", sum);

return 0;

This program declares and initializes an array arr with 5 elements. It then declares a
sum variable sum and initializes it to 0. The program uses a for loop to iterate over each
element of the array, adding each element to the sum variable using the statement sum
+= arr[i];. Finally, the program prints the sum of all elements in the array using printf.

Q9. Explain the concept of pointers in C. Discuss pointer arithmetic with


examples.

Pointers in C

In C programming, a pointer is a variable that stores the memory address of another


variable. Pointers are powerful and versatile tools that allow for more efficient memory
management and manipulation of data. They are widely used in C programming to work
with arrays, strings, dynamic memory allocation, and functions.

Declaring Pointers: To declare a pointer in C, you specify the data type followed by an
asterisk (*) and the name of the pointer variable. For example:

int *ptr;

This declares a pointer named ptr that can point to an integer variable.

Initializing Pointers: Pointers can be initialized to point to a specific memory location


or another variable. For example:

int num = 10;

int *ptr = #

In this example, ptr is initialized to point to the memory address of the num variable
using the address-of operator (&).

Dereferencing Pointers: Dereferencing a pointer means accessing the value stored at


the memory address it points to. This is done using the indirection operator (*) before the
pointer variable. For example:

int value = *ptr;

This retrieves the value stored at the memory location pointed to by ptr.

Pointer Arithmetic: Pointer arithmetic involves performing arithmetic operations on


pointers. When you perform arithmetic on pointers, they are adjusted based on the size of
their underlying data type.

Example of Pointer Arithmetic: Consider an array of integers: Page: 14


int arr[] = {10, 20, 30, 40};

int *ptr = arr; // ptr points to the first element of arr

// Accessing elements using pointer arithmetic

printf("%d\n", *ptr); // Output: 10

printf("%d\n", *(ptr + 1)); // Output: 20

printf("%d\n", *(ptr + 2)); // Output: 30

In this example, by adding an integer value to a pointer (ptr + n), we move n positions
forward in memory based on the size of an integer.

Pointer arithmetic can also be used to iterate over arrays efficiently without needing
array indices.

Overall, pointers in C provide flexibility and efficiency in handling memory addresses and
manipulating data structures.

Q10. Discuss how pointers and arrays are related in C. Write a C program that
demonstrates how to use pointers to access and modify array elements.

Pointers and Arrays Relationship in C:

In C programming, pointers and arrays are closely related due to the way arrays are
implemented in the language. In fact, arrays and pointers are so closely related that they
are often used interchangeably in many contexts.

1. Relationship between Pointers and Arrays:

 In C, an array name can be used as a pointer to the first element of the array.

 When an array name is used in an expression without being subscripted, it decays


into a pointer to its first element.

 This means that you can use pointer arithmetic with array names just like you
would with regular pointers.

2. Using Pointers to Access and Modify Array Elements: Here is a simple C program
that demonstrates how to use pointers to access and modify array elements:

#include

int main() {

int arr[5] = {10, 20, 30, 40, 50};

int *ptr = arr; // Pointer pointing to the first element of the array Page: 15
// Accessing array elements using pointers

for (int i = 0; i < 5; i++) {

printf("Element %d: %d\n", i, *(ptr + i));

// Modifying array elements using pointers

*(ptr + 2) = 35; // Modifying the third element of the array

// Printing the modified array

printf("\nArray after modification:\n");

for (int i = 0; i < 5; i++) {

printf("Element %d: %d\n", i, *(ptr + i));

return 0;

In this program:

 We declare an integer array arr with 5 elements.

 We declare a pointer ptr and initialize it to point to the first element of the array.

 We then use pointer arithmetic to access and modify elements of the array through
the pointer.

When you run this program, you will see that it accesses and modifies elements of the
array using pointers.

Q11. Describe the basic file handling operations in C. Write a C program that
opens a file, writes a string to it, and then closes the file.

Basic File Handling Operations in C:

In C programming, file handling operations are essential for reading from and writing to
files. The basic file handling operations in C involve opening a file, reading from it,
writing to it, and closing it. Below is a step-by-step guide on how to write a C program
that opens a file, writes a string to it, and then closes the file.
Page: 16
Step 1: Include Necessary Header Files:

#include
Step 2: Define the Main Function:

int main() {

FILE *filePointer;

char data[50] = "Hello, World!";

// Open the file in write mode

filePointer = fopen("sample.txt", "w");

if (filePointer == NULL) {

printf("File could not be opened.");

return 1;

// Write data to the file

fprintf(filePointer, "%s", data);

// Close the file

fclose(filePointer);

return 0;

In this program:

 We first include the necessary header file stdio.h.

 We define the main function where we declare a pointer to a FILE structure and
an array data containing the string we want to write to the file.

 We open a file named sample.txt in write mode using fopen. If the file cannot be
opened, an error message is displayed.

 We use fprintf to write the string stored in data to the file.

 Finally, we close the file using fclose.

This program demonstrates the basic file handling operations of opening a file, writing
data to it, and then closing it.

Prepared by: James Pablo Page: 17


Page: 18

You might also like