C PROGRAMMING FOR ENGINEERS
Code No: 181AF (Scheme)
1.a) What is a datatype?..[1]
A datatype is a classification that specifies the type of data that a variable, object, or
expression can hold in a programming language or database. It defines the kind of
operations that can be performed on the data and how it is stored in memory.
1. b) Define constant..[1]
A constant is a value that cannot be altered or modified once it is defined during the
execution of a program. Constants are often used to represent fixed values that remain the
same throughout a program.
1. c)What is the use of break keyword?..[1]
The break keyword is used in programming to terminate the execution of a loop or switch
statement prematurely. When the break keyword is encountered, the program exits the
current loop or switch and resumes execution at the next statement following it.
1.d) What is Type conversion?..[1]
Type conversion is the process of converting data from one data type to another. It allows a
variable of one type to be treated as another type, which is often necessary when
performing operations involving different data types.
1.e) Write two advantages of Recursion..[1]
Two advantages of recursion:
1. Simplified Code for Complex Problems
Recursion provides a clean and intuitive way to solve problems that have a repetitive
or self-similar structure.
2. Natural Fit for Problems with Backtracking
Recursion is well-suited for problems where the solution requires exploring multiple
possibilities and backtracking.
1.f) Discuss the limitations of arrays..[1]
1. Fixed Size
2. Contiguous Memory Allocation
3. No Built-in Dynamic Behavior
4. Inefficient Insertion and Deletion
1.g) Write the applications of pointers.[1]
Dynamic Memory Allocation:Pointers are used with functions like malloc(), calloc(), and
free() to allocate and manage memory at runtime.
Array and String Manipulation:Pointers allow direct access to array elements and strings
for efficient manipulation.
Data Structures:Pointers are used to dynamically create and manage nodes in data structures
like linked lists, binary trees, and graphs.
1.h) Write the purpose of #ifndef preprocessor directive in C..[1]
The #ifndef preprocessor directive in C stands for "if not defined." It is primarily used to
prevent multiple inclusions of the same header file in a program. This ensures that the
compiler processes the contents of the header file only once, avoiding issues like redefinition
errors.
1.i) Write the time complexity of Binary search…[1]
The time complexity of Binary Search is as follows:
1. Best Case:O(1)
2. Worst Case:O(log n)
3. Average Case:O(log n)
1.j) How is Union stored in C?..[1]
In C, a union is a data structure that allows different data types to occupy the same memory
space.
union UnionName {
data_type1 member1;
data_type2 member2;
// Other members
};
Memory Allocation: The union allocates enough memory to store the largest member.
Overlapping Memory: All members of the union share the same memory, meaning that the
memory location of the first member is the same as that of the last member. When a value is
assigned to one member, it overwrites the value of the other members.
PART – B
2.a) Write about components of a computer…[5]
The primary components of a computer:
1. Central Processing Unit (CPU): Often called the brain of the computer, the CPU
performs most of the processing inside the computer. It has two main parts: the
control unit (CU), which directs operations, and the arithmetic logic unit (ALU),
which performs mathematical and logical operations.
2. Motherboard: The motherboard is the main circuit board that connects all of the
computer's components.
3. Random Access Memory (RAM): RAM is the computer's short-term memory. It
stores data and instructions that are currently in use or being processed by the CPU.
4. Storage Devices: These are used to store data permanently or semi-permanently.
There are two primary types of storage devices:
o Hard Disk Drives (HDD): Traditional mechanical drives that store data
magnetically.
o Solid-State Drives (SSD): Faster storage devices with no moving parts,
offering quicker data access speeds than HDDs.
5. Power Supply Unit (PSU): The PSU provides electrical power to the computer by
converting electricity from a wall outlet into the appropriate voltage for the
components.
6. Graphics Processing Unit (GPU): The GPU handles rendering of images and
videos. It is especially important for tasks like gaming, video editing, and 3D
rendering.
7. Input Devices: These allow the user to interact with the computer. Common input
devices include:
o Keyboard: Used for typing text and commands.
o Mouse: A pointing device used to navigate the graphical user interface (GUI).
8. Output Devices: These display or present data processed by the computer. Common
output devices include:
o Monitor: Displays the visual output from the computer.
o Printer: Produces physical copies of documents or images.
2. b) Draw the flow chart to calculate Simple Interest…[5]
3.a) What are Syntax and Logical errors? Explain with examples…[4]
Syntax errors occur when the code violates the grammar rules of the programming
language.
Common causes of syntax errors:
Missing punctuation marks (like semicolons, parentheses, etc.).
Incorrect spelling of keywords or function names.
Incorrect use of operators or symbols.
Logical Errors:
Logical errors occur when the code runs without crashing, but it produces incorrect or
unexpected results. These errors don’t prevent the program from running, but they
indicate that something is wrong in the logic or reasoning behind the program.
Common causes of logical errors:
Incorrect formulas or algorithms.
Wrong assumptions made during the development process.
Errors in conditions or loops (e.g., using <= instead of <, or vice versa).
Mismanagement of variables or data types.
3.b) Write a C program to calculate area of a Rectangle..[6]
#include <stdio.h>
int main() {
float length, width, area;
printf("Enter the length of the rectangle: ");
scanf("%f", &length);
printf("Enter the width of the rectangle: ");
scanf("%f", &width);
area = length * width;
printf("The area of the rectangle is: %.2f\n", area);
return 0;
}
4.a) Write the syntax of if-else construct in C…[2]
The if-else construct in C is used to make decisions based on conditions. It executes one
block of code if the condition is true, and another block of code if the condition is false.
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
4. b) What is Dangling else problem in C? How to solve it?..[4]
The dangling else problem in C arises when an else statement is ambiguously associated
with multiple if statements, typically in nested if-else conditions. This happens because C
does not explicitly specify which if an else should belong to when there is more than one if
statement, especially when the if statements are nested.
How to Solve the Dangling Else Problem:
To avoid the dangling else problem, use curly braces {} to explicitly define the scope of each
if-else block. This ensures that each else statement is clearly associated with the intended if.
4. c) What is the need of precedence and associativity of operators in expression
evaluation? Explain with suitable examples…[4]
In programming, precedence and associativity of operators play crucial roles in determining
the order in which operators are evaluated in an expression.
Operator Precedence: It defines the priority or importance of operators when they appear
in an expression. Operators with higher precedence are evaluated before operators with
lower precedence.
Operator Associativity: It determines the order in which operators of the same precedence
are evaluated. Operators can be evaluated either from left to right (left-associative) or right
to left (right-associative).
Example:Operator Precedence
#include <stdio.h>
int main() {
int result = 3 + 5 * 2; // multiplication has higher precedence than addition
printf("Result: %d\n", result); // Outputs 13 (5 * 2 is evaluated first, then 3 + 10)
return 0;
}
Example 1: Left-Associative Operators
#include <stdio.h>
int main() {
int result = 10 - 5 + 3; // Left-associative operators: subtraction and addition
printf("Result: %d\n", result); // Outputs 8 (10 - 5 = 5, then 5 + 3 = 8)
return 0;
}
Example 2: Right-Associative Operators
#include <stdio.h>
int main() {
int result = 10;
result = result = 5; // Right-associative assignment
printf("Result: %d\n", result); // Outputs 5 (rightmost assignment is evaluated first)
return 0;
}
5.a) Write about logical and bit-wise operators…[4]
Logical operators are used to perform logical operations on expressions, typically for
conditional checks or decision-making in a program.
Logical AND (&&)
Logical OR (||)
Logical NOT (!)
Bitwise Operators in C:
Bitwise operators are used to perform operations on individual bits of integer variables.
These operations treat the operands as sequences of bits (0s and 1s) rather than as whole
numbers.
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise NOT (~)
Left Shift (<<)
Right Shift (>>)
5.b) Write a C program to print a pyramid pattern as given below… [6]
1
23
456
7 8 9 10
#include <stdio.h>
int main() {
int rows = 4; // Number of rows in the pyramid
int number = 1; // Starting number for the pattern
for (int i = 1; i<= rows; i++) {
for (int j = 1; j <= i; j++) {
printf("%d ", number); // Print the current number
number++; // Increment the number
}
printf("\n"); // Move to the next line after each row
}
return 0;
}
6.a) Discuss about various types of functions in C…[5]
Type Description Example
Determines if the function returns a value
Return Type int, void
or not
Whether the function accepts parameters
Parameters With or without parameters
or not
Type Description Example
Library Functions Predefined functions in C standard library printf(), scanf()
User-defined Functions created by the programmer for
Custom function definitions
Functions specific tasks
Factorial function, Fibonacci
Recursion Functions that call themselves
sequence
Changes inside function don't
Call by Value Function receives a copy of the argument
affect argument
Function receives the address of the Changes inside function affect
Call by Reference
argument argument
Function Function declaration or prototype informs
int add(int, int);
Declaration compiler about the function
6.b) Write a C program to find second largest number in an array of numbers using
function…[5]
#include <stdio.h>
int findSecondLargest(int arr[], int n);
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i< n; i++) {
scanf("%d", &arr[i]);
}
int secondLargest = findSecondLargest(arr, n);
if (secondLargest != -1) {
printf("The second largest number in the array is: %d\n", secondLargest);
} else {
printf("There is no second largest number in the array.\n");
}
return 0;
}
int findSecondLargest(int arr[], int n) {
int firstLargest, secondLargest;
if (n < 2) {
return -1; // If the array has fewer than 2 elements, there is no second largest number
}
firstLargest = secondLargest = -1; // Assuming non-negative numbers
for (int i = 0; i< n; i++) {
if (arr[i] >firstLargest) {
secondLargest = firstLargest; // Update second largest
firstLargest = arr[i]; // Update largest
} else if (arr[i] >secondLargest&&arr[i] != firstLargest) {
secondLargest = arr[i]; // Update second largest
}
}
return secondLargest; // Return the second largest number
}
7.a) Write about any two string manipulating functions in C...[4]
Here are two common string-manipulating functions in C:
1. strlen() – String Length Function
The strlen() function is used to determine the length of a string (excluding the null
terminator \0). It is declared in the <string.h> header file.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Length of string: %lu\n", strlen(str));
return 0;
}
2. strcpy() – String Copy Function
The strcpy() function copies the contents of one string into another. It is also defined in
<string.h>.
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "C Programming";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
7. b) Write a C program to count number of vowels in a string...[6]
#include <stdio.h>
#include <string.h>
int countVowels(char str[]) {
int count = 0;
char vowels[] = "AEIOUaeiou"; // List of vowels (both uppercase and lowercase)
for (int i = 0; str[i] != '\0'; i++) {
if (strchr(vowels, str[i])) { // Check if the character is a vowel
count++; }
}
return count;
}
int main() {
char str[100]; // String input
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read input including spaces
int vowelCount = countVowels(str);
printf("Number of vowels in the string: %d\n", vowelCount);
return 0;
}
8.a) How to define and call Macros in C? Explain with an example...[5]
In C, macros are defined using the #define preprocessor directive.
Syntax: #define MACRO_NAME replacement_text
#include <stdio.h>
#define PI 3.14159 // Object-like macro
#define SQUARE(x) ((x) * (x)) // Function-like macro
int main() {
double radius = 5.0;
double area = PI * SQUARE(radius); // Using macros
printf("Area of the circle: %.2f\n", area);
return 0;
}
8. b) What are Command-Line arguments? Write its usage in C...[5]
Command-line arguments are inputs given to a C program at the time of execution through
the terminal or command prompt. They allow users to pass parameters without modifying
the code.
Uses of Command-Line Arguments in C
1. Passing Input Without Hardcoding – Allows flexibility in providing input values.
2. File Handling – Used to pass filenames for reading/writing operations.
3. Configuration Options – Programs like compilers (gcc) use them for options (-o, -
Wall).
4. Automating Execution – Useful in scripting and automation.
9.a) What is FILE pointer? Write about fopen() and fclose() functions in C..[5]
A FILE pointer is a special pointer used in C for handling files. It is of type FILE * and helps
in reading, writing, and manipulating files using standard file I/O functions.
FILE *fp;
1. fopen() Function
The fopen() function is used to open a file in different modes (read, write, append, etc.)
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w"); // Opens a file in write mode
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("File opened successfully.\n");
fclose(fp); // Closing the file
return 0;
}
2. fclose() Function
The fclose() function is used to close an open file and free up system resources.
FILE *fp = fopen("example.txt", "r");
if (fp != NULL) {
// File operations here
fclose(fp); // Close the file
}
9. b) Write about calloc() and realloc() functions in C...[5]
In C, dynamic memory allocation is handled using functions from the stdlib.h library. Two
important functions for memory management are calloc() and realloc().
1. calloc() (Contiguous Allocation)
The calloc() function is used to allocate multiple blocks of memory dynamically, initializing all
elements to zero.
Syntax: void *calloc(size_t num, size_t size);
Key Features of calloc()
Allocates multiple memory blocks.
Initializes all elements to zero.
Returns a void * pointer, which needs type casting.
2. realloc() (Reallocate Memory)
The realloc() function is used to resize previously allocated memory (from malloc() or
calloc()) dynamically.
Syntax: void *realloc(void *ptr, size_t new_size);
Key Features of realloc()
Resizes an existing memory block.
Retains old data if possible.
If new size is larger, new memory is uninitialized.
If new size is smaller, extra data is lost.
10.a) What are bit-fields in C? Write its usage in C...[3]
Bit-fields in C are a way to allocate specific numbers of bits to structure members, allowing
memory-efficient storage of small data elements. They are typically used when memory
optimization is crucial, such as in embedded systems, networking, and hardware-related
programming.
struct struct_name {
data_type member_name : number_of_bits;
};
Usage of Bit-Fields in C
1. Memory Optimization
o Saves memory by storing data in fewer bits instead of using full int (typically
4 bytes).
2. Flags and Status Indicators
o Used for on/off (boolean) flags, reducing memory consumption.
3. Hardware Registers Representation
o Useful in embedded systems to represent registers with specific bit layouts.
4. Networking Protocols
o Efficiently stores protocol headers with exact bit-length fields.
10.b) Write a C program to enumerate the colors in the rainbow..[7]
#iclude <stdio.h>
enum RainbowColors {
VIOLET, // 0
INDIGO, // 1
BLUE, // 2
GREEN, // 3
YELLOW, // 4
ORANGE, // 5
RED // 6
};
int main() {
const char *colorNames[] = {"Violet", "Indigo", "Blue", "Green", "Yellow", "Orange",
"Red"};
printf("Colors in the Rainbow:\n");
for (int i = VIOLET; i <= RED; i++) {
printf("%d - %s\n", i, colorNames[i]);
} return 0;
11.a) Apply Bubble sort to sort the data: 45, 69, 83, 74, 32, 14, 25, 55, 99,100..[6]
Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order.
Pass 1: 45, 69, 74, 32, 14, 25, 55, 83, 99, 100
Pass 2: 45, 69, 32, 14, 25, 55, 74, 83, 99, 100
Pass 3: 45, 32, 14, 25, 55, 69, 74, 83, 99, 100
Pass 4: 32, 14, 25, 45, 55, 69, 74, 83, 99, 100
Pass 5: 14, 25, 32, 45, 55, 69, 74, 83, 99, 100
Pass 6: 14, 25, 32, 45, 55, 69, 74, 83, 99, 100
Final Sorted Array: 14, 25, 32, 45, 55, 69, 74, 83, 99, 100
11.b) Write an algorithm to find roots of a quadratic equation...[4]
Algorithm to Find Quadratic Roots
Input: Coefficients a, b, and c.
Output: Roots of the quadratic equation.
1. Start
2. Input values of a, b, and c.
3. Compute the discriminant: D=b 2−4 ac
4. Check the discriminant (D):
If D > 0, compute roots using
x 1=2 a−b+ D , x 2=2 a−b−D
If D = 0, compute the single root
x=2 a−b
If D < 0, compute complex roots
x 1=2 a−b+2 a ∣ D ∣i , x 2=2 a−b−2 a ∣ D ∣i
5. Display the roots.
6. End