C Programming IA2
C Programming IA2
C Programming IA2
Documentation section: The documentation section comprises comment lines that provide the
program's name, the author's information, and other details the programmer may want to
reference later. Comments can be inserted anywhere in the program, as long as they are
enclosed within the delimiters /* and */.
For example: /*this is a comment*/). These comments are useful for identifying the
program's main features or explaining the logic behind different parts of the program.
Link section or preprocessor directives: This section is here to help insert links for pre-defined
functions. It allows users to have access to the standard library as well as the primitive
functions. They include header files and commands that are preprocessed before performing
any compilation.
They usually start with #include<header file>. Header files may vary depending on the task to be
performed. For instance, when users want to work with strings, they might want to use the
header file: #include<string.h>
Definition section: The definition section consists of all the symbolic constants.
Global declaration section: there exist some functions that are going to be used more than
once. Those functions need to be accessed from every part of the program. Such functions are
called global functions; they are declared in this section.
Main function-main(): This function is viewed as the entry of the program. Every C program has
a main function. In this function, we can find both the declaration part where every variable is
declared as well as the executable part. The statements are enclosed in braces which mark the
beginning and ending of the instructions ({…..}).
The executable part is written in the declaration part. The statements end with a semicolon (;).
Subprogram: The subprogram consists of user-defined functions. Those are functions that are
defined by the user to perform a task as per their need. The user-defined functions are called in
the main function. There is no specific order but, more often, they are visible right after the
main function. User-defined functions are also called local functions. Unlike global functions,
they can be accessed only within the block of code they are declared.
Here is an example of a simple C program:
#include<stdio.h> //preprocessor directives
}
void greet(){
printf("Hello, I am new in C programming language!\n");
}
printf () and scanf () functions are some predefined functions that permit both the user
and the programmer to have an interaction. They are crucial for handling input and
providing output in the C programming language.
scanf() function is used in a case where we want to take input from the user. It captures
the user’s input. It uses a format specifier to determine its data type.
Here is an example of a program. In this program, we can ask a user to enter their age
and capture the age entered with the help of the function scanf():
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age); //%d is called a placeholder and tells the function that it wants
//integers to be stored in it.
printf("You are %d years old.\n", age);
return 0;
}
On the other hand, printf function is used to display a message to the user. It prints
output to the console. Printf function takes the string format and can include various
formats for placeholders as per the requirements.
Here is an example of a C program that includes a printf function
#include <stdio.h>
int main() {
int age = 25;
printf("I am %d years old.\n", age);
return 0;
}
2. A function is a block of code designed to perform a specific task.it is a set of instructions that
can be called whenever they are needed enhancing modularity and code reusability in
programming. Functions can be classified based on how they handle parameters (inputs) and
return values (outputs). There is a specific syntax to follow when defining a function: function
name, followed by the return type (if there is any), and then the body of the function where we
can find the statements to be executed.
Functions can be classified into four (4) categories as per their return type.
A function with a parameter and a return value: this type of function can take input
(parameter), perform some operations, and provide an output or a return value.
For instance, we can have a C program in which, we create a function that takes two parameters
and returns their sum:
#include <stdio.h>
int add((int a, int b) { //function declaration
return a + b; // Returning the sum of the two parameters
}
int main() {
int result = add(4, 5); // Function call with arguments 4 and 5
printf("sum is : %d\n", result);
return 0;
}
A function with a parameter, without a return value, is the type of function that takes a
parameter and performs some operations but does not return any value.
#include <stdio.h>
void printSum(int a, int b) { //a void function does not return any value
printf("Sum: %d\n", a + b);
}
int main() {
printSum(5, 3); // Function call with arguments 5 and 3
return 0;
}
A function without a parameter and no return value is the type of function that takes no
parameter and does not return any value. These functions are used only to perform a specific
task. They neither take input nor return a value.
#include <stdio.h>
void printHello() {
printf("Hello, World!\n");
}
int main() {
printHello(); // Function call
return 0;
}
This kind of function is mostly used to display on the console.
A function without a parameter but with a return value: is the type of function that does not
take any input; yet, it does return an output. They also perform some specific tasks as per the
user’s requirements.
#include <stdio.h>
int getNumber() {
return 42; // Returning an integer value
}
int main() {
int num = getNumber(); // Function call and storing the return value
printf("Number: %d\n", num);
return 0;
}
In this example, the function getNumber was not given any parameter; yet, it does return the
value after it had performed the task needed.
In some, the four types of functions discussed above are all used for different purposes. They
are all essential for code readability as well as efficiently writing your program. At the same
time, they all used to modularize code effectively.
3. In C programming language, there are three (3) kinds of Loops. Those loops can be used
depending on their usage as well as the user’s need. They all have a specific syntax to follow.
For loop:
For loop is the kind of loop that is suitable only when we initially know the number of iterations.
Syntax:
for (initialization; condition; increment)
{
// code to be executed
} As per the syntax, we can use a for loop when we know the starting value, the condition as
well as the increment. These are the parts of a for loop.
An example of a for loop is:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 5; i++) { //all three conditions are respected here: initial value, condition and
increment.
printf("Value of i: %d\n", i);
}
return 0;
}
This program is going to print the first 5 integers between 0 (inclusively) and 5 (exclusively).
While Loop: unlike the for loop, sometimes the number of iterations is not known. In cases like
that, while loop is very useful. The iterations keep on going for as long as the condition is true.
Otherwise, it just stops.
Syntax:
while (condition) {
// code to be executed
}
Example of while loop:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("Value of i: %d\n", i);
i++;
}
return 0;
}
In the case of a while loop, we know that the condition is going to be executed at least once
because it comes before the condition is initially checked.
Do…while loop:
It is the kind of loop that is very similar to the do-while loop. The only difference: In
C, the do...while loop is a control structure that runs a block of code at least once
and then continues to execute the block repeatedly as long as a given condition is true.
The main distinction between a do...while loop and a while loop is that the
do...while loop ensures the code block is executed at least once, since the condition is
checked after the block has been executed.
Syntax:
do{
// Code to be executed
} while (condition);
#include <stdio.h>
int main() {
int count = 1;
do {
count++;
return 0;
}
4. In C programming, storage classes determine the scope (visibility) and lifespan of
variables and functions within a program. They specify the storage location, initial value,
and accessibility of variables.
A storage class pertains to the duration a variable persists and its scope within the
program, meaning the segment of the program where the variable is acknowledged.
Lifetime: Valid only during the block's execution. These variables are created
upon entering the block and destroyed upon exiting. In other words, they exist for
as long as the block of code in which they are declared is not executed.
Register storage class: in this type of storage class, the variables are stored in the
CPU instead of the RAM.
void function() {
Static:
Lifespan: static variables tend to retain their values throughout the program; even
when the function is exited and then reopened.
Scope: they cannot be accessed outside of the function in which they are declared.
Default value: 0
Example:
void function() {
count++;
printf("%d\n", count);
External
Global variables and functions: Enable sharing of variables and functions across
various files.
Keyword: extern
Example: file #1
void someFunction();
file #2
void someFunction() {
global_var++;
In this example, we can see that a function is created in a separate file and then
used in another file. The extern storage class does not create space for the
function because it does exist already.
In some, auto is the default for local variables, with a local scope and a temporary
lifetime.
register: Indicates fast access storage, with a local scope and a temporary lifetime.
static: Provides a persistent lifetime across function calls or throughout the file.
extern:
Allows sharing across multiple files, with a global scope and a lifetime
spanning the entire program.
These storage classes help control the visibility and lifespan of variables, enhance
performance, and keep the code organized in larger projects.
Dynamic memory allocation in C enables programs to request and assign memory during
execution using functions provided by the standard library. This capability is essential for
developing adaptable and efficient programs, particularly when the specific memory
needs cannot be predetermined before the program starts.
Keys functions for dynamic memory allocation are as follows:
Dynamic Allocation: In contrast to static memory allocation (e.g., using arrays), dynamic
allocation enables flexible memory management during program execution.
Memory Management: Always use free with malloc to prevent memory leaks.
Purpose: Allocates a memory block of size bytes without initializing its contents.
Return Value: Returns a pointer to the allocated memory, or NULL if the allocation
fails.
if (arr == NULL) {
Calloc
calloc is a useful function for allocating and initializing memory in C, simplifying the
process of working with arrays and structures by automatically setting the allocated
memory to zero, eliminating the need for manual initialization.
Error Handling: Always verify if calloc returns NULL to manage allocation failures
effectively.
Memory Management: Use calloc in conjunction with free to ensure that the allocated
memory is properly deallocated when it is no longer needed.
Usage: Allocates memory for an array of num elements, each of size bytes, and initializes
all bytes to zero.
Returns: A pointer to the allocated memory, or NULL if the allocation fails.
if (arr == NULL) {
‘Realloc’:
Usage: Adjusts the size of the memory block pointed to by ptr to size bytes. The contents
up to the minimum of the old and new sizes remain unchanged.
Return Value: Returns a pointer to the resized memory block, which might be at a
different location, or NULL if the allocation fails.
if (arr == NULL) {
‘free’
Returns: No value
Syntax: free(arr);
Structure (struct)
A structure enables the grouping of variables of varied data types under a single
identifier. Each member within the structure occupies its distinct memory location.
Memory Allocation: Each member of the structure is allocated its own memory space.
The total size of the structure is the sum of the sizes of its members.
Access: Each member can be accessed independently using the dot (.) operator.
Usage: Structures are useful when you need to keep related data together but still want to
be able to access each piece of data independently.
Example:
ex.a = 10;
ex.b = 20.5;
ex.c = 'Z';
Union
On the other hand, a union similarly groups variables of diverse data types, but all its
members occupy a single shared memory location. The overall size of the union
corresponds to the size of its largest member.
Memory Allocation: All members of a union utilize the same memory location, resulting
in the union's size being equivalent to the size of its largest member.
Access: Only one member can be accessed at any given time due to the shared
memory location; writing to one member will overwrite the others.
Usage: Unions are advantageous when conserving memory space is crucial, ensuring that
only one member is utilized or accessed at a time.
Example: union Example {
int a;
float b;
char c;
};
#define PI 3.14159
int main() {
return 0;
}
Let's explain the expansion using the above example:
This macro takes a parameter x and computes its square. For instance,
SQUARE(radius) will be replaced with ((radius) * (radius)), yielding the square of
radius.
#include <stdio.h>
int main() {
return 0;
Overall, Macros can make code clearer by providing meaningful names for constants
or complex calculations. Reduces redundancy by reusing code snippets effectively.