PPS_MID-II_(1)[1]
PPS_MID-II_(1)[1]
UNIT-3
FUNCTIONS
Advantages of functions
1. Code Reusability: Write code once and reuse it.
2. Modularity: Break a large program into smaller, manageable parts.
3. Simplified Code: Makes code easier to understand and maintain.
4. Easier Debugging: Fix issues in one place without affecting other parts of the code
There are 4 different types of functions based on number of parameters passed and return type
1. Function with no return value and with no arguments
void printMessage() {
printf("Hello, this is a simple message.\n");
}
2. Function with no return value and with arguments
void printSum(int a, int b) {
int sum = a + b;
printf("The sum is: %d\n", sum);
}
3. Functions with return values and no arguments allow you to create a function that doesn’t
require any input data but still returns a result.
int getNumber() {
int number = 42; // or any logic to determine the value
return number;
}
4. Function with return value and with arguments
int multiply(int x, int y) { //function header (int x, int y are formal parameters)
return x * y;//function body
}
2.Construct a ‘C’ program to calculate the area of the square using Function without argument and
with return value.
int getArea() {
#include <stdio.h>
int main() {
int n;
if (n < 0) {
printf("Please enter a non-negative integer.\n");
return 1;
}
return 0;
}
4.Differentiate between recursion and iteration and Write a C program to calculate GCD of
#include <stdio.h>
int main() {
int a, b;
if (a < 0 || b < 0) {
printf("Please enter non-negative integers.\n");
return 1;
}
return 0;
}
5.Differentiate between call by value and call by reference function parameter passing
Pass by Value means passing a copy of the argument's value to the function. The function works
on this copy, so changes made to the parameter inside the function do not affect the original
variable in the caller function.
Pass by Reference means passing the actual memory address (reference) of the argument to the
function. The function can then modify the original variable’s value since it has direct access to its
memory location. In C, we achieve pass by reference by using pointers.
#include <stdio.h>
void passing_byValue(int y) {
y = 30; // This doesn’t change the original variable
printf("Inside function, y = %d\n", y);
}
int main() {
int a = 10;
printf("Before function call, a = %d\n", a); // prints 10
// Pass by reference
passing_byRef (&a);
printf("After function call, a = %d\n", a); // prints 20, changes from 10 to 20
// Pass by value
passing_byValue (a);
printf("After function call, a = %d\n", a); // prints 20, did not change to 30
return 0;
}
6.List and explain the types of storage classes in C.
extern int a; // It will get access to the variable defined in another file.
static int static_global_count = 0; //limits scope to the current file
void example() {
auto int num = 10; // 'auto' is optional
static int static_local_count = 0; // retains value across function calls
printf("Value of num: %d\n", num);
register int i;
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
}
UNIT-4
POINTERS
1.Define the Pointer in C Programming. Explain how the pointer variable declared and initialized?
Write a C program to find the sum and mean of all elements in an array using pointer.
The pointer in C language is a variable which stores the address of another variable. This variable can
be of type int, char, array, function, or any other pointer. The size of the pointer depends on the
machine architecture.
Just like the variables, we also have to declare the pointers in C before we use them in any program
SYNTAX:data_type * name_of_pointer_variable;
We can declare the pointers in the C language with the use of asterisk (*, dereferencing symbol).
For example:
int *ip;
char *cp;
Pointers can be initialized with address of the already declared variables. Address of a variable can be
obtained by placing an ampersand (&) in front of a variable name;
SYNTAX: pointer_variable = & name_of_another_variable;
int a = 10;
int *ip;
ip = &ip;
Pointers can be assigned with the address returned by malloc function with appropriate typecasting.
int *ip;
ip = (int *) malloc (10 * sizeof(int)); // address of the memory allocated for 10 integer values
if (n <= 0) {
printf("Invalid array size.\n");
return 1;
}
int arr[n];
printf("Enter %d elements of the array: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int sum;
float mean;
calculate_sum_and_mean(arr, n, &sum, &mean);
return 0;
}
2.Write a C program to implement function pointer to find sum and product of two numbers.
#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int *ptr;
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add;
result=(*ip)(a,b); //function call to sum up two numbers
printf("Value after addition is : %d",result);
ip=multiply;
result=(*ip)(a,b); //function call to get product of two numbers
printf("Value after multiplication is : %d",result);
return 0;
}
3.What is a pointer? How it can be used to access 1D array and 2D array using pointer.
The pointer in C language is a variable which stores the address of another variable. This variable can
be of type int, char, array, function, or any other pointer.
For an array, the base address is the location of the first element (index 0) of the array. The compiler
also defines the array name as a constant pointer to the first element.
If ‘p’ is a pointer to a one dimensional array ‘a’ then the array name “a” is a constant pointer pointing
to first element of that array &a[0] => a => (base address)
In case of 2D arrays,
• arr points to the first row (address of arr[0]).
• arr[0] points to the first element of the first row (arr[0][0]).
• arr + 1: Points to the second row (arr[1]).
• *(arr + 1): Dereferences the pointer to the second row, equivalent to arr[1].
• *(*(arr + 1) + 2): Accesses the element in the second row, third column (arr[1][2]).
4.What are the advantages and disadvantages of pointers? Explain the possible arithmetic and
value arithmetic operations on pointers.
There are various uses of the pointers in C language. Some of them are listed below:
1. One can easily access any location of memory in the computer using the pointers
2. We can allocate the memory dynamically in C language when we use the calloc() and
malloc() functions. The pointers are primarily used in such cases.
3. Pointers are used to create complex data structures, like the linked list, tree, graph, etc.
4. It reduces the code and thus improves the overall performance. We can use it to retrieve the
strings, trees, and many more. We can also use it with structures, arrays, and functions
5. Pass by reference is implemented by using pointers in C language.
5.Write a short note on:(i)void pointer (ii)pointer to pointer(iii) null pointer (iv) dangling
The Void pointers in C are the pointers of type void. It means that they do not have any associated
data type. They are also called generic pointers as they can point to any type and can be typecasted.
Syntax: void * pointer_name;
Note: Void pointers cannot be dereferenced. It can however be done using typecasting the void
pointer. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus
size.
int main()
{
int x = 4;
float y = 5.5;
// A void pointer
void* ptr;
return 0;
}
A pointer variable can store the address of any type including the primary data types, arrays, struct
types, etc. Likewise, a pointer can store the address of another pointer too, in which case it is called
"pointer to pointer" (also called "double pointer").
NULL Pointer is a pointer that is pointing to nothing (i.e. not pointing to any valid object or memory
location). In case, if we don’t have an address to be assigned to a pointer, then we can simply use
NULL. NULL is used to represent that there is no valid memory address.
A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer.
Such a situation can lead to unexpected behavior in the program and also serve as a source of bugs
in C programs.
int main()
{
int* ptr = (int*)malloc(sizeof(int));
// After below free call, ptr becomes a dangling
pointer
free(ptr);
printf("Memory freed\n");
// removing Dangling Pointer
ptr = NULL;
return 0;
}
A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the
address will remain constant. Therefore, we can say that if a constant pointer is pointing to some
variable, then it cannot point to any other variable.
#include <stdio.h>
int main()
{
int a=1;
int b=2;
int *const ptr;
ptr=&a; // We will get error here.
ptr=&b; // We will get error here.
printf("Value of ptr is :%d",*ptr);
return 0;
}
STRUCTURES
A nested structure in C is a structure within structure. One structure can be declared inside another
structure in the same way structure members are declared inside a structure.
An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities.
The array of structures in C are used to store information about multiple entities of different data
types.
The array of structures is also known as the collection of structures
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Comparison:
Example Use
Person details with an address. List of students or employees.
Cases
2. Define the structure employee with attributes employee id, name, department and basic
salary. Develop a C program to display the employee details in the increasing order of their
salaries.
#include <stdio.h>
#include <string.h>
int main() {
int n;
if (n <= 0) {
printf("Invalid number of employees.\n");
return 1;
}
return 0;
}
3. Define Structure. Differentiate between Union and Structure. Explain how to declare,
Structure in C is a user-defined data type that enables us to store the collection of different data
types. Structures are a way to group several related variables into one place.
Example: student is a tag name. Rollno, name, and marks are the member variables.
struct student
{
int rollno;
char name[20];
int marks[6];
};
struct student s;
s.rollno = 12;
strcpy(s.name, “Ram”);
s.marks = 988;
The Union is a user-defined data type in C language that can contain elements of the different data
types just like structure.
But unlike structures, all the members in the C union are stored in the same memory location. Due to
this, only one member can store data at the given instance.
union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
{
// defining a union variable
union un var1;
// initializing the union member
var1.member1 = 15;
printf("The value stored in member1 = %d", var1.member1);
return 0;
}
4.What is a union? For what kind of applications unions are useful? Explain the unions with
an example.
The Union is a user-defined data type in C language that can contain elements of the different data
types just like structure.
Unlike structures, all the members in the C union are stored in the same memory location. Due to
this, only one member can store data at the given instance.
Memory Optimization:
• Example: Storing multiple types of data (like int, float, or char) in a limited space.
• Efficiently manage different data formats for a variable, such as when implementing
protocols or parsers.
Data Interpretation:
• Used while interpreting the same memory location in different ways.
Hardware Registers:
• Represent hardware registers where multiple fields share the same memory location.
union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
{
// defining a union variable
union un var1;
// initializing the union member
var1.member1 = 15;
printf("The value stored in member1 = %d", var1.member1);
return 0;
}
UNIT-5
FILES
1.Define the Text and Binary files in C. List the importance of text and binary files. Explain
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and takes
bigger storage space.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security than text
files.
The fopen() function is used to create a new file or to open an existing file. This function is available
in stdio.h file
Syntax:
filename is the name of the file to be opened and mode specifies the purpose of opening the file.
Mode can be of following types,
Example:
#include <stdio.h>
#include <stdlib.h>
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
}
int main() {
char filename[100];
print_file_contents(filename);
return 0;
}
3.Write a C program to merge two files into single file.
#include <stdio.h>
#include <stdlib.h>
fclose(file);
}
int main() {
char input_file1[100], input_file2[100], output_file[100];
printf("Enter the name of the input file 1 to read its contents: ");
scanf("%s", input_file1);
printf("Enter the name of the input file 2 to read its contents: ");
scanf("%s", input_file2);
printf("Enter the name of the output file to merge the input file contents: ");
scanf("%s", output_file);
fclose (ofp);
return 0;
}
4.Write a C Program to copy the contents of file into a second file.
#include <stdio.h>
#include <stdlib.h>
fclose(file);
}
int main() {
char input_file[100], output_file[100];
printf("Enter the name of the input file to read its contents: ");
scanf("%s", input_file);
printf("Enter the name of the output file to copy the input file contents: ");
scanf("%s", output_file);
fclose (ofp);
return 0;
}
5.Write a c program to append the content in to file and display it.
#include <stdio.h>
#include <stdlib.h>
fclose(file);
}
int main() {
char file1[100], file2[100];
fclose (ofp);
// Reopen the file2 in read-only mode. Pointer will be set to the top.
ofp = fopen(file2, "r");
if (ofp == NULL) {
perror("Error opening file 2 for reading");
return;
}
return 0;
}
6.WAP to count no. of characters, lines and words in a file.
#include <stdio.h>
#include <stdlib.h>
char ch;
while ((ch = fgetc(file)) != EOF) {
if (ch == ‘ ‘) word_count++;
if (ch == ‘\n’) line_count++;
char_count++;
}
Printf (“Character count = %d, Word Count = %d, Line count = %d\n”,
char_count, word_count, line_count);
fclose(file);
}
int main() {
char filename[100];
print_file_contents(filename);
return 0;
}
7.Write a program to print the records in reverse order.
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
int total_bytes, records_count;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fseek(fptr, 0, 2);
total_bytes = ftell(fptr);
records_count = total_bytes / sizeof(struct threeNum);
File content need not be read in a sequential order. Using the library function fseek, we can place the
pointer position in the file at the specified byte.
Syntax:
int fseek ( file_pointer, displacement, pointer position);
int fseek ( FILE *fp, long num_bytes, int origin ) ;
Preprocessing directives are lines in the program that start with `#'.
The C preprocessor is a tool that processes the source code before the actual compilation starts. It
performs various tasks, including:
1. File Inclusion:
o Includes header files into the program using #include.
o Example: #include<stdio.h>.
2. Macro Definition:
o Defines macros for constants or reusable code snippets using #define.
o Example: #define PI 3.14.
3. Conditional Compilation:
o Compiles specific parts of the program based on conditions using directives like #if,
#ifdef, #ifndef, etc.
o Example: #ifdef DEBUG.
4. Code Optimization:
o Simplifies repetitive tasks by expanding macros before compilation.
#include <File> :
Inserts a particular header from another file in a list of directories specified by include path, then in a
standard list of system directories.
#ifdef macro_name:
Returns true if a macro with macro_name is defined then the block of code will be processed
otherwise not.
10.Explain about File I/O functions and Error Handling in files.
File I/O functions in C allow programs to read from and write to files stored on a disk. These
operations are performed using standard file handling functions from the stdio.h library.
int main() {
FILE *file;
Syntax:
enum EnumName {
constant1,
constant2,
constant3,
...
};
• By default, the constants are assigned integer values starting from 0.
• You can also manually assign specific values.
Example:
#include <stdio.h>
int main() {
enum Days today;
today = WEDNESDAY;
if (today == WEDNESDAY) {
printf("It's Wednesday!\n");
}
return 0;
}
Output:
It's Wednesday!
Manually Assigned Values:
enum Colors { RED = 1, GREEN = 2, BLUE = 4, YELLOW = 8 };
Advantages:
1. Improves Readability:
o Makes code easier to understand (e.g., WEDNESDAY vs. 2).
2. Safer Code:
o Prevents unintended assignments to unrelated constants.
3. Maintainability:
o Changing values in the enum reflects throughout the program.
Macros in Preprocessor
A macro is a preprocessor directive in C that defines a name for a constant, expression, or function-
like construct. Macros are replaced by their values or code during the preprocessing stage.
Syntax:
1. Object-like Macro:
#define NAME value
2. Function-like Macro:
#define NAME(parameters) code
Examples:
1. Object-like Macro:
#include <stdio.h>
#define PI 3.14159
#define AREA_OF_CIRCLE(radius) (PI * (radius) * (radius))
int main() {
float radius = 5.0;
printf("Area of the circle: %.2f\n", AREA_OF_CIRCLE(radius));
return 0;
}
Output:
Area of the circle: 78.54
2. Function-like Macro:
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
int num = 4;
printf("Square of %d is %d\n", num, SQUARE(num));
return 0;
}
Output:
Square of 4 is 16
Advantages of Macros:
1. Efficiency:
o Avoids the overhead of function calls.
2. Convenience:
o Useful for constants or repetitive code.
3. Portability:
o Changes in the macro definition propagate across the program.
Disadvantages of Macros:
1. No Type Checking:
o May lead to runtime errors due to improper usage.
2. Debugging Difficulty:
o Errors in macros are harder to trace as they are replaced during preprocessing.
int main()
{
int m = 8;
int n = 5;
printf (“Product of %d and %d = %d\n”, product (m,n));
printf (“Sum of %d and %d = %d\n”, sum (m,n));
printf (“Greatest of %d and %d = %d\n”, greatest (m,n));
}
13.Explain about command line arguments in c and write a c program to find sum of n numbers using
command line argument.
Command-line arguments are parameters passed to the main() function when the program is
executed. These arguments allow users to pass input values or options directly to the program from
the command line
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: %s num1 num2 ...\n", argv[0]);
return 1;
}
int sum = 0; // Loop through command-line arguments and compute the sum
for (int i = 1; i < argc; i++) {
sum += atoi(argv[i]); // Convert string to integer
}
printf("The sum of the given numbers is: %d\n", sum);
return 0;
}