Summer 2018
Semester II – C Programming
Q1. Attempt any FIVE of the following : 10
(a) Define :
(i) Two dimensional array
In C, a two-dimensional array is a collection
of elements arranged in rows and columns, much like a matrix or a table. It
allows for data to be stored in a grid-like format, which is useful for
representing things like matrices, tables, and more complex data structures.
Here’s an overview of how to declare, initialize, and access two-dimensional
arrays in C.
1.
Declaring a Two-Dimensional Array
data_type
array_name[rows][columns];
Example
:
int arr[3][4];
This
will create a 3x4 matrix, meaning it has 3 rows and 4 columns.
Initializing a Two-Dimensional Array
int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
(ii) Multi-dimensional array
In C, multi-dimensional arrays extend beyond two dimensions, allowing you to create arrays with three, four, or even more dimensions. These are commonly used for data structures like matrices, 3D models, or tables that need more than two dimensions to represent the data effectively.
Declaration
A 3D array can be declared as follows:
int array[2][3][4];
Here
• The first dimension represents 2
“tables”.
• The second dimension represents 3 “rows”
in each table.
• The third dimension represents 4
“columns” in each row.
You can initialize a multi-dimensional array similarly to 2D arrays, but with additional nested braces for each level:
int array[2][3][4] = {
{
{1,
2, 3, 4},
{5,
6, 7, 8},
{9,
10, 11, 12}
},
{
{13,
14, 15, 16},
{17,
18, 19, 20},
{21,
22, 23, 24}
}
};
(b) Give any four advantages of
pointer.
Efficient
Memory Management: Pointers allow dynamic memory allocation, helping
manage memory usage efficiently during runtime.
Array
and String Manipulation: Pointers enable direct manipulation of arrays
and strings, making operations faster and more memory-efficient.
Efficient
Passing of Large Data Structures: Pointers enable passing large data
structures (like arrays and structs) to functions by reference, avoiding costly
data copying.
Support
for Complex Data Structures: Pointers are essential for creating and
managing complex data structures like linked lists, trees, and graphs.
(c) Define type casting. Give any
one example.
Type casting in C is the process of converting a variable from one data type to another. This is useful when you want to perform operations between different data types or control how data is interpreted.
Example
int x = 5;
float y = (float)x; // Type casting int to float
Here, x (an integer) is converted to a float,
so y will store 5.0 instead of 5.
(d) State any four decision making
statements.
Here are four decision-making statements in C:
1.
if statement – Executes a block of code if a specified condition is true.
2.
if-else statement – Executes one block of code if a condition is true and another block
if it’s false.
3.
else if ladder – Allows multiple conditions to be checked in sequence.
4.
switch statement – Selects one of many code blocks to execute based on the value of a
variable.
(e) State any four math functions
with its use.
Here are four commonly used math functions in
C:
1.
sqrt(x) – Calculates the square root of x.
sqrt(16); // Returns 4.0
2.
pow(x, y) – Raises x to the power of y.
pow(2, 3); // Returns 8.0
3.
abs(x) – Returns the absolute (positive) value of an integer x.
abs(-5); // Returns 5
4.
ceil(x) – Rounds x up to the nearest integer.
ceil(2.3); // Returns 3.0
These functions are part of the <math.h>
library in C and are useful for performing common mathematical operations.
(f) State the use of following
symbols used for flowchart drawing :
In a flowchart, the rectangle shape represents a process or operation. It indicates a step where an action or calculation is performed. This can include tasks such as initializing a variable, performing a calculation, or executing a specific procedure.
Example of
Rectangle in Flowchart:
- Process: For example, "Calculate Total
Cost" or "Update Inventory."
Typical
Usage:
- Start Process: "Initialize
counter to 0"
- Math Operation:
"Sum = A + B"
- Assignment:
"Set X = 10"
The rectangle is one of the most frequently
used symbols in flowcharts, as it details the operational steps in the process.
In a flowchart, the diamond shape represents a decision point. It indicates a point where a condition is evaluated, leading to different branches based on whether the condition is true or false.
Example of
Diamond in Flowchart:
- Decision: "Is X greater than 10?" or
"Is the user authenticated?"
Typical
Usage:
- If the condition is true, the flow follows one branch.
- If the condition is false, the flow follows another branch.
The diamond shape is essential for
incorporating decision-making and branching in a flowchart.
- Example: Enter Name, Display Result
Represents the start or end of a process.
- Example: Start, End
(g) State use of while loop with
syntax.
Ans. The while loop in
C is used to repeatedly execute a block of code as long as a specified
condition evaluates to true. It is a type of entry-controlled loop, meaning the
condition is checked before the loop body is executed.
Syntax of while Loop
while (condition) { // Statements to be executed repeatedly}
Q2. Attempt any THREE of the
following : Marks 12
(a) Develop a simple ‘C’ program for
addition and multiplication of two integer numbers.
Ans.
#include <stdio.h>
int main() {
int num1, num2; // Variables to
store the two integers
int sum, product; // Variables to
store the results
// Input two integers
printf("Enter the first integer: ");
scanf("%d", &num1);
printf("Enter the second integer: ");
scanf("%d", &num2);
// Perform addition and multiplication
sum = num1 + num2;
product = num1 * num2;
// Display the results
printf("The sum of %d and %d is: %d\n", num1, num2, sum);
printf("The product of %d and %d is: %d\n", num1, num2, product);
return 0;
}
(b) Explain how to pass pointer to
function with example.
Ans.
Passing
Pointer to Function
In C, a pointer can be passed to a function to
allow the function to modify the actual value of a variable in the caller's
scope or to work with dynamically allocated memory.
When a pointer is passed:
1.
The address of the variable is passed to the
function.
2.
Inside the function, the * operator (dereference) is used to access or modify the value at the
passed address.
Syntax
void function_name(data_type
*pointer) {
// Access or modify the value using
*pointer
}
Example:
Swapping Two Numbers
This example demonstrates using pointers to
swap two integers:
#include <stdio.h>
// Function
to swap two integers using pointers
void swap(int
*a, int *b) {
int temp = *a; // Dereference 'a' to access the value
*a = *b; // Swap values
*b = temp;
}
int main()
{
int x = 5, y = 10;
printf("Before swapping: x = %d, y =
%d\n", x, y);
swap(&x, &y); // Pass the addresses of x and y
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
(c) Explain following functions :
getchar( )
putchar( )
getch( )
putch( )
with suitable examples.
Ans.
getchar()
The getchar() function is a standard library function in C used to read a single
character from the standard input (keyboard). It is part of the <stdio.h> library.
Key Points
1.
It reads one character at a time.
2.
Returns the ASCII value of the character read.
3.
To use the character, you often store the
return value in a char variable.
4.
It waits for the user to press Enter
after typing the character.
Syntax
int getchar(void);
Returns: The character entered, cast as an int.
putchar( )
The putchar()
function in C is used to print a single character to the standard output
(screen). It is part of the <stdio.h> library.
Key Points
1.
It outputs one character at a time.
2.
Takes a single character as an argument (in int form).
3.
Useful for displaying characters, especially
in loops.
Syntax
int putchar(int ch);
getch( )
The getch() function
is used to read a single character from the keyboard without displaying it on
the screen. It is commonly used for taking character input in interactive
programs. It is a part of the <conio.h> library, which is specific to certain compilers like
Turbo C.
Key Points
1.
Reads a single character from the
keyboard.
2.
Does not echo the character on the
screen.
3.
Does not require pressing Enter after
input.
4.
Useful for cases where instant input is
needed, such as menu navigation.
Syntax
char getch(void);
putch( )
The putch() function
is used to print a single character to the screen. It is part of the <conio.h>
library, which is specific to certain compilers like Turbo C.
Key Points
1.
Outputs a single character to the
screen.
2.
Similar to putchar() but specific to the <conio.h> library.
3.
Takes a character as an argument and
immediately displays it.
Syntax
void putch(char
ch);
(d) Develop a program to accept an integer number and print whether it is palindrome or not.
Ans.
#include <stdio.h>
int main() {
int num, original, reversed = 0, remainder;
// Input an integer
printf("Enter an integer: ");
scanf("%d", &num);
original = num; // Store the original number
// Reverse the number
while (num != 0) {
remainder = num % 10; // Get the last digit
reversed = reversed * 10 +
remainder; // Build the reversed number
num /= 10; // Remove the last digit
}
// Check if the original and reversed numbers are the same
if (original == reversed) {
printf("%d is a
palindrome.\n", original);
} else {
printf("%d is not a
palindrome.\n", original);
}
return 0;
}
Q3. Attempt any THREE of the
following : 12
(a) State the use of printf( ) &
scanf( ) with suitable example.
Ans.
The printf() and scanf()
functions are two of the most commonly used functions in C for output
and input operations, respectively.
1. printf() Function
The printf() function is
used to display (print) output to the console (standard output). It allows
formatted output and can print variables, strings, and other data types using
format specifiers.
Syntax
int printf(const char *format, ...);
format: A string containing format specifiers (e.g.,%d,%f,%s) that tell the function how to print the variables that follow.- Returns: The number of characters printed (excluding the
null character).
printf("Integer value:
%d\n", a); // %d is used for integer
printf("Float value:
%.2f\n", b); // %.2f is used for float (2
decimal places)
2. scanf() Function
The scanf() function is
used to read input from the user (keyboard). It stores the input values into
variables based on the format specifiers provided.
Syntax
int scanf(const char *format, ...);
format: A string that specifies the expected type of input (e.g.,%dfor integers,%ffor floats).- Returns: The number of successful inputs (not counting
the return value for incorrect input).
Example:
Using scanf()
//
Taking input from the user using scanf
printf("Enter an integer: ");
scanf("%d", &x); // %d is for integer input
printf("Enter a floating point number:
");
scanf("%f", &y); // %f is for float input
(b) Explain any four library
functions under conio.h header file.
Ans.
The <conio.h> header
file in C provides several functions that are used for console input and output
operations. This header is specific to certain compilers (like Turbo C) and is
not part of the standard C library. It includes functions for controlling the
console, such as reading input without displaying it, clearing the screen, and
controlling the cursor position.
Here are four commonly used functions from
the <conio.h> header:
Library Functions under <conio.h> in C
The <conio.h> header
file in C provides several functions that are used for console input and output
operations. This header is specific to certain compilers (like Turbo C) and is
not part of the standard C library. It includes functions for controlling the
console, such as reading input without displaying it, clearing the screen, and
controlling the cursor position.
Here are four commonly used functions from
the <conio.h> header:
1. clrscr() Function
The clrscr() function is
used to clear the screen. It clears all characters from the console, providing
a clean output screen.
Syntax
void clrscr(void);
2. getch() Function
The getch() function is
used to read a single character from the keyboard, without echoing it to the
screen. It waits for the user to press a key, and then returns the ASCII value
of that character.
Syntax
char getch(void);
3. gotoxy() Function
The gotoxy() function is
used to move the cursor to a specified position on the console screen. The
function takes two parameters: the x-coordinate (column) and the y-coordinate
(row) of the cursor.
Syntax
void gotoxy(int x, int y);
4. textcolor() and textbackground()
Functions
The textcolor() and textbackground() functions are used to set the color of the text and
the background on the console. These functions make the console output more
colorful and visually appealing.
Syntax
void textcolor(int color);void textbackground(int color);
(c) Explain how formatted input can
be obtain, give suitable example.
Ans. In C, formatted input is used to read
data from the user in a specific format. The scanf() function
is commonly used to perform formatted input. It allows the user to input
different data types such as integers, floating-point numbers, and strings,
while also specifying how the input should be processed using format
specifiers.
1.
Format Specifiers: These are placeholders in the format string of scanf() that tell the function how to interpret the user input.
2.
Data Types: You can use different format specifiers for various data types like
integers, floats, characters, etc.
3.
Multiple Inputs: You can use multiple format specifiers in a single scanf() function call to read multiple values at once.
Common
Format Specifiers in scanf()
- %d for integer input.
- %f for floating-point input.
- %c for a single character input.
- %s for a string input (reads until a
space is encountered).
- %lf for double input.
Syntax of scanf()
int scanf(const
char *format, ...);
- format: A string containing one or more format
specifiers.
- Returns: The number of successful inputs.
// Take formatted input
printf("Enter your age (integer): ");
scanf("%d", &age);
// Reading an integer
printf("Enter your salary
(floating-point): ");
scanf("%f", &salary);
// Reading a float
printf("Enter your grade (single character): ");
scanf(" %c", &grade);
// Reading a single character. Note the space before %c to skip any
newline character.
printf("Enter your name (string): ");
scanf("%s", name); //
Reading a string
(d) Develop a program to find
factorial of a number using recursion.
Ans.
#include <stdio.h>
// Recursive function to calculate
factorial
int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: n * factorial of (n-1)
else {
return n * factorial(n - 1);
}
}
int main() {
int num;
// Input a number from the user
printf("Enter a number: ");
scanf("%d", &num);
// Check for negative numbers (factorial is not defined for negative
numbers)
if (num < 0) {
printf("Factorial is not defined
for negative numbers.\n");
} else {
// Call the recursive factorial
function and print the result
printf("Factorial of %d is
%d\n", num, factorial(num));
}
return 0;
}
Q4. Attempt any THREE of the
following : 12
(a) Write a program to sweep the
values of variables a = 10, b = 5 using function.
Ans.
#include <stdio.h>
// Function to swap two variables using pointers
void swap(int *a, int *b) {
int temp;
temp = *a; // Store the value of a in temp
*a = *b; // Assign the value of b to a
*b = temp; // Assign the value of temp (original a) to b
}
int main() {
int a = 10, b = 5;
// Print initial values of a and
b
printf("Before
swapping:\n");
printf("a = %d, b =
%d\n", a, b);
// Call the swap function to swap
the values of a and b
swap(&a, &b);
// Print swapped values of a and
b
printf("After
swapping:\n");
printf("a = %d, b =
%d\n", a, b);
return 0;
}
(b) Develop a program using
structure to print data of three students having data members name, class,
percentage.
Ans.
#include <stdio.h>
// Define a structure to store
student information
struct Student {
char name[50];
char class[10];
float percentage;
};
int main() {
// Declare an array of 3 students
struct Student students[3];
// Input details for each student
for (int i = 0; i < 3; i++) {
printf("Enter details for student %d\n", i + 1);
printf("Enter name: ");
scanf("%s", students[i].name);
printf("Enter class: ");
scanf("%s", students[i].class);
printf("Enter percentage: ");
scanf("%f", &students[i].percentage);
printf("\n");
}
// Print the details of all students
printf("\nDetails of the students:\n");
for (int i = 0; i < 3; i++) {
printf("Student %d\n", i +
1);
printf("Name: %s\n",
students[i].name);
printf("Class: %s\n",
students[i].class);
printf("Percentage:
%.2f%%\n\n", students[i].percentage);
}
return 0;
}
(c) Design a program to print a
message 10 times.
Ans.
#include <stdio.h>
int main() {
// Loop to print the message 10 times
for (int i = 1; i <= 10; i++) {
printf("This is message number
%d\n", i);
}
return 0;
}
(d) Draw a flowchart for checking whether given number is prime or not.
· Start: The flowchart
begins with a start symbol.
· Input Number: A number N is input from the user.
· Initialize i: A variable i is initialized to 2, which will be used to check divisibility.
· Check for 1 or Less: If N is less than or equal to 1, it's not prime, so the flowchart moves to
the "N is not prime" end.
· Check Divisibility: The
flowchart checks if N is
divisible by i.
- If divisible, N is not prime, and the flowchart moves to the "N is not
prime" end.
- If not divisible, the value of i is incremented.
· Loop: The flowchart loops
back to step 4 to check divisibility with the incremented i.
· Prime or Not Prime: If
the loop completes without finding a divisor, N is prime. Otherwise, it's not prime.
· End: The flowchart ends with an end
symbol.
(e) Implement a program to
demonstrate logical AND operator.
Ans. The Logical AND (&&)
operator in C evaluates to true (non-zero) only
if both operands are true. If either operand is false (zero), the
result is false (zero).
#include <stdio.h>
int main() {
int a, b;
// Input two numbers
printf("Enter two numbers (a and b): ");
scanf("%d %d", &a, &b);
// Demonstrate the logical AND operator
if (a > 0 && b > 0) {
printf("Both a and b are positive
numbers.\n");
} else {
printf("At least one of a or b is
not a positive number.\n");
}
return 0;
}
Q5. Attempt any TWO of the following : 12
(a) Draw a flowchart of Do-while
loop and write a program to add numbers until user enters zero.
Ans.
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Enter numbers to add (enter 0 to stop):\n");
// Do-while loop to repeatedly add numbers until 0 is entered
do {
printf("Enter a number: ");
scanf("%d", &num);
sum += num; // Add the input number to
the sum
} while (num != 0);
// Print the total sum
printf("The total sum is: %d\n", sum);
return 0;
}
(b) Give a method to create, declare
and initialize structure also develop a program to demonstrate nested
structure.
Ans.
Steps to
Declare and Initialize a Structure:
1.
Declare
a Structure: Use the struct keyword to
define a structure with its members.
2.
Create
a Structure Variable: Declare a
variable of the structure type to use it in the program.
3.
Initialize
a Structure: Assign values to
structure members using dot notation (.) or directly at the time of declaration.
Example :
// Creating and initializing a structure variable struct Student s1 = {"Alice", 20, 85.5};
A nested structure is a structure
that contains another structure as a member. It is useful for creating
hierarchical data.
#include <stdio.h>
// Defining an Address structure
struct Address {
char city[50];
char state[50];
int pincode;
};
// Defining a Student structure
containing Address as a nested structure
struct Student {
char name[50];
int age;
float percentage;
struct Address addr; // Nested structure
};
int main() {
// Declaring and initializing a nested structure
struct Student s1 = {
"Alice",
20,
85.5,
{"New York", "New
York", 10001}
};
// Accessing and displaying nested structure members
printf("Student Details:\n");
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("Percentage: %.2f\n", s1.percentage);
printf("Address: %s, %s, %d\n", s1.addr.city, s1.addr.state, s1.addr.pincode);
return 0;
}
(c) Implement a program to
demonstrate concept of pointers to function.
Ans.
A pointer to a function in C
is a pointer that stores the address of a function. This allows us to call
functions indirectly or pass them as arguments to other functions, enabling
flexibility and dynamic behavior in programming.
#include <stdio.h>
// Function declarations
int add(int a, int b);
int subtract(int a, int b);
int main() {
int x = 10, y = 5;
int result;
// Pointer to a function
int (*operation)(int, int);
// Assign the address of 'add' function to the pointer
operation = add;
result = operation(x, y); // Call the 'add' function via pointer
printf("Addition: %d + %d = %d\n", x, y, result);
// Assign the address of 'subtract' function to the pointer
operation = subtract;
result = operation(x, y); // Call the 'subtract' function via pointer
printf("Subtraction: %d - %d = %d\n", x, y, result);
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
Q6. Attempt any TWO of the following
: 12
(a) Develop a program to swap two
numbers using pointer and add swapped numbers also print their addition.
Ans.
#include <stdio.h>
// Function to swap two numbers
using pointers
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1, num2, sum;
// Input two numbers
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
// Print original numbers
printf("\nBefore swapping:\n");
printf("Number 1: %d\n", num1);
printf("Number 2: %d\n", num2);
// Swap numbers using pointers
swap(&num1, &num2);
// Print swapped numbers
printf("\nAfter swapping:\n");
printf("Number 1: %d\n", num1);
printf("Number 2: %d\n", num2);
// Add swapped numbers
sum = num1 + num2;
printf("\nSum of swapped numbers: %d\n", sum);
return 0;
}
(b) Design a programme in C to read
the n numbers of values in an array and display it in reverse order.
Ans.
#include <stdio.h>
int main() {
int n;
// Prompt the user for the number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n]; // Declare an array of size n
// Read elements into the array
printf("Enter %d numbers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display the array in reverse order
printf("Numbers in reverse order:\n");
for (int i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
(c) Develop a program to find
diameter, circumference and area of circle using function.
Ans.
#include <stdio.h>
// Function prototypes
float calculateDiameter(float radius);
float calculateCircumference(float radius);
float calculateArea(float radius);
int main() {
float
radius, diameter, circumference, area;
// Input
radius of the circle
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
// Calculate
diameter, circumference, and area using functions
diameter =
calculateDiameter(radius);
circumference = calculateCircumference(radius);
area =
calculateArea(radius);
// Display
the results
printf("Diameter: %.2f\n", diameter);
printf("Circumference: %.2f\n", circumference);
printf("Area: %.2f\n", area);
return 0;
}
// Function to calculate diameter
float calculateDiameter(float radius) {
return 2 *
radius;
}
// Function to calculate circumference
float calculateCircumference(float radius) {
return 2 *
3.14159 * radius; // π is approximately 3.14159
}
// Function to calculate area
float calculateArea(float radius) {
return
3.14159 * radius * radius;
}