Dca1102 - Programming in C
Dca1102 - Programming in C
DCA1102 – PROGRAMMING IN C
ASSIGNMENT QUESTIONS OF SET-1 AND SETS-2 AND THEIR
ANSWERS
(SEMESTER 1)
Flow control statements in C are used to control the sequence of execution of statements
within a program. These statements allow developers to make decisions, repeat actions, and
create structured and organized code. The primary flow control statements in C include:
if Statement
• A code block can be conditionally executed using the if statement. The code inside the
if block is executed once a specific condition is evaluated and found to be true.
#include <stdio.h>
int main() {
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
}
return 0;
}
In this example, the print If statement will only be executed if the condition x > 5 is true.
if-else Statement
• If the condition is false, the if-else statement executes a different piece of code,
extending the functionality of the if statement.
#include <stdio.h>
int main() {
int x = 3;
if (x > 5) {
printf("x is greater than 5\n");
} else {
printf("x is not greater than 5\n");
}
return 0;
}
Here, depending on whether the criterion x > 5 is true or false, the program will print various
messages.
switch Statement
• To choose which of several code blocks will be executed, use the switch statement. It
functions with enumerated or integral types.
#include <stdio.h>
int main() {
int choice = 2;
switch (choice) {
case 1:
printf("Option 1 selected\n");
break;
case 2:
printf("Option 2 selected\n");
break;
case 3:
printf("Option 3 selected\n");
break;
default:
printf("Invalid option\n");
}
return 0;
}
After determining the choice's value, the switch statement runs the related case. To get out of
the switch block, you need to use the break statement.
while Loop
• If a certain condition is true, the while loop repeatedly runs a block of code.
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5) {
printf("Iteration %d\n", count);
count++;
}
return 0;
}
In this case, the while loop publishes the message till the count exceeds five.
These C flow control statements regulate the execution flow according to predefined criteria
and loops, laying the groundwork for building intricate and well-structured programs. It is
necessary to comprehend these statements in order to write understandable and effective C
code.
Q3
Define a function. List and explain the categories of user-defined functions.
A function is a reusable, self-contained chunk of code used in programming that carries out a
single purpose. Programmers can divide a program into smaller, more manageable chunks
with the use of functions, which improves the modularity, readability, and maintainability of
the code. A function is declared in C using the syntax as follows:
return_type function_name(parameters) {
// Function body
// Code to perform a specific task
return value; // Optional return statement
}
Let's dissect a function definition's constituent parts:
Return Type
• This indicates the kind of value that will be returned by the function when it has
finished running. The return type of a function is stated as void if it returns an empty
string.
Function Name
• The function is uniquely identified by this user-defined identifier. The same
guidelines apply to function names as they do to variable names.
Parameters
• Variables called parameters are used to supply values to the function. They serve as
stand-ins for the real values that are supplied when calling the function.
Function Body
• The actual code that the function runs is included in the function body. The curly
brackets encapsulate this code. {}
Return Statement (Optional)
• The function may use the return statement to send a value back to the caller code if it
has a return type other than void.
Let's now talk about the many types of user-defined functions:
Function that is void (has no arguments and no return value)
void greet() {
printf("Hello, World!\n");
}
While it completes a task, this kind of function does not return any value and does not require
any input parameters.
Function having no return value and parameters
• void addNumbers(int a, int b) {
printf("Sum: %d\n", a + b);
}
This function does not return any result; instead, it calculates the sum using two parameters, a
and b.
Function with a return value and arguments
• int multiply(int x, int y) {
return x * y;
}
This kind of function accepts parameters, multiplies x and y, and then outputs the result.
Programmers may create more modular and effective code by knowing and using these
several C user-defined function types. This improves code structure, reusability, and
maintainability.
Q4
Define an array. How to initialize a one-dimensional array? Explain with suitable
examples.
A basic data structure in C is an array, which enables the storing of many items of the same
data type under a single identifier. Arrays are often used in a variety of programming settings
and are crucial for handling data collections, like lists. The most basic type of array, a one-
dimensional array, is made up of components kept in adjacent memory regions. Arrays must
be properly initialized in order for programs to use them effectively.
The syntax to declare a one-dimensional array in C is as follows:
data_type array_name[size];
data_type: Indicates the kind of elements that will be stored in the array.
array_name: The name given to the array as an identifier.
size: The maximum number of items an array can contain.
Setting up initials at declaration time
• int numbers[5] = {1, 2, 3, 4, 5};
Here, the values 1, 2, 3, 4, and 5 are defined and initialized into an array called numbers of
size 5.
Pertial initialization
• int numbers[5] = {1, 2}; // Initializes the first two elements, rest will be 0
Less values than the array's size are automatically initialized to zero for the remaining entries.
Specifying array size
• int numbers[] = {1, 2, 3, 4, 5}; // Compiler infers the size from the number of
elements
In this instance, the number of items supplied in the initialization defines the array's size
automatically.
Using Loop for initialization
• int numbers[5];
for (int i = 0; i < 5; i++) {
numbers[i] = i + 1;
}
Loops may also be used to initialize arrays, which is helpful in cases when the initialization
logic is more intricate.
These examples show the versatility that C offers when working with one-dimensional arrays
by initializing the arrays using a variety of methods. Comprehending array initialization is
essential for efficient data handling and processing in C applications.
Q5
(a) Define Structure and write the general syntax for declaring and accessing
members.
A user-defined data type in C called a structure enables the grouping of variables of various
data kinds under a single name. To declare a structure, use the syntax
• struct structure_name {
data_type member1;
data_type member2;
// ... Additional members
};
Use the dot (.) operator to access structure members after creating an instance of the
structure:
• struct structure_name instance_name;
instance_name.member1 = value1;
instance_name.member2 = value2;
This makes it possible to read or give values to specific structural members. For instance:
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person person1;
strcpy(person1.name, "John Doe");
person1.age = 25;
return 0;
}
In this instance, a structure A person's name and age define them. The dot operator is used to
assign and retrieve values to the newly formed instance person1.
Q5b
List out the difference between structures and unions.
Memory Distribution:
• Structures: Each member's memory is allocated independently, resulting in the total of
their distinct sizes.
Unions: Each member shares a single memory block, the size of which is decided by
the biggest member.
Member Entry:
• Structures: Every member may be accessed separately and has a dedicated storage
area.
Unions: You can only access one member at a time. The values of other members are
impacted when one member's value is altered.
Efficiency of Memory:
• Structures: Because each member is given their own space, they are less memory-
efficient.
Unions: When only one member is required at a time, they are more memory-efficient
because they share memory among their members.
Use Case:
• Structures: Employed when many bits of data must be individually stored and
retrieved.
Unions are useful in situations when many data kinds are stored in the same memory
area and only one type of information is needed at any one moment.
Starting Point:
• Structures: It is possible to initialize each member independently.
Unions: One initialization of a member is permitted at a time.
Calculation Size:
• Structures: Size is the total of each member's sizes.
unions : is determined by the largest member's size.
Grammar:
• Structures: Using the struct keyword, declare them.
Unions: Union keyword declared.
In conclusion, unions share a shared memory block for all members, resulting in more
efficient memory consumption but limiting access to a single member at a time, whereas
structures allocate distinct memory for each member, enabling independent access. Unions
are helpful in situations where diverse data types share memory space, whereas structures are
appropriate when numerous bits of information are required.
Q6
Explain the difference between static memory allocation and dynamic memory
allocation in C. Explain various dynamic memory allocation function in c.
int main() {
int *dynamicArray;
return 0;
}
In this example, memory is created for an integer array of size 5 using malloc(), and it is then
deallocated using free(). Although dynamic memory allocation has many advantages, it must
be carefully managed to prevent memory leaks and other problems. In order to stop memory
leaking, dynamically allocated memory must be released when it is no longer required.