[go: up one dir, main page]

0% found this document useful (0 votes)
47 views12 pages

Dca1102 - Programming in C

if you are a beginner at C programming language, this is for you

Uploaded by

kadiatoumuj
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)
47 views12 pages

Dca1102 - Programming in C

if you are a beginner at C programming language, this is for you

Uploaded by

kadiatoumuj
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/ 12

MANIPAL UNIVERSITY JAIPUR

DCA1102 – PROGRAMMING IN C
ASSIGNMENT QUESTIONS OF SET-1 AND SETS-2 AND THEIR
ANSWERS
(SEMESTER 1)

ABDULAI IDRISSA KAMARA


Roll Number : 2314516672
Q1
Describe various features of the C programming language.
Having been in widespread use for more than 40 years, the C programming language is
strong and adaptable. C, which Dennis Ritchie created at Bell Laboratories in the early 1970s,
is still a key language in computer science and has impacted a lot of other programming
languages. The C programming language has the following features:
Programming Language
• C is a procedural language, meaning that program design is done from the top down.
It enables the breakdown of an issue into more manageable modules or functions,
which facilitates code comprehension, upkeep, and debugging.
Structured Programming
• C provides support for structured programming by utilizing blocks and functions.
Programs are arranged into functions, each of which has a distinct function,
encouraging the modularity and reuse of code.
Mid-Level Language
• C is sometimes referred to be a mid-level language since it can be used for both
system-level programming and application development because it combines low-
level capabilities like direct memory manipulation with high-level abstractions.
Portability
• Programs written in C are very portable, which allows them to run with little to no
changes on several systems. Standard libraries are used to provide this portability, and
compilers for different platforms are readily available.
Efficiency
• The performance and efficiency of C are well-known. Because it offers low-level
memory access, programmers may optimize programs for both performance and size.
Because of this, it may be used to design embedded systems, system software, and
other applications that require high performance.
Static Typing
• The data types of variables in C are known at compile time since the language is
statically typed. Better error checking and compiler optimization are made possible as
a result. But it also needs declarations of specified types.
Rich Standard Library
• C includes an extensive collection of standard libraries that include functions for a
wide range of tasks, including memory allocation, input/output, text manipulation,
and mathematical calculations. These libraries improve the portability of the language
and make typical programming jobs easier.
Pointers and Memory Management
• C provides pointers for direct memory management. Although this feature is efficient
and flexible, it also increases the risk of problems such as segmentation faults. C uses
manual memory management, with dynamic memory allocation and deallocation
handled by methods like free( ) and malloc( ).
Bitwise Operations
• C is capable of bitwise operations, which let you work with individual bits inside of
variables. This is especially helpful for low-level data processing jobs and systems
programming.
Preprocessor Directives
• Conditional compilation, header files, and macro definitions are all permitted by the
C preprocessor. This gives you a means to group code together, make it easier to
understand, and utilize macros to create code that can be reused.
Community and Legacy
• There is a sizable and vibrant C development community. Many operating systems
are implemented in C, such as Linux and Unix. C's continued relevance and appeal
are also attributed to the large number of libraries and applications that are created in
the language.
To sum up, the C programming language provides a strong and adaptable software
development environment with characteristics that support a variety of uses, from high-level
application development to system programming. Its broad feature set, portability, and
performance have made it a fundamental language in computer science.
Q2
Explain various flow control statements in C with examples.

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;

printf("Name: %s\n", person1.name);


printf("Age: %d\n", person1.age);

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.

Memory Allocation for Static Data:


• In C, static memory allocation refers to the process of allocating memory for variables
either at the compile stage or prior to the program's execution. Static memory
allocation involves reserving memory for the length of the application, with the size
and type known at build time. Declaring arrays and static variables is the most
popular way to employ static memory allocation.
For example
• int staticArray[10]; // Static allocation of an integer array
static int staticVariable = 5; // Static allocation of an integer variable
Static memory allocation has several limits in terms of flexibility and adaptation, but its
major benefits are speed and simplicity.

Dynamic Memory Allocation:


• In contrast, dynamic memory allocation takes place while the application is running
or executing. It offers increased flexibility and adaptability by enabling memory to be
allocated and deallocated as needed. When memory needs to be allocated and released
dynamically during program execution, or when the size of data structures is
uncertain at compile time, dynamic memory allocation is very helpful.
The stdlib.h library's malloc(), calloc(), realloc(), and free() methods are used in C to allocate
memory dynamically.
Dynamic Memory Allocation Example
#include <stdio.h>
#include <stdlib.h>

int main() {
int *dynamicArray;

// Allocate memory for an integer array of size 5


dynamicArray = (int *)malloc(5 * sizeof(int));

// Check if memory allocation is successful


if (dynamicArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}

// Initialize the array


for (int i = 0; i < 5; i++) {
dynamicArray[i] = i * 2;
}

// Print the values


for (int i = 0; i < 5; i++) {
printf("%d ", dynamicArray[i]);
}

// Deallocate the memory


free(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.

You might also like