0% found this document useful (0 votes)
20 views

DCA6110 Basic Structure of a C Program

The document provides an overview of fundamental concepts in C programming, including the basic structure of a C program, decision control statements, storage classes, and the differences between call by value and call by reference. It explains the significance of pointers in memory management and includes examples of code to illustrate these concepts. The document emphasizes the importance of understanding these elements for writing efficient and maintainable C programs.

Uploaded by

rohit20021004
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)
20 views

DCA6110 Basic Structure of a C Program

The document provides an overview of fundamental concepts in C programming, including the basic structure of a C program, decision control statements, storage classes, and the differences between call by value and call by reference. It explains the significance of pointers in memory management and includes examples of code to illustrate these concepts. The document emphasizes the importance of understanding these elements for writing efficient and maintainable C programs.

Uploaded by

rohit20021004
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/ 18

INTERNAL ASSIGNMENT

NAME VIVEK KUMAR


SESSION NOVEMBER 2024
ROLL NO 2414504937
PROGRAM MASTER OF COMPUTER APPLICATIONS (MCA)
SEMESTER I
COURSE CODE & NAME DCA6110

1. Answer
Basic Structure of a C Program

C is a robust programming language extensively utilized for system programming, application


development, and embedded systems. Each C program adheres to a specific structure that promotes
readability, efficiency, and maintainability. The fundamental components of a C program include:

Preprocessor Directives
Preprocessor directives begin with the '#' symbol and are processed prior to compilation. These
directives commonly involve including header files (such as `#include <stdio.h>` or include
<math.h>`) and defining macros (using `#define`).

Main Function
Every C program must include the `main()` function, which acts as the starting point for execution.
The operation of the entire program initiates from this specific function.

Variable Declaration
Before utilizing any variables within a program, they must be declared. Variables can store various
data types including integers (`int`), floating-point numbers (`float`), and characters (`char`).

Body of the Program (Statements & Logic)


This section comprises instructions written in C, encompassing constructs such as loops (`for`,
`while`), conditional statements (`if-else`), and function invocations that delineate the program's
logic.

Functions
Functions facilitate breaking down a larger program into smaller, more manageable sections. A
function may either be predefined (e.g., `printf()`, `scanf()`) or user-defined, thereby promoting code
reusability.

Return Statement
When the `main()` function has an explicit return type (typically defined as `int`), it should return a
value—commonly using `return 0;`. This notation indicates successful completion of the program.
Example of a Simple C Program
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}

In this example:
• #include <stdio.h> is a preprocessor directive that includes the standard input-output
library.
• main() is the starting point of execution.
• printf("Hello, World!\n"); prints text on the screen.
• return 0; indicates successful program termination.

scanf() Function in C
The scanf() function is used to take user input in a C program. It reads formatted data from
standard input (usually the keyboard). The function is declared in the stdio.h library and follows a
specific syntax:
Syntax of scanf()
c
CopyEdit
scanf("format specifier", &variable);
• The format specifier defines the type of data to be read (%d for integers, %f for floating-
point numbers, %c for characters, etc.).
• The ampersand (&) is used before variable names to pass their memory addresses to
scanf().
Example Using scanf()

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

printf("Enter your age: ");


scanf("%d", &age);

printf("You are %d years old.\n", age);


return 0;
}

Explanation of the Code:


The program declares an integer variable known as age.
It prompts the user for their age by using printf().
scanf("%d", &age); reads an integer input value and stores it in age.
The value that has been entered is then shown using printf().
Other important points about scanf():
It stops reading as soon as a white-space is met (space, newline).
The operator & (the address operator) is needed before any variable except strings.
Multiple values can be read at once if multiple format specifiers are used.

2. Answer
Decision Control Statements in C
Control statements are those statements of a programming language that allow a program to
choose between two or more paths of execution based on the evaluation of certain conditions.
Thus, they help in controlling the flow of execution of the code by allowing for conditional
branching, as opposed to executing all the statements in a sequential way. Decision control
statements first evaluate the conditions and directly execute the corresponding specific block of
code when the conditions are satisfied.

Types of Decision Control Statements in C


C offers a variety of types of decision control statements:

1. The if Statement
The simplest form of decision construction is used in the if statement. It checks a condition, and
when true, executes a block of code; when false, it skips the if block and moves on to the next
statement.

Syntax:
if (condition) {
// Code executes if condition is true
}

Example:
#include <stdio.h>

int main() {
int num = 5;

if (num > 0) {
printf("The number is positive.\n");
}

return 0;
}
2. The if-else statement provides two possible execution paths. If the condition is true, one block
of code runs; otherwise, another block run.
Syntax:
if (condition) {
// Code executes if condition is true
} else {
// Code executes if condition is false
}

Example:
#include <stdio.h>

int main() {
int num = -3;

if (num > 0) {
printf("Positive number.\n");
} else {
printf("Negative number.\n");
}

return 0;
}

3. If-Else-If Ladder
The if-else-if structure is used when there are multiple conditions to be checked one after the
other. If one of the conditions is true, the corresponding block executes and skipping all of the
remaining conditions.
Syntax:
if (condition1) {
// Code executes if condition1 is true
} else if (condition2) {
// Code executes if condition2 is true
} else {
// Code executes if none of the conditions are true
}

Example:
#include <stdio.h>

int main() {
int marks = 85;
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else {
printf("Grade: C\n");
}

return 0;
}

4. Nested if Statement

A nested if statement is simply an if statement inside of a separate if statement. This type of


structure allows us code a manner in which we can check for one or more conditions.

Syntax:
if (condition1) {
if (condition2) {
// Code executes if both conditions are true
}
}

Example:
#include <stdio.h>

int main() {
int num = 10;

if (num > 0) {
if (num % 2 == 0) {
printf("Positive even number.\n");
}
}

return 0;
}

5. switch Statement
The switch statement is used when a variable needs to be compared with multiple fixed values. It
executes the block corresponding to the matching value. If no match is found, the default case
executes.
Syntax:
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no match found
}

Example:
#include <stdio.h>

int main() {
int day = 3;

switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
default: printf("Invalid day\n");
}

return 0;
}

Key Differences Between if-else and switch Statements


Feature if-else switch
Condition Type Works with expressions Works with fixed values
Performance Slower in some cases Faster for large cases
Readability Less readable for many conditions More structured for multiple cases

Conclusion:
Decision control statements in C are very important for handling conditional logic. By using these
numerous types of decision statements like if, if-else, if-else-if, and switch, this is efficiently
accomplished. Knowing these control structures will help the programmer in writing flexible and
dynamic programs.
3. Answer
The purpose of storage kinds in C:
These necessities in C programming conformity as declared storages for defining and confirming
variable scalars, lifetimes, discernibilities, and their initial values. It adds to memory management
by defining every kind of memory variable and its retrieval in the course of program execution.

The main objectives of storage classes are:

Memory management criteria


Carrying out scope- is a variable accessible inside a function or outside.
Lifetime of memory- is how long the concerned variable will hold that particular value.
Default initialization of a variable where explicit initialization is missing.
There are four major types of storage classes server in the C programming language.

Types of storage classes in C:


1. The Local Storage Class (auto)
Area: Local to the function in which it is declared.
Life: Exists while the function executes.
Memory: Placed in stack memory.
Value: Any garbage value.
Keyword: auto (optional because all local variables are automatic by default).
Example:
#include <stdio.h>

void display() {
auto int num = 10; // Local variable (auto is optional)
printf("Auto Variable: %d\n", num);
}

int main() {
display();
return 0;
}

Description: The variable num is created at the instant the display() function is called and destroyed
at the end of its execution.
1. External Storage Class (Extern)
Scope: Global (across the custom files).
Lifetime: Exists through the life of the program.
Memory: Stored in the data segments.
Default Value: Zero.
Keyword: Extern.
Example:
#include <stdio.h>

extern int num; // Declaration (defined in another file or below)

int main() {
printf("Extern Variable: %d\n", num);
return 0;
}

int num = 50; // Definition of extern variable

In essence, extern defines that num is created elsewhere. It helps in making the external variables
shareable across multiple files.

3. The Static Storage Class (static).


Scope:
If it is declared inside the function, its scope is only this function.
If it is declared outside the function, it is limited to this file.
Lifetime: The lifetime is throughout the execution of the program.
Memory: Located in the data segment.
Default Value: Zero.
Keywords: static.
Example:
#include <stdio.h>

void counter() {
static int count = 0; // Static variable retains value between function calls
count++;
printf("Count: %d\n", count);
}

int main() {
counter();
counter();
counter();
return 0;
}

Output:
Count: 1
Count: 2
Count: 3
4. Register Storage Class: register
Scope: Local to the function in which the register is declared.
Lifetime: Exists and is active only while the executing function is in action.
Memory: It is stored in the CPU registers (only if available).
Default Value: Garbage, if not initialized.
Keywords: register.
Usage: Used for declaring frequently used variables in order to enhance performance.
Example:
#include <stdio.h>

int main() {
register int num = 5; // Hints the compiler to store in a CPU register
printf("Register Variable: %d\n", num);
return 0;
}

Comparison of Storage Classes


Storage Class Scope Lifetime Default Value Memory Location
auto Local Function execution Garbage Stack
extern Global Entire program Zero Data Segment
static Local or File Entire program Zero Data Segment
register Local Function execution Garbage CPU Register (if available)

Conclusion:
Storage classes in C have acquired great significance in variable declaration and memory
management. Automatic variables hold temporary values, external variables give global
accessibility, static variables provide persistent values, and register variables are optimized for
speed. Knowledge of storage classes will lend to proper design of a program.

4. Answer
Differences between Call by Value and Call by Reference in C
C programming allows function calls through two different methods called Call by Value and Call
by Reference. Which method is used depends on how arguments are passed to a function and
changes to variables inside the function.

1. Call by Value
In Call by Value, the value from the actual parameter is copied into a temporary parameter variable.
Modifications do not reflect on the original value.
The original variable is unaffected, inasmuch as the actual operations are performed on the copy
only.
Example of Call by Value
#include <stdio.h>

void changeValue(int num) {


num = 20; // Modifying local copy
printf("Inside function: %d\n", num);
}

int main() {
int a = 10;
printf("Before function call: %d\n", a);
changeValue(a);
printf("After function call: %d\n", a);
return 0;
}

Output:
Before function call: 10
Inside function: 20
After function call: 10
The content of this program explains that the function changeValue() may change num, but since it
is a copy, a remains itself unchanged.

2. Call By Reference
In Call By Reference, a function actually gets the address of the actual parameter.
Any modification carried out on the parameter inside the function modifies the actual variable.
Pointer is used to access and modify the actual data.
Example of Call by Reference
Example of Call by Reference
#include <stdio.h>

void changeValue(int *num) {


*num = 20; // Modifying original value using pointer
}

int main() {
int a = 10;
printf("Before function call: %d\n", a);
changeValue(&a);
printf("After function call: %d\n", a);
return 0;
}
Output:
Before function call: 10
After function call: 20
Explanation: The function changeValue() modifies the value at the memory address of a,
permanently changing its value.

Key Differences Between Call by Value and Call by Reference


Feature Call by Value Call by Reference
Parameter Passed Copy of value Address of variable
Effect on Original Variable No change Changed
Memory Usage More (creates a copy) Less (uses existing variable)
Performance Slower for large data Faster for large data

Explanation of Recursion in C
A method to solve a problem by breaking it into smaller parts where a function calls itself to do so.
Common examples include factorial calculation, Fibonacci series, and tree traversal.

How Recursion Works


A recursive function is formed from two parts:
Base Case – Where recursion stops.
Recursive Case – The function calls itself with an altered function argument.
Example: Factorial Using Recursion
#include <stdio.h>

int factorial(int n) {
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}

int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Output:
Factorial of 5 is 120

It is an iterative method where each function calls another function, and with the final iteration, no
other function calls are needed. Each iteration continues till n=0.
Then, it returns step-by-step values to calculate 5 times 4 times 3 times 2 times 1 gives an answer of
120.
Advantages of Recursion:
Easy solutions to complex problems like tree traversal, backtracking, and sorting.
Reduces code size that would otherwise use loops.
Easy to read when it makes sense to express the given problem in terms of smaller subproblems.

Disadvantages of Recursion:
Uses more memory for the stack of function calls.
Execution is slower for deep recursion than for looping.
Might run into infinite recursion if the defining base case is done differently.

Conclusion:
Called by virtue and called by reference are distinct ways of passing arguments to functions. Call by
Value is performed with copies while Call by Reference modifies the actual data. Recursion is the
process used for breakdowning problems into small sub-problems. On understanding the same, one
can write efficient and optimized C programs.

5. Answer
The C definition and scope of pointers
A pointer in a C program is a variable storing the memory address of another variable. A pointer
gives the location in memory where that variable and its referenced value are stored.

Why Use Pointers?


Memory management with pointers is far efficient.
Pointers improve access to the data stored.
Function arguments can be passed through references by pointers.
Array-handling and string processing benefit from pointers.
Declaring a pointer
To declare a pointer in C programing, put an asterisk sign just before the name of a pointer variable:
int *ptr; // Declaring a pointer to an integer

Here, ptr is a pointer that can store the memory address of an integer variable.
Example: Pointer Declaration and Usage
#include <stdio.h>

int main() {
int num = 10; // Regular integer variable
int *ptr; // Pointer variable

ptr = &num; // Storing address of num in ptr

printf("Value of num: %d\n", num);


printf("Address of num: %p\n", &num);
printf("Pointer ptr stores: %p\n", ptr);
printf("Value at address stored in ptr: %d\n", *ptr);

return 0;
}

Output:
Value of num: 10
Address of num: 0x7ffc2b3a4b38
Pointer ptr stores: 0x7ffc2b3a4b38
Value at address stored in ptr: 10

The explanation of what has gone ahead:


ptr = &num; means that ptr has been assigned the address of num.
*ptr is used to access value of what's at the memory location.
& operator is used to get the memory address of a variable.
Pointer Arithmetic in C
Pointer arithmetic involves the operations done on the pointer variables that allow easy traversal
through the memory ones. The main operations include increment, decrement, addition, and
subtraction.

1. Incrementing of a Pointer (ptr++)


Increments a pointer to move into the next memory location of its data type.
#include <stdio.h>

int main() {
int arr[] = {10, 20, 30};
int *ptr = arr; // Pointer to first element

printf("First element: %d\n", *ptr);


ptr++; // Move to next integer (4 bytes ahead)
printf("Second element: %d\n", *ptr);

return 0;
}

Conclusion:
Pointers in C are powerful tools for efficient memory handling and program optimization. Pointer
arithmetic enhances their capabilities, allowing seamless navigation through memory.
Understanding pointers is crucial for advanced C programming.
6. Answer
Differences Between Structure and Union in C
C program possesses two important data structures: Structures (struct) and unions (union). They
allow various data types to be grouped under a single name, but they differ in memory management
and usage.

1. Structure
A structure is a user-defined data type that allows the grouping of different variables under a single
name.
Each member of a structure includes its own memory place, meaning all members can keep
values at the same time.
Example of Structure in C
#include <stdio.h>

struct Student {
int roll_no;
float marks;
char grade;
};

int main() {
struct Student s1 = {101, 89.5, 'A'};

printf("Roll No: %d\n", s1.roll_no);


printf("Marks: %.2f\n", s1.marks);
printf("Grade: %c\n", s1.grade);

return 0;
}

Memory Used by Structures


If int takes 4 bytes, float 4 bytes, and char 1 byte, the total memory taken by struct Student can be
approximately 9 bytes or even more considering padding.

2. Union
A union is another way of grouping several variables together under a single name.
All members share the same memory space, which indicates that at one moment, there can only be
one member that holds a valid value.
Example of Union in C
#include <stdio.h>

union Data {
int num;
float value;
char letter;
};

int main() {
union Data d;

d.num = 100;
printf("Integer: %d\n", d.num);

d.value = 25.5; // Overwrites previous value


printf("Float: %.2f\n", d.value);

d.letter = 'A'; // Overwrites previous value


printf("Character: %c\n", d.letter);

return 0;
}

Memory Usage in Union


A union takes memory equal to its largest member. If the largest data type is float (4 bytes), then the
union uses 4 bytes total, regardless of how many members are defined.

Key Differences Between Structure and Union


Feature Structure (struct) Union (union)
Memory Separate memory for each member Shared memory for all members
Allocation
Size Sum of all members' sizes Size of the largest member
Access All members can store values at the Only one member can store a value
same time at a time
Use Case Used when all members need Used when only one value is
storage at once needed at a time

(b) Memory allocation functions in C


Dynamic memory allocation comprises four main functions responsible for managing memory
dynamically during runtime:

malloc()
calloc()
realloc()
free()
These functions are available for use post-including the stdlib.h library.
1. malloc() - Memory Allocation
Allocates a block of memory without initializing it.
Returns pointer to allocated memory, or NULL if allocation failed.
Example of malloc()
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;

ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers

if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

for (int i = 0; i < 5; i++) {


ptr[i] = i * 10; // Assigning values
printf("%d ", ptr[i]);
}

free(ptr); // Deallocate memory

return 0;
}

2. calloc() (Continuous Allocation)


• Similar to malloc(), but initializes all elements to zero.
• Syntax:
ptr = (int*) calloc(n, sizeof(int));
Example of calloc()
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;

ptr = (int*) calloc(5, sizeof(int)); // Allocates memory for 5 integers and initializes them to 0

if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

for (int i = 0; i < 5; i++) {


printf("%d ", ptr[i]); // Outputs 0 for all elements
}

free(ptr); // Deallocate memory

return 0;
}

3. realloc() (Reallocation)
• Used to resize an already allocated memory block.
• Syntax:
ptr = realloc(ptr, new_size);
Example of realloc()
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr = (int*) malloc(2 * sizeof(int)); // Allocating memory for 2 integers

ptr[0] = 10;
ptr[1] = 20;

// Expanding the memory to store 4 integers


ptr = (int*) realloc(ptr, 4 * sizeof(int));

ptr[2] = 30;
ptr[3] = 40;

for (int i = 0; i < 4; i++) {


printf("%d ", ptr[i]);
}

free(ptr); // Deallocate memory

return 0;
}

4. free() (Memory Deallocation)


• Frees dynamically allocated memory.
• Prevents memory leaks.
Example of free()
int *ptr = (int*) malloc(5 * sizeof(int));
free(ptr); // Releases allocated memory

Conclusion:
Structure vs. Union: While unions share memory across members, structures allot memory to each
member independently.
Malloc(), calloc(), realloc(), and free() are useful tools for dynamic memory allocation.

You might also like