Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

NAME SIDDHARTH PAL

SESSION AUGUST 2023


PROGRAM BCA
SEMESTER I
COURSE CODE & NAME DCA1102_PROGRAMMING IN C

Question 1- Describe various features of the C programming language.

Answer 1-
The C programming language is a popular & adaptable language that is valued for its strength
and simplicity. Dennis Ritchie created it at Bell Labs in the early 1970s.

The following are some of the C programming language's characteristics:

1. High-Level Language: C is known as a high-level programming language as it offers


layers that let you create programs without having to know the specifics of the hardware.
As a result, C is easier to understand and use than low-level languages like assembly.

2. Efficient: When it comes to memory use and execution speed, C is renowned for being
efficient. It enables direct memory access and low-level data manipulation, both of which
are essential for creating effective algorithms and systems.

3. Extendable: C functions and libraries provide modularity and extension. By building and
utilizing function libraries, you may increase the usefulness of your programs. Because of
this, reusing code and expanding on current solutions is simple.

4. Modular: Modular programming, which divides a program into more manageable,


smaller modules or functions, is supported by C. This encourages maintainability,
reusability, and structure of the code.

5. Concise: C is sometimes seen as succinct when contrasted to lower-level languages like


assembly, but not being as expressive and high-level as certain contemporary
programming languages. Because of its relatively simple syntax, algorithms may be
expressed effectively.

6. Portable: In general, C code is universal convertible. A C program can be written,


compiled, and executed with little to no changes on a variety of platforms. The
availability of compilers on several systems makes this portability easier.

7. Rich Library: A vast array of functions for input/output, memory management, and
other tasks are included in the extensive standard library of C. To improve the
functionality of their programs, developers can additionally build and use custom
libraries.

C may be a highly favored programming language for different program advancement


projects,, due to it combination of low-level capabilities. However, the control of C
requires developers to manual memory administration and follow cautious programming
practices.

Question 2- Explain various flow control statements in C with examples.

Answer 2-
In C, statements can be executed in a program's order of choice using flow control statements.
They consist of loops and conditional statements, which let you decide what to do and how often
to run specific code blocks.
The following provides an explanation and examples of basic flow control statements in C:
a. if Statement
b. if-else Statement
c. Nested if Statement
d. if-else-if
e. switch statement
f. Conditional Operator
g. Jump Statements:
● break
● continue
● return

if Statement:
If a certain condition is true, a block of code is executed using the if statement.
For eg
Write a code to get entered number is positive, negative or 0 :-

#include <stdio.h>
int main() {
int number;

printf("Enter a number: ");


scanf("%d", &number);
if (number > 0)
{ printf("The number is positive.\n");
}
if (number < 0)
{ printf("The number is negative.\n");
}
if (number == 0)
{ printf("The number is zero.\n");
}
return 0;}

if-else Statement:

The if-else statement is used to execute one block of code if a condition is true and another block
if it's false. Two blocks make up the if-else statement:
one for the false expression and one for the true expression.
For eg-
#include <stdio.h>
int main()
{
int num = 3;
if (num > 5)
{ printf("num is greater than 5\n");
} else
{ printf("num is not greater than 5\n");
}
return 0;
}

Nested if Statement:

You may put one or more if statements within another if statement in C thanks to nested if
statements. Using this, more intricate decision structures may be made.
For eg-
Write a code to get age and gender, if age is greater or equal to 18 users get a message “You are
eligible for adult privileges” , if gender is male then “Welcome, sir!”, if female “Welcome,
ma'am!” and if age is less than 18 the user gets a message “You are not yet eligible for adult
privileges”.

#include <stdio.h>

int main() {
int age;
char gender;

printf("Enter your age: ");


scanf("%d", &age);
printf("Enter your gender (M/F): ");
scanf(" %c", &gender);
if (age >= 18) {
printf("You are eligible for adult privileges.\n");

if (gender == 'M' || gender == 'm') {


printf("Welcome, sir!\n");
} else if (gender == 'F' || gender == 'f') {
printf("Welcome, ma'am!\n");
} else {
printf("Welcome!\n");
}
} else {
printf("You are not yet eligible for adult privileges.\n");
}
return 0;
}

if-else-if :

With this framework, one can deal with various situations.


For eg- write a code to know which day of week it is :-
#include <stdio.h>
int main()
{int day;

printf("Enter a number (1-7) to determine the day of the week: ");


scanf("%d", &day);

if (day == 1) {
printf("Monday\n");
} else if (day == 2) {
printf("Tuesday\n");
} else if (day == 3) {
printf("Wednesday\n");
} else if (day == 4) {
printf("Thursday\n");
} else if (day == 5) {
printf("Friday\n");
} else if (day == 6) {
printf("Saturday\n");
} else if (day == 7) {
printf("Sunday\n");
} else {
printf("Invalid input. Please enter a number between 1 and 7.\n");
}
return 0;
}

switch statement:
Alternative to the if else if, which contains cases that will run based on value of switch
For eg- give user 3 choices and print “You selected Option n”

#include <stdio.h>
int main()
{
int choice;
printf("Enter a number (1-3) to choose an option: ");
scanf("%d", &choice);
switch (choice) {
case 1: printf("You selected Option 1.\n"); break;
case 2: printf("You selected Option 2.\n"); break;
case 3: printf("You selected Option 3.\n"); break;
default: printf("Invalid choice.\n"); break;
}
return 0;
}

Conditional Operator:
Also known as the ternary operator,
For eg- write a code to determine if a number is even or odd:

#include <stdio.h>
int main()
{
int number;
printf("Enter a number: ");
scanf("%d", &number);
(number % 2 == 0) ? printf("Even\n") : printf("Odd\n");
return 0;
}

break:
The break statement is used to exit a loop at the time when a specific condition is met.
To end a loop early, apply the break statement.
'Switch' statements are frequently used it to end the switch block.

continue:
To go on to the following iteration and bypass the rest of the loop body, use the 'continue'
command.
return:
To end a function and return a value to the caller, use the return statement.

Question 3- Define a function. List and explain the categories of user-defined functions.
Answer 3- (a) Computer programs have the ability to ask other programs, or "functions," to
complete tasks on the program's behalf.
The details of the function's execution aren't required to be recognized by the rest of the program.
This may simplify the rest of the program's concepts.
A function is designe to categorize specific areas of the program, and its code is specifically
designed to have useful features.
It completes a few specific tasks that are helpful to other software components. We can
potentially able to reuse it rather than having to rewrite it.

(b) User-defined functions categorized into four categories based on the values they return and
the arguments they accept:
1. Function with no arguments and no return value : Functions that have no arguments
and no return values. Such functions can either be used to display information or to
perform any task on global variables.
2. Function with no arguments and a return value: Functions that have no arguments but
have some return values. Such functions are used to perform specific operations and
return their value.
3. Function with arguments and no return value: Functions that have arguments but no
return values. Such functions are used to display or perform some operations on given
arguments.
4. Function with arguments and with return value: Functions that have arguments and
some return value. These functions are used to perform specific operations on the given
arguments and return their values to the user.

Question 4- Define an array. How to initialize a one-dimensional array? Explain with suitable
examples.
Answer 4- (a) In C, an array is a group of elements kept in consecutive memory regions that are
all of the same data type. By using its index or subscript, each element in the array is distinct.
Working with a collection of linked data gets easier with the help of arrays. It may be used to
hold a collection of user-defined and derived data types, such pointers and structures, as well as
primitive data types like char, float, and int.

(b) To initialize a one-dimensional array in C, following syntax can be used:


datatype arrayName[size] = {value1, value2, ..., valueN};
● An example of initializing and printing a C one-dimensional array's elements is as
follows:

#include <stdio.h>
int main() {
// Initializing an array of integers
int numbers[] = { 1, 2, 3, 4, 5};
// Finding and printing the sum of array elements
int sum = 0;
// Loop to calculate the sum
int i;
for (i = 0; i < 5; ++i) {
sum += numbers[i]; } // Printing the array elements and their sum
printf("Array: ");
// Loop to print the array elements
for (i = 0; i < 5; ++i) {
printf("%d ", numbers[i]); }
printf("\nSum: %d\n", sum);
return 0;}

Output will be - Array: 1 2 3 4 5


Sum: 15

Question 5- (A) Define Structure and write the general syntax for declaring and accessing
members. (B) List out the differences between unions and structures.
Answer 5-
(A) Structure:
Structure is a composite data type in C programming that enables you to combine variables of
several data types under one name. It's a method for grouping relevant data.
-Eg:
#include
// Define a structure named 'Person'
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declare a structure variable 'person1'
struct Person person1;
// Access and assign values to structure members
strcpy(person1.name, "Siddharth");
person1.age = 25;
person1.height = 5.9;
// Display the information
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f feet\n", person1.height);
return 0;}

Output will be- Name: Siddharth


Age: 25
Height: 5.9 feet

(B) The distinctions between structures and unions

Allocation of Memory:

Every component of a structure has a memory space of its own, and the total memory used by
the structure is the sum of the memory needs of all the components.
Every member of a union shares the same amount of memory, and the size of the union is
dictated by the largest member's size.

Access for Members:


Each member of a structure can be accessed separately.
You can only access one member at a time in a union.

Memory Overlap:
Member memory overlap is not permitted in structures.
Unions allow memory overlap between members, as they share the same memory space.

Sizes:
An structure's dimensions are the minimum of all of its member parts' sizes.
A union's size is determined by the size of its largest member.

Usage:
: When you wish to put similar data elements in one group, you utilize structures.
Unions are useful for memory saving because they allow various factors to share the same
amount of memory.

Initialization:
A structure's members can be initialized independently of one another.
Initialization is limited to a union's first member.

Question 6- Explain the difference between static memory allocation and dynamic memory
allocation in C. Explain various dynamic memory allocation function in c.
Answer 6- Static Memory Allocation:
Static memory allocation refers to the allocation of memory at compile-time. The amount of
memory needed is predetermined when the software is written and doesn't change while it runs.
Static memory allocation in C is usually accomplished with fixed-size data structures or arrays.

int main() {
int staticArray[5]; // Static memory allocation for an array
// ... rest of the code
return 0;
}
Dynamic Memory Allocation:
Dynamic memory allocation refers the allocation of memory at runtime.
application execution can decide the extent of memory needs, providing flexibility in memory
management according to the requirements of the application. In C, methods like malloc, calloc,
realloc, and free from the stdlib.h library are used to allocate memory dynamically.

malloc (Memory Allocation):


void* malloc(size_t size);
allocates a block of memory with the given size in bytes.
gives back a pointeer to the memory's initial allocation.

For example: int* dynamicArray = (int*)malloc(5 * sizeof(int));

calloc (Contiguous Allocation):


void* calloc(size_t elementSize, size_t numElements);
this allocates a memory block for an array of size elementSize elements, each of numElements
sets each element's initial value to zero.
gives back a pointerto the memory's initial allocation.

For example: int* dynamicArray = (int*)calloc(5, sizeof(int));

realloc (Reallocate Memory):


The realloc function (void* realloc(void* ptr, size_t newSize); modifies the size of the memory
block that was previously allocated and referred to by ptr to newSize.
gives back an pointer to the reallocated memory's starting location.

For example: dynamicArray = (int*)realloc(dynamicArray, 10 * sizeof(int));

free (Free Memory):


void free(void* ptr);
Releases the memory block that ptr points to, allowing it to be allocated again.

For example: free(dynamicArray);

You might also like