[ASSIGNMENT]
NAME PREMCHAND MENON
ROLL 2314520412
PROGRAM BCA
SEMESTER I
COURSE NAME PROGRAMMING IN C
COURSE CODE DCA1102
(SET 1)
Q1.
The C programming language is a versatile and powerful programming language that has
been widely used for system programming, application development, and more. Dennis
Ritchie introduced the programming language C. Then after this has been a widely utilized
tool for tasks such as developing operating systems, compilers, and databases.
Here are some key features of the C programming language:
1. Procedural Language: C is a procedural programming language, meaning that it
follows a procedural paradigm where a program is divided into functions or
procedures. It emphasizes procedures or routines to structure the program.
2. Mid-Level Programming Language: C is often referred to as a "mid-level" language It
not only contains high-level features functions and structures but also loaded with low
level features like manipulation of memory.
3. Structured Programming: C supports structured programming principles, allowing the
use of functions, blocks, and modular programming. This enhances code readability,
maintainability, and reduces complexity.
4. Efficient and Fast Execution: C is efficient and quickly executable. It allows direct
manipulation of memory addresses and provides low-level access to computer
memory, making it suitable for system-level programming.
5. Portability: C programs are generally portable across different platforms with minimal
changes. The language's design philosophy encourages writing programs that can be
easily adapted to various environments.
6. Extensive Standard Library: A rich standard library is C comes with that provides a
set of functions for common tasks, such as file I/O, string manipulation, memory
allocation, and more. This allows developers to perform many operations without
having to write custom code.
7. Pointer Support: C supports pointers, allowing direct manipulation of memory
addresses. While this feature can be error-prone, it is powerful and provides fine-
grained control over memory allocation and deallocation.
8. Static Type Language: This is a statically typed language. Hence variable types must
be declared before they are used. This helps to identify errors at compile-time.
1
9. Low-Level Manipulation: C allows low-level manipulation of bits and bytes, making
it suitable for tasks such as device driver development and embedded systems
programming.
10. Efficient Memory Management: C provides manual memory management through
functions like malloc and free, giving programmers control over memory allocation
and deallocation.
11. Support for Recursion: C supports recursion, allowing functions to call themselves.
This feature is useful for solving problems that can be naturally expressed using
recursive algorithms.
12. Wide Range of Applications: C has been used in the development of operating
systems, compilers, embedded systems, game development, device drivers, and
various other software applications.
13. Ease of Learning: C's syntax is concise and relatively simple, making it easier for
programmers to learn and understand. This simplicity contributes to the language's
popularity and longevity.
14. Influence on Other Languages: C has influenced many modern programming
languages, including C++, C#, Objective-C, and more. Understanding C provides a
solid foundation for learning other languages.
While C has many powerful features, it also requires careful programming due to its low-
level capabilities, especially concerning memory management. Additionally, C does not
provide some of the abstractions found in higher-level languages, which can make certain
programming tasks more challenging. Despite this, C remains an essential language in the
software development landscape.
Q2.
Flow control statements in C allow you to control the flow of program execution based on
certain conditions or loops. These flow control statements in C provide the necessary tools
for making decisions, iterating over sequences, and controlling the flow of execution within a
program.
Here are the main types of flow control statements in C, along with examples:
if Statement: Usage of if statement is, whenever a set of code needs to be executed
conditionally.
Example:
#include <stdio.h>
int main() {
int x = 10;
if (x > 0) // this code will execute only when x is greater than 0
{
printf("x is positive\n");
}
return 0;
}
2
if-else Statement: The if-else statement is used to execute different blocks of code,
depends on a condition.
Example:
#include <stdio.h>
int main()
{
int t = -5;
if (t > 0)
{ // this code will execute only when t > 0
printf("t is positive\n");
}
else { // this code will execute only when t <= 0
printf("t is non-positive\n");
}
return 0;
}
Nested if Statements: The if statements can be nested inside each other for more complex
conditions.
Example:
#include <stdio.h>
int main()
{
int x = 10;
if (x > 0)
{ // this code will execute only when x > 0
if (x % 2 == 0)
{ // code will execute only when x is > 0 and x mode 2 is 0
printf("x is positive and even\n");
}
else { // code will execute only when x is > 0 and x mode 2 is not 0
printf("x is positive but odd\n");
}
}
else
{ // this code will execute only when x is less or equal to 0
printf("x is non-positive\n");
}
return 0;
}
Switch Statement: The switch statement is used for multi-way branching based on the
value of an expression.
Example:
#include <stdio.h>
int main()
{
int day = 3;
3
switch (day) { // the code will be switched into the cases according to the value in
variable day
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
// ... other cases ...
default:
printf("Invalid day\n");
}
return 0;
}
While Loop: This kind of loop repeats a block of code as long as a given condition is true.
Example :
#include <stdio.h>
int main()
{
int count = 0;
while (count < 5)
{ // this code will be executed 5 times till variable count become 5
printf("Count: %d\n", count);
count++;
}
return 0;
}
Do-while Loop: This kind of loop is similar to while, but it guarantees that the loop body
is executed at least once.
Example:
#include <stdio.h>
int main()
{
int count = 0;
do { // print will be executed once(first time) every execution then it will be
executed only when then while condition is true
printf("Count: %d\n", count);
count++;
} while (count < 5);
return 0;
}
4
For Loop: The for loop provides a compact way to iterate over a range of values.
Example:
#include <stdio.h>
int main()
{
for (int i = 0; i < 5; i++)
{ // this code will be executed 5 times till variable i become 5
printf("i: %d\n", i);
}
return 0;
}
Break Statement: The break statement is used to exit a loop prematurely
Example:
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++)
{ // this code will be quit the for loop when variable i is equal to 5
if (i == 5)
{
break; // exit the loop when i equals 5
}
printf("i: %d\n", i);
}
return 0;
}
Continue Statement: The continue statement is used to skip the rest of the loop's body and
move to the next iteration.
Example:
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
continue; // code will skip even numbers by checking mode of 2 is 0
}
printf("i: %d\n", i);
}
return 0;
}
5
Q3.
In programming, a function is a separate piece of code that is used to carry out a particular
task or set of related task. A user-defined function is a function that is created by a user to
fulfill a particular requirement, as opposed to a built-in function that is defined by the
language or environment that the user is using. Functions are used to organize code, make it
modular, and promote reusability. In many programming languages, including C, C++, Java,
and Python, functions play a fundamental role in structuring code.
Structure of a Function is as follows
Return type function_name(parameters)
{
// Function body
// Statements and logic go here
// Return statement (if applicable)
return value;
}
User-defined functions can be divided into different categories based on the way in which
they are declared and called. The main categories are as follows:
1. Function with No Parameters and No Return Value: This type of function
performs a task without taking any parameters and does not return a value.
Example:
void greet()
{
printf("Hello, world!\n");
}
2. Function with Parameters and No Return Value: This type of function takes
parameters but does not return a value. It performs a task based on the provided
parameters.
Example:
void add(int a, int b)
{
printf("Sum: %d\n", a + b);
}
3. Function with Parameters and Return Value: This type of function takes
parameters and returns a value. It performs a task and provides the result to the calling
code.
Example:
int multiply(int x, int y)
{
return x * y;
}
6
4. Function with No Parameters and Return Value: This type of function does not
take any parameters but returns a value. It generates and returns a result without
relying on external input.
Example:
double getRandomNumber()
{
return rand() % 100 / 100.0;
}
5. Recursive Function: A recursive function is a function that calls itself either directly
or indirectly. Recursive functions are useful for solving problems that can be broken
down into smaller, similar sub-problems.
Example:
int factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else {
return n * factorial(n - 1);
}
}
6. Variadic Function (Function with Variable Number of Arguments): A variadic
function is a function that accepts a variable number of arguments. The stdarg.h
library is often used to handle variable arguments.
Example:
#include <stdarg.h>
double average(int count, ...) {
va_list args;
va_start(args, count);
double sum = 0;
for (int i = 0; i < count; i++) {
sum += va_arg(args, double);
}
va_end(args);
return sum / count;
}
7
(SET 2)
Q4.
An array is a collection of elements of the same data types. It is stored in contiguous memory
locations. Every element in an array can be easily identified by an index or a subscript, and
the index starts from 0.
The general syntax to declare an array is like:
data_type array_name[size];
Following is the explanation of each parameter in the above syntax
data_type: The data type of the elements in the array.
array_name: The name given to the array.
size: The number of elements in the array.
Example : int numbers[5]
To initializing an integer array with five elements, the user can declare it as
int numbers[5] = {10, 20, 30, 40, 50};
This creates an array named “numbers” which can hold five integers. The elements index
range from 0 to 4, with corresponding values 10, 20, 30, 40, and 50 respectively.
Similarly to initializing an character array with five elements, the user can declare it as
char vowels[] = {'A', 'E', 'I', 'O', 'U'};
In this case, the array size is determined automatically by the number of values in the list.
Arrays can also be initialized using loops, allowing dynamic or condition-based assignment.
For example:
int evenno [5];
int i, n = 0;
for (i = 0; i < 5; i++)
{
evenno [i] =( i+1)*2;
}
This loop initializes an array “evenno” with 5 integers, assigning values 2 to 10 to respective
array elements.
To access array elements, use the array name and the element's index in square brackets:
printf("%d\n", numbers [0]); // Prints the first element of the numbers array
printf("%c\n", vowels[2]); // Prints the third element of the vowels array
printf("%d\n", evenno [4]); // Prints the last element of the evenno array
8
Q5.
a) A structure is a user-defined data type that allows to group together variables of
different data types under a single name. Each variable in the structure is called a
member or field. Structures prove valuable for organizing intricate data and
representing real-world entities. Here's the general syntax for declaring and
accessing members of a structure:
struct structure_name {
data_type member1;
data_type member2;
:
:
data_type membern;
};
In the above syntax struct indicates the declaration of a structure, structure_name is
the name given to the structure and data_type is the data_type of each member. Each
member can have different datatypes.
Syntax for declaring a variable of the structure is struct structure_name
variable_name;
In the above syntax structure_name indicates the name of a structure and
variable_name is the name given to the variable of the structure.
Syntax for accessing members of a structure is variable_name.member1 = value1;
In the above syntax variable_name is the name given to the variable of the structure
and member1 is the names of the members within the structure.
Example:
#include <stdio.h>
// Defining a structure named 'Person'
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declaring a variable 'person1' of type 'Person'
struct Person person1;
// Accessing and assigning values to the members of 'person1'
strcpy([Link], "John");
[Link] = 25;
9
[Link] = 5.9;
// Displaying the values of the members
printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);
printf("Height: %.2f\n", [Link]);
return 0;
}
In this example, a structure named Person is defined with three members: name (an
array of characters), age (an integer), and height (a floating-point number). An
instance of this structure, person1, is declared in the main function, and values are
assigned to its members. The program then prints out the values of the structure
members.
b) The structure is an user-defined data type declared using struct keyword. It is used
to combine items of different types into one type. In C, the struct keyword defines
the structure. The members of the structure are referred to as its members. The
members can be any valid data types.
Union is also an user-defined data type but declared using union keyword. A union
is a set of variables from different data types in a single memory location. A union
can be defined with multiple members, but only one member is allowed to contain
a value at a time.
Structures and Unions are used to group different data types however they have
distinct differences in terms of memory allocation, usage, and behavior.
Here are the key differences between structures and unions:
Parameter Structure Union
Allocates separate memory Shares the same memory
for each member. location for all members.
Memory Total memory size is the Total memory size is
Allocation sum of the sizes of all determined by the largest
members. member
Usage Used when multiple pieces Used when different data
of data need to be stored members share the same
memory location
Each member of the Only one member of the
structure holds a different union can be active at a time
piece of information
Memory Less memory efficient as More memory efficient as
Efficiency each member has its own members share the same
memory space memory space
Member Access Members are accessed Only one member is active at
individually a time
10
Members can be accessed Accessing one member may
simultaneously without overwrite the values of other
affecting each other members
Initialization Each member can be Only the first member is
initialized independently initialized
Size Size is the sum of the sizes Size is the size of the largest
of its members member
Syntax struct MyStruct union MyUnion
{ {
int member1; int member1;
char member2; char member2;
float member3; float member3;
}; }
Use Cases Suitable for situations Useful when different types
where each member of data are related, and only
represents a distinct piece one type is active at a given
of data time (e.g., a variant)
Default Member No default initialization; The first member is
Initialization each member must be implicitly initialized if no
explicitly initialized explicit initialization is
provided
Q6.
Static memory allocation and dynamic memory allocation are two approaches to managing
memory in C, and they differ in how memory is allocated and deallocated during the
program's execution.
Static Memory Allocation: Allocation at Compile Time: In static memory allocation,
memory for variables is allocated at compile time. This means that the compiler
determines the memory requirements of the program before it is executed.
o Fixed Size: The size of the allocated memory is fixed and cannot be changed during
runtime. The amount of memory needed must be known at the time of compilation.
o Variables and Arrays: Variables declared with keywords like int, float, or arrays with
a fixed size are examples of statically allocated memory.
o Lifetime: The memory allocated statically exists throughout the entire execution of
the program.
Example
int main() {
int staticArray[10]; // Statically allocated array
int staticVar = 5; // Statically allocated variable
// ...
return 0;
}
11
Dynamic Memory Allocation: Allocation at Runtime: Dynamic memory allocation
involves allocating memory during the program's execution, at runtime, using functions
like malloc(), calloc(), or realloc().
o Variable Size: The size of dynamically allocated memory can be determined during
runtime, allowing for flexibility in managing memory based on program
requirements.
o Heap Memory: Dynamic memory is typically allocated on the heap, and it must be
explicitly managed by the programmer.
o Lifetime: Dynamically allocated memory exists until it is explicitly deallocated by the
programmer using functions like free(). The programmer has more control over the
memory's lifecycle.
Example
int main() {
int *dynamicArray;
dynamicArray = (int*)malloc(10 * sizeof(int)); // Dynamically allocated array
// ...
free(dynamicArray); // Deallocate the dynamically allocated memory
return 0;
}
In summary, the key difference is that static memory allocation occurs at compile time, with a
fixed size and a fixed lifetime, while dynamic memory allocation happens at runtime,
allowing for flexibility in size and lifetime but requiring explicit management by the
programmer.
Dynamic memory allocation is achieved through a set of functions provided by the standard
library, namely malloc(), calloc(), realloc(), and free(). These functions allow programmers to
allocate memory on the heap during runtime.
Following are the functions:
The relevant library functions for dynamic memory allocation in C are defined in the
‘<stdlib.h>’ header file:
malloc (size) (Memory Allocation):
Prototype: void* malloc(size_t size);
Purpose: Allocates a specified number of bytes of memory on the heap.
Return Value: Returns a pointer to the beginning of the allocated memory block.
Example: int *dynamicArray = (int*)malloc(10 * sizeof(int));
calloc (n, size) (Contiguous Allocation):
Prototype: void* calloc(size_t num, size_t size);
Purpose: Allocates a block of memory for an array of elements, each with a specified
size. The memory is initialized to zero.
12
Return Value: Returns a pointer to the beginning of the allocated memory block.
Example: int *dynamicArray = (int*)calloc(10, sizeof(int));
realloc (ptr, size) (Reallocate Memory):
Prototype: void* realloc(void* ptr, size_t size);
Purpose: Changes the size of the previously allocated memory block pointed to by ptr.
It can be used to expand or shrink the memory block.
Return Value: Returns a pointer to the beginning of the reallocated memory block. If
the size is reduced, the excess memory is freed.
Example: dynamicArray = (int*)realloc(dynamicArray, 20 * sizeof(int));
free (ptr) (Free Memory):
Prototype: void free(void* ptr);
Purpose: Deallocates the memory block previously allocated by malloc, calloc, or
realloc.
Example: free(dynamicArray); dynamicArray = NULL; // Optional, to avoid using
the freed memory
13