DCA6110 Basic Structure of a C Program
DCA6110 Basic Structure of a C Program
1. Answer
Basic Structure of a C Program
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`).
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;
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.
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
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;
}
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.
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>
int main() {
printf("Extern Variable: %d\n", num);
return 0;
}
In essence, extern defines that num is created elsewhere. It helps in making the external variables
shareable across multiple files.
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;
}
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>
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>
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.
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.
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.
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
return 0;
}
Output:
Value of num: 10
Address of num: 0x7ffc2b3a4b38
Pointer ptr stores: 0x7ffc2b3a4b38
Value at address stored in ptr: 10
int main() {
int arr[] = {10, 20, 30};
int *ptr = arr; // Pointer to first element
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'};
return 0;
}
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);
return 0;
}
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;
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
return 0;
}
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;
}
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;
ptr[2] = 30;
ptr[3] = 40;
return 0;
}
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.