0% found this document useful (0 votes)
19 views112 pages

Au PPSC Lab Record 09-12-24

Uploaded by

anunayx
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)
19 views112 pages

Au PPSC Lab Record 09-12-24

Uploaded by

anunayx
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/ 112

WEEK – 1 Date:

Explore different platforms?


(a) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
Vim:

Introduction to Vim:
Vim, short for "Vi Improved," is a highly configurable text editor that is an extended version of
the original Unix-based Vi editor. It is widely used for editing and creating any type of text, code,
or configuration files. Vim is known for its efficiency, versatility, and powerful features.

One distinctive aspect of Vim is its modal editing system. In Vim, the editor operates in different
modes, each serving a specific purpose. Understanding and utilizing these modes is crucial for
efficient text editing.
Vim Modes:
Normal Mode:
• This is the default mode when you open a file in Vim.
• In Normal mode, you can navigate through the text, delete, copy, paste, and execute various
commands.
• To enter Normal mode from other modes, press Esc.
Insert Mode:
• In Insert mode, you can actually insert and edit the text.
• To enter Insert mode from Normal mode, press i.
• To exit Insert mode and return to Normal mode, press Esc.
Visual Mode:
• Visual mode allows you to select and manipulate text.
• To enter Visual mode from Normal mode, press v.
• You can also use V for line-wise selection or Ctrl + v for block-wise selection.
Command-Line Mode:
• This mode is used for entering and executing commands.
• To enter Command-Line mode from Normal mode, press :. This is where you can save, quit, and
perform other operations.
Basic Vim Commands:
Navigation:
• h, j, k, l: Move left, down, up, and right respectively.
• w, b: Move forward and backward by word.
• gg, G: Move to the beginning and end of the file, respectively.
• Ctrl + f, Ctrl + b: Scroll forward and backward.
Editing:
• i: Enter Insert mode before the cursor.
• a: Enter Insert mode after the cursor.
• x: Delete the character under the cursor.
• dd: Delete the current line.
• yy: Yank (copy) the current line.
Saving and Quitting:
• :w: Save changes.
• :q: Quit (close) Vim.
• :wq or ZZ: Save and quit.
Dev C++:
d) Program to print "Hello world" in C

#include<stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}

Output:

e) Write a simple program to read int, float, char and string using scanf() and display
using printf() in all the above given platforms.

#include<stdio.h>
#include<conio.h>
int main()
{
int n;
char ch;
float m;
char str[20];
scanf("%d",&n);
fflush(stdin);
scanf("%c%f%s",&ch,&m,str);
printf("n = %d\n",n);
printf("ch = %c\n",ch);
printf("m = %f\n",m);
printf("str = %s\n",str);
return 0;
}

Input:

Output:
WEEK – 2 Date:
a) Program to find the Sum and Difference of 2 numbers
Objective: Learn int and float data types. https://www.hackerrank.com/challenges/sum-
numbersc/problem?isFullScreen=true

FileName: SumandDiff.C
#include<stdio.h>
int main()
{
int x,y;
scanf("%d%d",&x,&y);
printf("Sum of %d and %d is: %d\n",x,y,x+y);
printf("Difference between %d and %d is: %d\n",x,y,x-y);
return 0;
}

Input:

Output:
b) Playing with Characters
Objective: Learn how to take a character, a string and a sentence as input in C.
https://www.hackerrank.com/challenges/playing-withcharacters/problem?isFullScreen=true

FileName: InputDemo.C
#include<stdio.h>
int main()
{
char ch;
char word[100];
char words[100];
scanf("%c\n",&ch);
scanf("%s\n",word);
scanf("%[^\n]s",words);
printf("%c\n",ch);
printf("%s\n%s",word,words);
return 0;
}

Input:

Output:
c) Bitwise Operators Objective: Learn how to work with bits (0,1) and bitwise operators.
https://www.hackerrank.com/challenges/bitwise-operators inc/problem?isFullScreen=true005

FileName:BitwiseOperators.C

#include <stdio.h>
void calculate_the_maximum(int n, int k)
{
int a=0,o=0,x=0;
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++)
{
if((i&j)<k && (i&j)>a)
a=i&j;
if((i|j)<k && (i|j)>o)
o=i|j;
if((i^j)<k && (i^j)>x)
x=i^j;
printf("%d %d %d\n",a,o,x);
}
}
printf("%d\n%d\n%d",a,o,x);
}

int main()
{
int n, k;

scanf("%d %d", &n, &k);


calculate_the_maximum(n, k);

return 0;
}

Input:

Output:
d) Conversion of Fahrenheit to Celsius and vice versa.

FileName: TempConversion.C

#include <stdio.h>

// Function to convert Fahrenheit to Celsius


float fahrenheitToCelsius(float fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}

// Function to convert Celsius to Fahrenheit


float celsiusToFahrenheit(float celsius)
{
return (celsius * 9 / 5) + 32;
}
int main()
{
int choice;
float temperature, result;

// Menu for user selection


printf("Temperature Conversion Menu:\n");
printf("1. Convert Fahrenheit to Celsius\n");
printf("2. Convert Celsius to Fahrenheit\n");
printf("Enter your choice (1 or 2): ");
scanf("%d", &choice);

// Perform the selected conversion


switch (choice)
{
case 1:
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &temperature);
result = fahrenheitToCelsius(temperature);
printf("Temperature in Celsius: %.2f\n", result);
break;

case 2:
printf("Enter temperature in Celsius: ");
scanf("%f", &temperature);
result = celsiusToFahrenheit(temperature);
printf("Temperature in Fahrenheit: %.2f\n", result);
break;
default:
printf("Invalid choice. Please enter 1 or 2.\n");
break;
}
return 0;
}

Output:
e) Distance travelled by an object.
Calculate the distance travelled by an object using the formula: Distance = ut+(1/2)at2
Where:
u is the initial velocity (m/s),
t is the time (seconds),
a is the acceleration (m/s²).

FileName: Distance.C
#include <stdio.h>

// Function to calculate the distance traveled


float calculateDistance(float initialVelocity, float time, float acceleration)
{
return (initialVelocity * time) + (0.5 * acceleration * time * time);
}

int main()
{
float initialVelocity, time, acceleration, distance;

// Input values from the user


printf("Enter the initial velocity (m/s): ");
scanf("%f", &initialVelocity);
printf("Enter the time (seconds): ");
scanf("%f", &time);
printf("Enter the acceleration (m/s^2): ");
scanf("%f", &acceleration);

// Calculate the distance


distance = calculateDistance(initialVelocity, time, acceleration);

// Display the result


printf("The distance traveled by the object is: %.2f meters\n", distance);

return 0;
}

Input:

Output:
f) Calculate Simple interest and compound interest
Formulas to find interest:
Simple Interest = (P x T x R)/100
Compound Interest = P x (1+R/100)^T - P

FileName: Interest.C

#include <stdio.h>
#include <math.h> // Required for pow() function

// Function to calculate Simple Interest


float calculateSimpleInterest(float principal, float rate, float time)
{
return (principal * rate * time) / 100;
}

// Function to calculate Compound Interest


float calculateCompoundInterest(float principal, float rate, float time)
{
return principal * pow((1 + rate / 100), time) - principal;
}
int main()
{
float principal, rate, time, simpleInterest, compoundInterest;

// Input values from the user


printf("Enter the principal amount: ");
scanf("%f", &principal);
printf("Enter the rate of interest (in %% per annum): ");
scanf("%f", &rate);
printf("Enter the time (in years): ");
scanf("%f", &time);

// Calculate Simple Interest


simpleInterest = calculateSimpleInterest(principal, rate, time);

// Calculate Compound Interest


compoundInterest = calculateCompoundInterest(principal, rate, time);

// Display the results


printf("Simple Interest: %.2f\n", simpleInterest);
printf("Compound Interest: %.2f\n", compoundInterest);

return 0;
}
Input:

Output:
WEEK – 3 Date:

a) Evaluate the following expressions


i. a/b*c-b+a*d/3
ii. j = (i++) + (++i)

FileName: Expressions.C

#include <stdio.h>
int main()
{
// Variables for the first expression
int a, b, c, d, result1;

// Variables for the second expression


int i, j;

// Input values for the first expression


printf("Enter values for a, b, c, and d: ");
scanf("%d %d %d %d", &a, &b, &c, &d);

// Evaluate the first expression: a/b*c - b + a*d/3


result1 = a / b * c - b + a * d / 3;
printf("Result of expression (a/b*c - b + a*d/3): %d\n", result1);

// Input value for i in the second expression


printf("Enter value for i: ");
scanf("%d", &i);

// Evaluate the second expression: j = (i++) + (++i)


j = (i++) + (++i);

// Display the results


printf("Value of j after evaluating (i++) + (++i): %d\n", j);
printf("Final value of i: %d\n", i);
return 0;
}
Input:

Output:
b) Square root of a given number.

FileName: SquareRoot.C

#include<stdio.h>
#include<math.h>
int main()
{
int n;
double sq;
printf("Enter any number\n");
scanf("%d",&n);
sq=sqrt(n);
printf("Square Root of %d is: %.2lf",n,sq);
return 0;
}

Input:

Output:
c) Find the area of circle, square, rectangle and triangle.

FileName: Area.C

#include <stdio.h>
#include <math.h> // For using pow() and M_PI

// Function to calculate the area of a circle


float areaOfCircle(float radius)
{
return M_PI * pow(radius, 2); // M_PI is a constant for pi
}

// Function to calculate the area of a square


float areaOfSquare(float side)
{
return pow(side, 2);
}

// Function to calculate the area of a rectangle


float areaOfRectangle(float length, float width)
{
return length * width;
}

// Function to calculate the area of a triangle


float areaOfTriangle(float base, float height)
{
return 0.5 * base * height;
}

int main()
{
int choice;
float radius, side, length, width, base, height, area;

// Display menu for user selection


printf("Area Calculation Menu:\n");
printf("1. Circle\n");
printf("2. Square\n");
printf("3. Rectangle\n");
printf("4. Triangle\n");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);
// Calculate area based on user's choice
switch (choice)
{
case 1: // Circle
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = areaOfCircle(radius);
printf("Area of the circle: %.2f\n", area);
break;

case 2: // Square
printf("Enter the side of the square: ");
scanf("%f", &side);
area = areaOfSquare(side);
printf("Area of the square: %.2f\n", area);
break;

case 3: // Rectangle
printf("Enter the length and width of the rectangle: ");
scanf("%f %f", &length, &width);
area = areaOfRectangle(length, width);
printf("Area of the rectangle: %.2f\n", area);
break;

case 4: // Triangle
printf("Enter the base and height of the triangle: ");
scanf("%f %f", &base, &height);
area = areaOfTriangle(base, height);
printf("Area of the triangle: %.2f\n", area);
break;

default: // Invalid choice


printf("Invalid choice! Please select a valid option (1-4).\n");
}

return 0;
}
Input:

Output:
d) Find the maximum of three numbers using conditional operator.

FileName: BiggestofThreeNumbers.C

#include <stdio.h>
int main()
{
int num1, num2, num3, max;

// Input three numbers from the user


printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);

// Using the conditional operator to find the maximum


max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);

// Display the maximum number


printf("The maximum of the three numbers is: %d\n", max);

return 0;
}

Input:

Output:
e) Take marks of 5 subjects in integers, find the total in integer and average in float.

FileName: AverageMarks.C

#include <stdio.h>
int main()
{
int sub1, sub2, sub3, sub4, sub5, total;
float average;

// Input marks for 5 subjects


printf("Enter marks for subject 1: ");
scanf("%d", &sub1);
printf("Enter marks for subject 2: ");
scanf("%d", &sub2);
printf("Enter marks for subject 3: ");
scanf("%d", &sub3);
printf("Enter marks for subject 4: ");
scanf("%d", &sub4);
printf("Enter marks for subject 5: ");
scanf("%d", &sub5);

// Calculate total and average


total = sub1 + sub2 + sub3 + sub4 + sub5;
average = total / 5.0; // Ensure the division is performed in float

// Display the results


printf("\nTotal Marks: %d\n", total);
printf("Average Marks: %.2f\n", average);

return 0;
}

Input:

Output:
WEEK – 4 Date:

a) Conditional statements in C. Objective: Understand if and else.


https://www.hackerrank.com/challenges/conditional-statements inc/problem?isFullScreen=true

FileName: SimpleIfElse.C

#include<stdio.h>
int main()
{
int digit;
printf("Enter a digit:\n");
scanf("%d", &digit);
if (digit == 0)
{
printf("Zero ");
}
else if (digit == 1)
{
printf("One ");
}
else if (digit == 2)
{
printf("Two ");
}
else if (digit == 3)
{
printf("Three ");
}
else if (digit == 4)
{
printf("Four ");
}
else if (digit == 5)
{
printf("Five ");
}
else if (digit == 6)
{
printf("Six ");
}
else if (digit == 7)
{
printf("Seven ");
}
else if (digit == 8)
{
printf("Eight ");
}
else if (digit == 9)
{
printf("Nine ");
}
else
{
printf("Invalid Numebr\n");
}
return 0;
}

Input:

Output:
b) Roots of a Quadratic Equation.

FileName: RootsofQuadraticEquation.C
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, discriminant, root1, root2, realPart, imaginaryPart;

// Input coefficients
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);

if (a == 0)
{
printf("This is not a quadratic equation (a cannot be zero).\n");
return 0;
}

// Calculate the discriminant


discriminant = b * b - 4 * a * c;

// Check the nature of the discriminant


if (discriminant > 0)
{
// Two distinct real roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct:\n");
printf("Root 1 = %.2f\n", root1);
printf("Root 2 = %.2f\n", root2);
}
else if (discriminant == 0)
{
// One real root (double root)
root1 = -b / (2 * a);
printf("Roots are real and equal:\n");
printf("Root = %.2f\n", root1);
}
else
{
// Complex roots
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and imaginary:\n");
printf("Root 1 = %.2f + %.2fi\n", realPart, imaginaryPart);
printf("Root 2 = %.2f - %.2fi\n", realPart, imaginaryPart);
}
return 0;
}

Input:

Output:
c) Generate electricity bill based on the following information.

Input Format:
Customer ID, Name, and the number of units consumed are taken as input.

Rate Slabs:
Units <= 100: ₹1.50 per unit.
Units 101–300: ₹1.50 for the first 100 units + ₹2.00 per unit for the next 200 units.
Units > 300: ₹1.50 for the first 100 units + ₹2.00 for the next 200 units + ₹3.00 for units above
300.

Minimum Charge:
If the calculated bill amount is less than ₹50, it is set to ₹50.

Surcharge:
If the bill amount exceeds ₹500, a 20% surcharge is added to the total.

FileName: FindElectricityBill.C

#include <stdio.h>
int main()
{
int customerID;
char customerName[50];
float units, billAmount;

// Input customer details


printf("Enter Customer ID: ");
scanf("%d", &customerID);
printf("Enter Customer Name: ");
scanf("%s", customerName);
printf("Enter number of units consumed: ");
scanf("%f", &units);

// Calculate bill amount based on slab rates


if (units <= 100)
{
billAmount = units * 1.50;
}
else if (units <= 300)
{
billAmount = 100 * 1.50 + (units - 100) * 2.00;
}
else
{
billAmount = 100 * 1.50 + 200 * 2.00 + (units - 300) * 3.00;
}

// Add a minimum bill amount check


if (billAmount < 50)
{
billAmount = 50; // Minimum charge
}

// Add a surcharge if bill amount exceeds 500


if (billAmount > 500)
{
billAmount += billAmount * 0.20; // 20% surcharge
}

// Display the bill


printf("\nElectricity Bill\n");
printf("---------------------------\n");
printf("Customer ID : %d\n", customerID);
printf("Customer Name : %s\n", customerName);
printf("Units Consumed : %.2f\n", units);
printf("Total Bill Amount: Rs. %.2f\n", billAmount);

return 0;
}

Input:

Output:
d) Simulate a calculator using switch case.

FileName: SimpleCalculator.C

#include <stdio.h>
int main()
{
char operator;
double num1, num2, result;

// Input operator and numbers


printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator); // Space before %c ensures no issues with trailing characters
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);

// Perform calculation based on the operator


switch (operator)
{
case '+':
result = num1 + num2;
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;

case '-':
result = num1 - num2;
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;

case '*':
result = num1 * num2;
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;

case '/':
if (num2 != 0)
{
result = num1 / num2;
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
}
else
{
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operator. Please use +, -, *, or /.\n");
}
return 0;
}

Input:

Output:
e) Find the given year is a leap year or not.

FileName: LeapYear.C

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

// Input the year


printf("Enter a year: ");
scanf("%d", &year);

// Check if the year is a leap year


if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
printf("%d is a leap year.\n", year);
}
else
{
printf("%d is not a leap year.\n", year);
}

return 0;
}

Input:

Output:
WEEK – 5 Date:

a) Objective: Learn the usage of the for loop.


https://www.hackerrank.com/challenges/for-loop-in-c/problem?isFullScreen=true
Task: Program to complete the following task by using for loops.
For each integer n in the interval [a,b] (given as input) :
If 1<=n<=9, then print the English representation of it in lowercase.
That is "one" for 1, "two" for 2 , and so on.
Else if n>9 and it is an even number, then print "even".
Else if n>9 and it is an odd number, then print "odd".

Input
8
11

Output
eight
nine
even
odd

FileName: LoopDemo.C
#include <stdio.h>
int main()
{
int a, b;
scanf("%d\n%d", &a, &b);

for(int i=a;i<=b;i++)
{
if(i<=9)
{
switch(i)
{
case 1: printf("one\n");
break;
case 2: printf("two\n");
break;
case 3: printf("three\n");
break;
case 4: printf("four\n");
break;
case 5: printf("five\n");
break;
case 6: printf("six\n");
break;
case 7: printf("seven\n");
break;
case 8: printf("eight\n");
break;
case 9: printf("nine\n");
break;
}
}
else
{
if(i%2==0)
printf("even\n");
else
printf("odd\n");
}
}
return 0;
}

Input:

Output:
b) Sum of the digits of a 5-digit number.
Objective: Learn the usage of while loop and usage of operators - % and /.
https://www.hackerrank.com/challenges/sum-of-digits-of-a-five-
digitnumber/problem?isFullScreen=true

FileName: SumofDigits.C
#include<stdio.h>
int digits_Sum(int); //function prototype
int main()
{
int n,sum;
scanf("%d",&n);
sum=digits_Sum(n);
printf("Sum of the digits of a given number %d is %d",n,sum);
return 0;
}
int digits_Sum(int m)
{
int s=0,rem;
while(m>0)
{
rem=m%10;
s=s+rem;
m=m/10;
}
return s;
}

Input:

Output:
c) i. Program to find the given number is a prime or not.

FileName: PrimeorNot.C

#include<stdio.h>
int findFactors(int); //function prototype
int main()
{
int n;
scanf("%d",&n);
int fact_count=findFactors(n);
printf("\nFactors of given number %d is: %d\n",n,fact_count);
if(fact_count==2)
{
printf("Given number %d is PRIME NUMBER",n);
}
else
{
printf("Given number %d is NOT A PRIME NUMBER",n);
}
return 0;
}
int findFactors(int m)
{
int count=2,i;
printf("1 ");
for(i=2;i<=m/2;i++)
{
if(m%i==0)
{
count++;
}
}
printf("%d\n",m);
return count;
}

Input:

Output:
c) ii. Program to print the prime numbers between a given range.

FileName: PrimeNumbers.C

#include<stdio.h>
int findFactors(int);
int main()
{
int x,y,i;
scanf("%d%d",&x,&y);
for(i=x;i<=y;i++)
{
int fact_count=findFactors(i);
if(fact_count==2)
printf("%d ",i);
}
return 0;
}
int findFactors(int m)
{
int count=2,i;
for(i=2;i<=m/2;i++)
{
if(m%i==0)
{
count++;
}
}
return count;
}

Input:

Output:
d) Program to find the given number is Armstrong Number or not.

FileName: Armstrong.C
Armstrong number: A number that is equal to the sum of its own digits raised to the power of
the number of digits is called Armstrong Number.
Examples:
153 => 1^3 + 5^3 + 3^3 => 1+125+27 => 153
371 => 3^3 + 7^3 + 1^3 => 27 + 343 + 1 => 371
9 => 9^1 => 9
1634 => 1^4 + 6^4 + 3^4 + 4^4 => 1634

#include<stdio.h>
#include<math.h>
int findArmStrongCalculation(int); //function prototype
int main()
{
int n,res;
scanf("%d",&n);
res=findArmStrongCalculation(n);
if(n==res)
printf("Given Number %d is Armstrong Number",n);
else
printf("Given Number %d is Not a Armstrong Number",n);
return 0;
}
int findArmStrongCalculation(int n)
{
int digits=(int)log10(n)+1;
int rem,sum=0;
while(n>0)
{
rem=n%10;
sum=sum+(int)pow(rem,digits);
n=n/10;
}
return sum;
}

Input:

Output:
e) Program to find the given number is Palindrome or not.

FileName: Palindrome.C

#include <stdio.h>
int main()
{
int num, originalNum, reversedNum = 0, remainder;

// Input the number


printf("Enter a number: ");
scanf("%d", &num);

// Store the original number


originalNum = num;

// Reverse the number


while (num != 0)
{
remainder = num % 10; // Extract the last digit
reversedNum = reversedNum * 10 + remainder; // Build the reversed number
num /= 10; // Remove the last digit
}

// Check if the original number and reversed number are the same
if (originalNum == reversedNum)
{
printf("%d is a palindrome.\n", originalNum);
}
else
{
printf("%d is not a palindrome.\n", originalNum);
}
return 0;
}

Input:

Output:
f) Printing patterns using Loops. Objective: Print a pattern of numbers.
https://www.hackerrank.com/challenges/printing-pattern2/problem?isFullScreen=true

FileName:PatternDemo.C

#include <stdio.h>
#include <string.h>

int main()
{
int n,i,j;
scanf("%d", &n);

int len = 2*n - 1;


for (i = 0; i < len; i++)
{
for (j = 0; j < len; j++)
{
int min = i < j ? i : j;
min = min < len-i ? min : len-i-1;
min = min < len-j-1 ? min : len-j-1;
printf("%d ", n-min);
}
printf("\n");
}

return 0;
}

Input:

Output:
g) Construct a Pyramid pattern.

FileName: PyramidPattern.C

#include <stdio.h>
int main()
{
int n, i, j;

// Input the height of the pyramid


printf("Enter the number of rows:\n");
scanf("%d", &n);

// Outer loop to handle the number of rows (height of the pyramid)


for (i = 1; i <= n; i++)
{
// Loop for spaces before the numbers
for (j = 1; j <= n - i; j++)
{
printf(" ");
}

// Loop for printing numbers in the pyramid


for (j = 1; j <= (2 * i - 1); j++)
{
printf("%d", i);
}

// Move to the next line after printing each row


printf("\n");
}
return 0;
}

Input:

Output:
WEEK – 6 Date:
a) 1D Arrays in C Objective: Print the sum and free the memory where the array is stored.
https://www.hackerrank.com/challenges/1d-arrays-in-c/problem?isFullScreen=true

FileName: ArrayDemo1.C

#include <stdio.h>

int main()
{
int n;
scanf("%d", &n);

int arr[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
}
printf("%d", sum);
return 0;
}

Input:

Output:
b) Array reversal Objective: Working with indices in array
https://www.hackerrank.com/challenges/reverse-array-c/problem?isFullScreen=true

FileName: ReverseArray.C

#include <stdio.h>
void reverseArray(int [],int); //function prototype
void reverseArray(int arr[], int size) //function Definition
{
int i;
for(i=0;i<size/2;i++)
{
// Swap the elements
int temp=arr[i];
arr[i]=arr[size-i-1];
arr[size-i-1]=temp;
}
}

int main()
{
int size;

printf("Enter the size of the array: ");


scanf("%d", &size);

int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}

reverseArray(arr, size); //function call

printf("Reversed array:\n");
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}
Input:

Output:
c) Search an element in array (Linear Search)

FileName: LinearSearch.C

#include <stdio.h>
Int linearSearch(int[],int,int); //function prototype
// Function to perform linear search
int linearSearch(int arr[], int size, int target) //function definition
{
for (int i = 0; i < size; i++)
{
if (arr[i] == target) {
return i; // Return the index if the element is found
}
}
return -1; // Return -1 if the element is not found
}
int main()
{
int size, target, result;

printf("Enter the size of the array: ");


scanf("%d", &size);

int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the element to search for: ");


scanf("%d", &target);

result = linearSearch(arr, size, target); //function call

if (result != -1)
{
printf("Element found at index %d.\n", result);
}
else
{
printf("Element not found in the array.\n");
}
return 0;
}
Input:

Output:
d) Find min and max elements in array

FileName: FindMinandMax.C

#include <stdio.h>
Int findMin(int[],int);
Int findMax(int[],int);

// Function to find the minimum element


int findMin(int arr[], int size)
{
int min = arr[0]; // Initialize min with the first element
for (int i = 1; i < size; i++)
{
if (arr[i] < min)
{
min = arr[i];
}
}
return min;
}

// Function to find the maximum element


int findMax(int arr[], int size)
{
int max = arr[0]; // Initialize max with the first element
for (int i = 1; i < size; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
return max;
}

int main()
{
int size;

printf("Enter the size of the array: ");


scanf("%d", &size);
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}

int min = findMin(arr, size);


int max = findMax(arr, size);

printf("Minimum element: %d\n", min);


printf("Maximum element: %d\n", max);

return 0;
}

Input:

Output:
e) Insert an element into array

FileName: ElementInsertion.C

#include <stdio.h>

int main()
{
int size, position, element;

printf("Enter the size of the array: ");


scanf("%d", &size);

int arr[size + 1]; // Extra space for the new element

printf("Enter %d elements:\n", size);


for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}

printf("Enter the element to insert: ");


scanf("%d", &element);

printf("Enter the index position to insert the element (0 to %d): ", size);
scanf("%d", &position);

// Check if the position is valid


if (position < 0 || position > size)
{
printf("Invalid position!\n");
return 1;
}

// Shift elements to the right to make space for the new element
for (int i = size; i > position; i--)
{
arr[i] = arr[i - 1];
}

// Insert the new element


arr[position] = element;
printf("Array after insertion:\n");
for (int i = 0; i <= size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Input:

Output:
f) Eliminate duplicate elements from array

FileName: RemoveDuplicate.C

#include<stdio.h>
int main()
{
int n,i,j=1,k,available=0;
printf("Enter the size of an array\n");
scanf("%d",&n);

int arr[n];
for(i=0;i<n;i++)
scanf("%d",&arr[i]);

int temp[n];
temp[0]=arr[0];

for(i=1;i<n;i++)
{
available=0;
for(k=0;k<j;k++)
{
if(arr[i]==temp[k])
{
available=1;
break;
}
}
if(available==0)
{
temp[j]=arr[i];
j++;
}
}
printf("Elements in the given array\n");
for(i=0;i<n;i++)
printf("%d ",arr[i]);

printf("\nElements after removing of duplicate elements\n");


for(i=0;i<j;i++)
printf("%d ",temp[i]);
return 0;
}
Input:

Output:
g) Sorting of elements in an array using Bubble sort

FileName: BubbleSort.C
#include <stdio.h>
void bubbleSort(int[],int); //function declaration

// Function to perform Bubble Sort


void bubbleSort(int arr[], int size) //function definition
{
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to print the array
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}

int main()
{
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);

int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
bubbleSort(arr, size); // Sorting the array

printf("Sorted array:\n");
printArray(arr, size); // Printing the sorted array

return 0;
}

Input:

Output:
WEEK – 7 Date:
a) Sum of two 2-D arrays

FileName: SumofArrays.C

#include<stdio.h>
void addMatrix(int rows,int cols,int M1[rows][cols],int M2[rows][cols]);
void printMatrix(int rows,int cols,int M[rows][cols]);
int main()
{
int rows,cols,i,j;
scanf("%d%d",&rows,&cols);
int M1[rows][cols],M2[rows][cols],M3[rows][cols];
printf("Enter the %d Elements for Matrix-A\n",rows*cols);
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf("%d",&M1[i][j]);
}
}
printf("Enter the %d Elements for Matrix-B\n",rows*cols);
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf("%d",&M2[i][j]);
}
}
printf("\nMatrix M1 is:\n");
printMatrix(rows,cols,M1);

printf("\nMatrix M2 is:\n");
printMatrix(rows,cols,M2);

printf(“\nAddition of M1 and M2 Matrix is:\n”);


addMatrix(rows,cols,M1,M2);

return 0;
}
void addMatrix(int rows,int cols,int M1[rows][cols],int M2[rows][cols])
{
int i,j;
int M3[rows][cols];
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
M3[i][j]=M1[i][j]+M2[i][j];
}
}
printMatrix(rows,cols,M3);
}

void printMatrix(int rows,int cols,int M[rows][cols])


{
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%d ",M[i][j]);
}
printf("\n");
}
}

Input:

Output:
b) Multiplication of two 2-D arrays

FileName: Multiplication.C
#include<stdio.h>

void multiplyMatrices(int rows1,int cols1,int rows2,int cols2,int mat1[rows1][cols1],int


mat2[rows2][cols2])
{
int result[rows1][cols2],i,j,k;
for(i= 0; i<rows1; i++)
{
for(j = 0; j < cols2; j++)
{
result[i][j] = 0;
for(k = 0; k < cols1; k++)
{
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
printf("Product of the matrices:\n");
printMatrix(rows1, cols2, result);
}

void printMatrix(int rows, int cols, int mat[rows][cols])


{
int i,j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
int main()
{
int rows1, cols1, rows2, cols2,i,j;

printf("Enter the number of rows and columns for the first matrix: \n");
scanf("%d %d", &rows1, &cols1);

printf("Enter the number of rows and columns for the second matrix: \n");
scanf("%d %d", &rows2, &cols2);
int mat1[rows1][cols1], mat2[rows2][cols2];
if (cols1 != rows2)
{
printf("Matrix multiplication not possible. Number of columns in the first matrix must equal
the number of rows in the second matrix.\n");
return 1;
}

printf("Enter elements of the first matrix:\n");


for (i = 0; i < rows1; i++)
{
for (j = 0; j < cols1; j++)
{
scanf("%d", &mat1[i][j]);
}
}

printf("Enter elements of the second matrix:\n");


for (i = 0; i < rows2; i++)
{
for (j = 0; j < cols2; j++)
{
scanf("%d", &mat2[i][j]);
}
}
printf("Matrix - A\n");
printMatrix(rows1,cols1,mat1);
printf("Matrix - B\n");
printMatrix(rows2,cols2,mat2);
multiplyMatrices(rows1,cols1,rows2,cols2,mat1, mat2);

return 0;
}
Input:

Output:
c) Transpose of a Matrix

FileName: Transpose.C

#include<stdio.h>
void displayMatrix(int rows,int cols,int matrix[rows][cols]);
void findTranspose(int rows,int cols,int matrix[rows][cols]);

int main()
{
int rows,cols,i,j;
scanf("%d%d",&rows,&cols);
int A[rows][cols];
printf("Enter the %d elements\n",(rows*cols));
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("Given Matrix A is:\n");
displayMatrix(rows,cols,A);
findTranspose(rows,cols,A);
return 0;
}
void displayMatrix(int rows,int cols,int Matrix[rows][cols])
{
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%d ",Matrix[i][j]);
}
printf("\n");
}
}
void findTranspose(int rows,int cols,int Matrix[rows][cols])
{
int T[cols][rows],i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
T[j][i]=Matrix[i][j];
}
}
printf("Transpose of a Given Matrix A is:\n");
displayMatrix(cols,rows,T);
}

Input:

Output:
d) Trace of a Matrix

FileName: TraceofMatrix.C

#include <stdio.h>

// Function to calculate the trace of a square matrix


int calculateTrace(int size,int mat[size][size])
{
int trace = 0;
for (int i = 0; i < size; i++)
{
trace += mat[i][i]; // Sum of diagonal elements
}
return trace;
}

int main()
{
int size;
printf("Enter the size of the square matrix: ");
scanf("%d", &size);

int size, mat[size][size];

printf("Enter the elements of the matrix:\n");


for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
scanf("%d", &mat[i][j]);
}
}
int trace = calculateTrace(size,mat); // Calculate trace

printf("Trace of the matrix: %d\n", trace);

return 0;
}
Input:

Output:
e) Print the Lower Triangular Matrix

FileName: LowerTriangularMatrix.C

#include <stdio.h>
// Function to print the lower triangular matrix
void printLowerTriangular(int rows, int cols,int mat[rows][cols])
{
int i,j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
if (j <= i)
{
printf("%d ", mat[i][j]); // Print element if j <= i
}
else
{
printf("0 "); // Print 0 otherwise
}
}
printf("\n");
}
}
int main()
{
int rows, cols;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);

int mat[rows][cols],i,j;
printf("Enter the elements of the matrix:\n");
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
scanf("%d", &mat[i][j]);
}
}
printf("Lower triangular matrix:\n");
printLowerTriangular(rows, cols,mat);

return 0;
}
Input:

Output:
WEEK – 8 Date:

a) Printing Tokens Objective: print each word of the sentence in a new line
https://www.hackerrank.com/challenges/printing-tokens- /problem?isFullScreen=true

FileName:StringDemo.C

#include<stdio.h>
int main()
{
char sentance[100];
printf("Enter a line of Text\n");
scanf("%[^\n]s",sentance);

int i;
for(i=0; sentance[i]!='\0';i++)
{
if(sentance[i]==' ')
printf("\n");
else
printf("%c",sentance[i]);
}
return 0;
}

Input:

Output:
b) i. Count number of alphabets (lowercase, uppercase, consonants, vowels) and digits

FileName: CountofChars.C

#include<stdio.h>
int main()
{
char str[100];
int i;
int digits=0,lowercase=0,uppercase=0,vowels=0,consonants=0;
printf("Enter a line of Text\n");
scanf("%[^\n]s",str);
for(i = 0; str[i] != '\0'; i++)
{
char ch = str[i];

if (ch>='0' && ch<='9')


{
digits++;
}
else if(ch>='A' && ch<='Z')
{
uppercase++;
}
else if(ch>='a' && ch<='z')
{
lowercase++;
}
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
vowels++;
}
else
{
consonants++;
}
}
printf("Lowercase letters: %d\n", lowercase);
printf("Uppercase letters: %d\n", uppercase);
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
printf("Digits: %d\n", digits);
return 0;
}
Input:

Output:
b) ii. Lowercase to Uppercase, Uppercase to Lowercase, Toggle case, Sentential case

FileName:CountofCases.C

#include<stdio.h>
int main()
{
char str[30];
int i;

printf("Enter a String\n");
scanf("%[^\n]s",str);

printf("Conversion to Lower Case:\n");


for(i=0;str[i]!='\0';i++)
{
if(str[i]>='A' && str[i]<='Z')
printf("%c",(char)str[i]+32);
else
printf("%c",str[i]);
}

printf("\nConversion to Upper Case:\n");


for(i=0;str[i]!='\0';i++)
{
if(str[i]>='a' && str[i]<='z')
printf("%c",(char)str[i]-32);
else
printf("%c",str[i]);
}

printf("\nConversion to Toggle Case:\n");


for(i=0;str[i]!='\0';i++)
{
if(str[i]>='A' && str[i]<='Z')
printf("%c",(char)str[i]+32);
else if(str[i]>='a' && str[i]<='z')
printf("%c",(char)str[i]-32);
else
printf("%c",str[i]);
}
printf("\nConversion to Sentential Case:\n");

int newSentence = 1;
for (i = 0; str[i] != '\0'; i++)
{
char ch = str[i];
if (ch >= 'a' && ch <= 'z')
{
if (newSentence)
{
str[i] = ch - 32;
newSentence = 0;
}
}
else if (ch >= 'A' && ch <= 'Z')
{
if (!newSentence)
{
str[i] = ch + 32;
}
}

if (ch == '.' || ch == '!' || ch == '?'|| ch==' ')


{
newSentence = 1;
}
}
printf("%s",str);
return 0;
}

Input:

Output:
c) Digit Frequency Objective: find the frequency of each digit in the given string.
https://www.hackerrank.com/challenges/frequency-of-digits1/problem?isFullScreen=true

FileName: DigitFrequency.C

#include<stdio.h>
int main()
{
char s[30];
int i;
int digits_count[10]={0};
printf("Enter any String\n");
gets(s);
for(i=0;s[i]!='\0';i++)
{
digits_count[s[i]-'0']++;
}
printf("Digits Count:\n");
for(i=0;i<10;i++)
{
if(digits_count[i]!=0)
printf("%d -> %d\n",i,digits_count[i]);
}
return 0;
}

Input:

Output:
d) Find string length, concatenate 2 strings, reverse a string using built-in and without
built-in string functions.

FileName:StringOperations.C

a) Without String functions


#include <stdio.h>

// Function to find the length of the string


int stringLength(char str[])
{
int length = 0;
while (str[length] != '\0')
{
length++;
}
return length;
}

// Function to concatenate two strings


void stringConcatenate(char str1[], char str2[], char result[])
{
int i = 0, j = 0;

// Copy first string to result


while (str1[i] != '\0')
{
result[i] = str1[i];
i++;
}

// Append second string to result


while (str2[j] != '\0')
{
result[i] = str2[j];
i++;
j++;
}
result[i] = '\0'; // Null-terminate the result
}
// Function to reverse a string
void stringReverse(char str[])
{
int length = stringLength(str);
for (int i = 0; i < length / 2; i++)
{
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}

int main()
{
char str1[100], str2[100], concat[200];

// Input first string


printf("Enter the first string:\n");
scanf("%s",str1);

// Input second string


printf("Enter the second string:\n");
scanf("%s",str2);

// Find string length


printf("Length of the first string: %d\n", stringLength(str1));

// Concatenate strings
stringConcatenate(str1, str2, concat);
printf("Concatenated string: %s\n", concat);

// Reverse the first string


stringReverse(str1);
printf("Reversed first string: %s\n", str1);
return 0;
}

Input:

Output:
b) With String functions:

#include<stdio.h>
#include<string.h>
int main()
{
char str1[100], str2[100];

printf("Enter the first string: ");


scanf("%s",str1);

printf("Enter the second string: ");


scanf("%s",str2);

// Find string length


printf("Length of the first string: %d\n", strlen(str1));

// Concatenate strings
strcat(str1, str2);
printf("Concatenated string: %s\n",str1);

// Reverse the second string


strrev(str2);
printf("Reversed first string: %s\n", str2);

return 0;
}

Input:

Output:
WEEK – 9 Date:

a) Objective: Learn simple usage of functions.


https://www.hackerrank.com/challenges/functions-in-c/problem?isFullScreen=true

FileName:FunctionDemo.C
#include <stdio.h>
int max(int x,int y)
{
if(x>y)
return x;
else
return y;
}
int max_of_four(int p,int q,int r,int s)
{
return max(p,max(q,max(r,s)));
}
int main()
{
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
Input: Output:
b) Fibonacci Numbers
Objective: Complete the recursive function.
https://www.hackerrank.com/challenges/ctci-fibonacci-numbers/problem

FileName: Fibonacci.C

#include <stdio.h>
int fibonacci(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
return fibonacci(n-1)+fibonacci(n-2);
}

int main()
{
int n;
scanf("%d", &n);
printf("%d", fibonacci(n));
return 0;
}

Input:

Output:
c) Factorial
Objective: N! (N factorial) using recursion.
https://www.hackerrank.com/contests/ccc-veltech-practice-setende/challenges/factorial-
using-recursion-1

FileName: Factorial.C

#include <stdio.h>

// Function to calculate factorial using recursion


int factorial(int n)
{
if (n == 0 || n == 1)
{
return 1; // Base case: factorial of 0 or 1 is 1
}
else
{
return n * factorial(n - 1); // Recursive case
}
}

int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d is %d\n", num, factorial(num));
}

return 0;
}

Input:

Output:
d) Digit Sum
Objective: find the super digit of the integer.
https://www.hackerrank.com/challenges/recursive-digit-sum/problem

FileName:DigitSum.C

#include <stdio.h>

// Function to calculate the sum of digits using recursion


int digitSum(int n)
{
if (n == 0)
{
return 0; // Base case
}
else
{
return (n % 10) + digitSum(n / 10); // Recursive case
}
}

// Function to reduce the sum to a single digit using recursion


int singleDigitSum(int n)
{
int sum = digitSum(n);
if (sum < 10)
{
return sum; // Base case: if sum is already a single digit
} else {
return singleDigitSum(sum); // Recursive case: call again with the new sum
}
}
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num < 0)
{
num = -num; // Handle negative numbers
}

printf("Single digit sum is %d\n", singleDigitSum(num));

return 0;
}

Input:

Output:
e) Program to Calculate LCM

FileName: LCM.C

#include <stdio.h>

// Function to calculate GCD using the Euclidean algorithm


int gcd(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}

// Function to calculate LCM


int lcm(int a, int b)
{
return (a * b) / gcd(a, b); // LCM formula
}

int main()
{
int num1, num2, result;

printf("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

result = lcm(num1, num2);

printf("LCM of %d and %d is %d\n", num1, num2, result);

return 0;
}

Input:

Output:
f) Calculate the Nth term Objective: Find the Nth term.
https://www.hackerrank.com/challenges/recursion-in-c/problem?isFullScreen=true

FileName: NthTerm.C
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
int find_nth_term(int n, int a, int b, int c)
{
//Write your code here.
if(n==1)
return a;
else if(n==2)
return b;
else if(n==3)
return c;
else
return find_nth_term(n-1,a,b,c)+find_nth_term(n-2,a,b,c)+find_nth_term(n-3,a,b,c);
}
int main()
{
int n, a, b, c;

scanf("%d %d %d %d", &n, &a, &b, &c);


int ans = find_nth_term(n, a, b, c);

printf("%d", ans);
return 0;
}

Input:

Output:
WEEK – 10 Date:

a) Pointers in C
Objective: learn to implement the basic functionalities of pointers in C.
https://www.hackerrank.com/challenges/pointer-in-c/problem?isFullScreen=true

FileName: PointerDemo.C

#include <stdio.h>
#include<math.h>
void update(int *a,int *b)
{
// Complete this function
int t1=*a + *b;
int t2=abs(*a - *b);
*a=t1;
*b=t2;
}

int main()
{
int a, b;
int *pa = &a, *pb = &b;

scanf("%d %d", &a, &b);


update(pa, pb);
printf("%d\n%d", a, b);

return 0;
}

Input
4
5

Output
9
1

Explanation
4+5 => 9
|4-5| => 1
b) Students Marks Sum
Objective: Learn using Pointers with Arrays and Functions
https://www.hackerrank.com/challenges/students-markssum/problem?isFullScreen=true

FileName:ArraysSum.C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int marks_summation(int* marks, int number_of_students, char gender)


{
//Write your code here.
int sum=0,i;
if(gender=='b')
{
i=0;
}
else
{
i=1;
}
while(i<number_of_students)
{
sum=sum+*(marks+i);
i=i+2;
}
return sum;
}

int main()
{
int number_of_students,i;
char gender;
int sum;

scanf("%d", &number_of_students);
int *marks = (int *) malloc(number_of_students * sizeof (int));

for (i = 0; i < number_of_students; i++)


{
scanf("%d", (marks + i));
}

scanf(" %c", &gender);


sum = marks_summation(marks, number_of_students, gender);
printf("%d", sum);
free(marks);

return 0;
}

Input:

Output:
c) Sorting Array of Strings
Objective: sort a given array of strings into lexicographically increasing order or into an order
in which the string with the lowest length appears first.
https://www.hackerrank.com/challenges/sorting-array-ofstrings/problem?isFullScreen=true

FileName: StringSorting.C

#include <stdio.h>
#include <string.h>

#define MAX_STRINGS 100 // Maximum number of strings


#define MAX_LENGTH 100 // Maximum length of each string

// Function to sort an array of strings


void sortStrings(char arr[][MAX_LENGTH], int n)
{
char temp[MAX_LENGTH]; // Temporary string for swapping
int i,j;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (strcmp(arr[j], arr[j + 1]) > 0)
{
// Swap strings if arr[j] is greater than arr[j + 1]
strcpy(temp, arr[j]);
strcpy(arr[j], arr[j + 1]);
strcpy(arr[j + 1], temp);
}
}
}
}
int main()
{
char arr[MAX_STRINGS][MAX_LENGTH];
int n,i;

printf("Enter the number of strings: ");


scanf("%d", &n);

printf("Enter %d strings:\n", n);


for (i = 0; i < n; i++)
{
scanf("%s",&arr[i]);
}
sortStrings(arr, n);

printf("\nSorted strings:\n");
for (i = 0; i < n; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}

Input:

Output:
d) Find the sum of a 1D array using malloc()

FileName: ArraySum.C

#include <stdio.h>
#include <stdlib.h> // For malloc() and free()
int main()
{
int n, i, sum = 0;
int *arr;

printf("Enter the number of elements: ");


scanf("%d", &n);

// Allocate memory for n integers


arr = (int *)malloc(n * sizeof(int));

// Check if memory allocation was successful


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

// Input elements into the array


printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", arr+i);
}

// Calculate the sum of the array elements


for (i = 0; i < n; i++)
{
sum += *(arr+i);
}

printf("Sum of the array elements: %d\n", sum);

// Free the allocated memory


free(arr);

return 0;
}
Input:

Output:
e) Swap two numbers using functions and pointers - call by value and reference.

FileName: Swapping.C

1. Swapping Using Call by Value


In this case, the values are swapped inside the function, but the changes do not affect the
original variables.

#include <stdio.h>

void swap(int a, int b)


{
int temp = a;
a = b;
b = temp;
}

int main()
{
int x = 5, y = 10;
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(x, y); // Passing by value
printf("After swapping: x = %d, y = %d\n", x, y); // No change in x and y
return 0;
}

Output:
2. Swapping Using Call by Reference
In this case, pointers are used, and the changes reflect in the original variables.

#include <stdio.h>
void swap(int*,int*); //function prototype
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

int main()
{
int x = 5, y = 10;
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(&x, &y); // Passing by reference
printf("After swapping: x = %d, y = %d\n", x, y); // x and y are swapped
return 0;
}

Output:
f) Dynamic Array in C
Objective: Handling requests by a Librarian to place the books in the shelves.
https://www.hackerrank.com/challenges/dynamic-array-inc/problem?isFullScreen=true

FileName:DynamicArray.C

#include <stdio.h>
#include <stdlib.h>
int main()
{
int numShelves, queries;

// Input the number of shelves and queries


printf("Enter number of shelves and queries: ");
scanf("%d %d", &numShelves, &queries);

// Dynamic arrays for the shelves


int *totalBooks = (int *)calloc(numShelves, sizeof(int)); // To store the number of books on each shelf
int **bookPages = (int **)malloc(numShelves * sizeof(int *)); // To store the pages of each book

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


bookPages[i] = NULL; // Initialize pointers to NULL
}

for (int q = 0; q < queries; q++) {


int type;
printf("Enter query type (1, 2, or 3): ");
scanf("%d", &type);

if (type == 1) {
int shelf, pages;
printf("Enter shelf and pages: ");
scanf("%d %d", &shelf, &pages);

// Add a book with the specified number of pages to the shelf


totalBooks[shelf]++;
bookPages[shelf] = (int *)realloc(bookPages[shelf], totalBooks[shelf] * sizeof(int));
bookPages[shelf][totalBooks[shelf] - 1] = pages;

} else if (type == 2) {
int shelf, bookIndex;
printf("Enter shelf and book index: ");
scanf("%d %d", &shelf, &bookIndex);

// Print the number of pages in the specified book


printf("Pages: %d\n", bookPages[shelf][bookIndex]);

} else if (type == 3) {
int shelf;
printf("Enter shelf number: ");
scanf("%d", &shelf);

// Print the total number of books on the specified shelf


printf("Total books on shelf %d: %d\n", shelf, totalBooks[shelf]);
}
}

// Free the allocated memory


for (int i = 0; i < numShelves; i++) {
free(bookPages[i]);
}
free(bookPages);
free(totalBooks);
return 0;
}
Input:

Output:
WEEK – 11 & 12 Date:
File handling concepts
a) Write text into and read text from a file.
FileName: FileRead.C

#include <stdio.h>
int main()
{
FILE *file;
char textToWrite[] = "Hello, this is some text.";
char buffer[100];
// Writing text to a file
file = fopen("example.txt", "w");
if (file == NULL)
{
perror("Error opening file for writing");
return 1;
}
fprintf(file, "%s", textToWrite);
fclose(file);

// Reading text from a file


file = fopen("example.txt", "r");
if (file == NULL)
{
perror("Error opening file for reading");
return 1;
}
fgets(buffer, sizeof(buffer), file);
fclose(file);

// Print the read text


printf("Read from file: %s\n", buffer);
return 0;
}

Output:
b) Write text into and read text from a binary file using fread() and fwrite().
FileName: BinaryFileRead.c

#include <stdio.h>
int main()
{
FILE *sourceFile, *destinationFile;
char buffer[1024]; // Buffer to store data
// Open the source file for reading in binary mode
sourceFile = fopen("source.txt", "rb");
if (sourceFile == NULL)
{
perror("Error opening source file");
return 1;
}
// Open the destination file for writing in binary mode
destinationFile = fopen("destination.txt", "wb");
if (destinationFile == NULL)
{
perror("Error opening destination file");
fclose(sourceFile);
return 1;
}
// Copy the contents of the source file to the destination file
size_t bytesRead;
while ((bytesRead = fread(buffer, 1, sizeof(buffer), sourceFile)) > 0)
{
fwrite(buffer, 1, bytesRead, destinationFile);
}
fclose(sourceFile);
fclose(destinationFile);
return 0;
}
Output:
c) Copy the contents of one file to another file.
FileName: FileCopy.c
#include <stdio.h>
int main()
{
FILE *sourceFile, *destinationFile;
char ch;
// Open the source file for reading
sourceFile = fopen("input.txt", "r");
if (sourceFile == NULL)
{
perror("Error opening source file");
return 1;
}
// Open the destination file for writing
destinationFile = fopen("output.txt", "w");
if (destinationFile == NULL)
{
perror("Error opening destination file");
fclose(sourceFile);
return 1;
}
// Copy contents from source to destination
while ((ch = fgetc(sourceFile)) != EOF)
{
fputc(ch, destinationFile);
}
// Close the files
fclose(sourceFile);
fclose(destinationFile);
printf("File copied successfully.\n");
return 0;
}
Output:
d) Merge two files into the third file using command-line arguments
FileName: MergeFiles.C

#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc != 4)
{
printf("Usage: %s source1.txt source2.txt destination.txt\n", argv[0]);
return 1;
}
FILE *sourceFile1, *sourceFile2, *destinationFile;
char ch;
// Open the first source file for reading
sourceFile1 = fopen(argv[1], "r");
if (sourceFile1 == NULL)
{
perror("Error opening first source file");
return 2;
}
// Open the second source file for reading
sourceFile2 = fopen(argv[2], "r");
if (sourceFile2 == NULL)
{
perror("Error opening second source file");
fclose(sourceFile1);
return 3;
}
// Open the destination file for writing
destinationFile = fopen(argv[3], "w");
if (destinationFile == NULL)
{
perror("Error opening destination file");
fclose(sourceFile1);
fclose(sourceFile2);
return 4;
}
}
Output:
e) Find no. of lines, words and characters in a file.
FileName: FileCharacterCount.C

#include <stdio.h>
#include <ctype.h>

int main()
{
const char *filePath = "example.txt"; // File path
FILE *file = fopen(filePath, "r"); // Open file in read mode

if (file == NULL)
{
printf("Error opening file!\n");
return 1;
}

int lines = 0, words = 0, characters = 0;


char ch;
int inWord = 0; // Flag to track if we are inside a word

while ((ch = fgetc(file)) != EOF)


{
characters++; // Increment character count

// Check for new line


if (ch == '\n')
{
lines++;
}

// Check for word boundaries


if (isspace(ch))
{
if (inWord)
{
words++; // Increment word count
inWord = 0;
}
}
else
{
inWord = 1; // Inside a word
}
}
// Increment word count if the file doesn't end with a space/newline
if (inWord)
{
words++;
}

// Close the file


fclose(file);

// Output the counts


printf("Lines: %d\n", lines);
printf("Words: %d\n", words);
printf("Characters: %d\n", characters);

return 0;
}

Output:
Week-13
Augmented Experiments
(a) Variadic functions in C
Objective: Understanding variable number of arguments
https://www.hackerrank.com/challenges/variadic-functions-inc/problem?isFullScreen=true

FileName: Variadic.C
#include <stdio.h>
#include <stdarg.h>
// Function to find the average of a variable number of integers
double findAverage(int num, ...)
{
va_list args;
va_start(args, num);
double sum = 0;
for (int i = 0; i < num; i++)
{
sum += va_arg(args, int);
}
va_end(args);
return sum / num;
}
int main() {
// Example usage of the variadic function
double average1 = findAverage(3, 10, 20, 30);
double average2 = findAverage(2, 10, 20);
double average3 = findAverage(6, 100, 200, 300, 400, 500, 600);
printf("Average: %.2f\n", average1);
printf("Average: %.2f\n", average2);
printf("Average: %.2f", average3);
return 0;
}

Output:
(b) Small triangles, Large Triangles
Objective: Print sorted by their areas
https://www.hackerrank.com/challenges/small-triangles-
largetriangles/problem?isFullScreen=true
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct triangle
{
int a;
int b;
int c;
};
typedef struct triangle triangle;
void sort_by_area(triangle* tr, int n)
{
/**
* Sort an array a of the length n
*/
float areas[n];
for (int i = 0; i < n; i++)
{
float p = (tr[i].a + tr[i].b + tr[i].c) / 2.0;
areas[i] = sqrt(p * (p - tr[i].a) * (p - tr[i].b) * (p - tr[i].c));
}
// Applying bubble sort
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (areas[j] > areas[j + 1]) {
// swapping area
float t = areas[j];
areas[j] = areas[j + 1];
areas[j + 1] = t;

// swapping triangles too


triangle temp = tr[j];
tr[j] = tr[j + 1];
tr[j + 1] = temp;
}
}
}
}
int main()
{
int n, i;
printf("Enter number of triangles: ");
scanf("%d", &n);
triangle *tr = malloc(n * sizeof(triangle));
for (i = 0; i < n; i++) {
printf("Enter sides of triangle %d: ", i + 1);
scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
}
sort_by_area(tr, n);
printf("After Sorting the given triangles based on areas: \n");
for (i = 0; i < n; i++) {
printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
}
return 0;
}

Output:
Viva Question and Answers
C Fundamentals:

1. What is the difference between printf and scanf in C?


printf is used to display output on the screen, while scanf is used to take input from the user.

2. How do you print a float value with two decimal places using printf?
Use the format specifier %.2f.
Example: printf("%.2f", 3.14159); // Output: 3.14

3. What is the purpose of the & symbol in scanf?


The & (address-of) operator is used to pass the address of the variable where the input value
should be stored.

4. What is the difference between %d and %ld in printf and scanf?


o %d is used for int (integer type).
o %ld is used for long int (long integer type).

5. How do you read a character input using scanf without skipping the input?
Use a space before %c to ignore any newline character. Example: scanf(" %c", &ch);

6. What are the basic data types in C?


int (integer), float (floating-point), char (character), double (double precision floating-point)

7. What is the output of the following code?


int a = 5, b = 2;
printf("%d", a / b);
The output is 2 because both a and b are integers, so the division results in integer division,
truncating the decimal.

8. Explain the difference between = and == operators in C.


o = is the assignment operator, used to assign a value to a variable.
o == is the equality operator, used to compare two values for equality.
o
9. How do you declare a constant variable in C?
Use the const keyword. Example:
const int x = 10;

10. What will be the output of the following code?


printf("%d", sizeof(char));
The output is 1, as the size of char is 1 byte in C.
Operators and its Types:
1. What are the different types of operators in C?
The main types of operators in C are:
o Arithmetic Operators: +, -, *, /, %
o Relational Operators: ==, !=, >, <, >=, <=
o Logical Operators: &&, ||, !
o Bitwise Operators: &, |, ^, ~, <<, >>
o Assignment Operators: =, +=, -=, *=, /=, %=
o Unary Operators: +, -, ++, --, sizeof, &
o Conditional (Ternary) Operator: ?:

2. What is the difference between ++a and a++?


o ++a (pre-increment): Increments the value of a and then returns the incremented value.
o a++ (post-increment): Returns the current value of a and then increments a.

3. What are bitwise operators in C?


Bitwise operators perform operations at the bit level:
o & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).

4. What is the difference between && and & in C?


o && is a logical AND operator, used for boolean operations. It short-circuits (stops
evaluating) if the first condition is false.
o & is a bitwise AND operator, used for bit-level operations.

5. What is the ternary operator in C? Give an example.


The ternary operator is a shorthand for if-else statements.
Syntax: condition ? expression1 : expression2;
Example: int a = 10, b = 5; int max = (a > b) ? a : b; // max will be 10

6. What does the sizeof operator do in C?


The sizeof operator returns the size of a data type or variable in bytes.
Example: printf("%d", sizeof(int)); // Output: 4 (typically on most systems)

7.Explain the difference between = and ==.


o = is the assignment operator, used to assign a value to a variable.
o == is the equality operator, used to compare two values for equality.

Conditional Statements:
1. What are the types of conditional statements in C?
The main types of conditional statements in C are:
1. if statement
2. if-else statement
3. else-if ladder
4. switch statement
5. Nested if statement
2. What is the difference between if and if-else statements?
o if: Executes a block of code only if the condition is true.
o if-else: Provides an alternate block of code to execute if the condition is false.

3. What is the purpose of the else-if ladder?


The else-if ladder allows multiple conditions to be tested sequentially. If a condition is true,
its corresponding block executes, and the remaining conditions are skipped.

4. What is the switch statement in C?


The switch statement is used to select one of many code blocks to be executed based on the
value of a variable or expression.
Syntax:
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}

5. What happens if the break statement is not used in a switch case?


If the break statement is omitted, the control will "fall through" and continue executing the
subsequent cases until a break is encountered or the switch ends.

6. Can we use a switch statement with float data types?


No, the switch statement only works with int, char, or enumeration constants. float and
double are not allowed in switch.

7. What is the purpose of the default case in a switch statement?


The default case is executed if none of the case values match the switch expression. It acts
as a fallback when no specific case is matched.

Looping Statements:
1. What are control statements in C?
Control statements in C manage the flow of execution in a program. They are divided into three
main categories:
1. Conditional Statements: if, if-else, switch
2. Looping Statements: for, while, do-while
3. Jump Statements: break, continue, goto, return
2. What is the difference between break and continue?
o break: Terminates the nearest enclosing loop or switch statement immediately.
o continue: Skips the remaining code in the current iteration and jumps to the next iteration
of the loop.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) break; // Loop stops at 3
printf("%d ", i);
}

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


if (i == 3) continue; // Skips printing 3
printf("%d ", i);
}

3. What are looping control statements in C?


Looping control statements repeatedly execute a block of code as long as a condition is true.
C has three types of loops:
1. for loop
2. while loop
3. do-while loop
4. Explain the do-while loop with an example.
A do-while loop executes the loop body at least once, regardless of the condition. The
condition is checked after executing the loop body.

5. When would you use a goto statement?


The goto statement transfers control to a labeled statement.
int i = 1;
loop:
printf("%d ", i);
i++;
if (i <= 5) goto loop;

6. What is an infinite loop? Provide an example.


An infinite loop is a loop that never terminates because its condition is always true.
Example:
while (1)
{
printf("This is an infinite loop\n");
}

7. Explain the use of the return statement in C.


The return statement exits the function and optionally returns a value to the caller.
Example:
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
printf("%d", result); // Output: 8
return 0;
}

8. What is the difference between while and do-while loops?


o while loop: Checks the condition before executing the loop body, so it may not run at all
if the condition is false initially.
o do-while loop: Executes the loop body at least once before checking the condition.
Example of while loop:

Arrays:
1. What is an array in C?
An array is a collection of elements of the same data type stored in contiguous memory
locations. It allows storing multiple values using a single variable name.
Example: int arr[5] = {1, 2, 3, 4, 5};

2. How do you declare and initialize an array in C?


Arrays are declared by specifying the data type, name, and size. Initialization can be done
during or after declaration.
Example: int arr[5]; // Declaration
int arr2[5] = {1, 2, 3, 4, 5}; // Declaration and Initialization

3. What is the difference between an array and a pointer?


An array stores multiple elements, whereas a pointer holds the address of a single element.
The name of the array (arr) points to the first element, but pointers can be reassigned, while
arrays cannot.
Example: int arr[3] = {1, 2, 3};
int *ptr = arr; // Pointer points to array's first element

4. Can you change the size of an array after it is declared?


No, the size of an array in C is fixed at the time of declaration. To achieve dynamic resizing, use
dynamic memory allocation (malloc, calloc, etc.).

5. How can you access elements of an array in C?


Array elements are accessed using their index, starting from 0.
Example: int arr[3] = {10, 20, 30};
printf("%d", arr[0]); // Output: 10

6. What happens if you access an array out of bounds?


Accessing an array out of bounds causes undefined behavior. It may lead to a segmentation
fault or unexpected output because the memory outside the array is accessed.
7. How do you pass an array to a function in C?
Arrays are passed to functions by passing the base address (pointer) of the array.
Example:
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}

8. What is the difference between a one-dimensional and two-dimensional array?


o One-dimensional array: A linear array of elements.
Example: int arr[5] = {1, 2, 3, 4, 5};
o Two-dimensional array: An array of arrays (like a matrix).
Example: int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};

9. How do you find the length of an array in C?


You can find the length using sizeof operator:
int arr[5] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);
printf("Length = %d", length); // Output: 5

10. What is the difference between a static array and a dynamic array?
o Static Array: Size is fixed at compile-time.
Example: int arr[10];
o Dynamic Array: Size is determined at runtime using dynamic memory allocation (malloc,
calloc).
Example: int *arr = (int *)malloc(5 * sizeof(int));

Strings:
What is a string in C?
A string in C is a sequence of characters terminated by a null character (\0). It is represented
as an array of characters.
Example: char str[] = "Hello";

2. How do you declare and initialize a string in C?


Strings can be declared as an array of characters and initialized directly or by using input
functions like scanf.
Example:
char str1[] = "Hello"; // Initialization during declaration
char str2[10] = "World"; // Declaring with size

3. What is the difference between char str[] and char *str?


o char str[]: Declares an array of characters where memory is allocated for the string.
o char *str: Declares a pointer to a string literal. The memory is read-only, and modifying it
results in undefined behavior.
Example:
char str1[] = "Hello"; // Array
char *str2 = "World"; // Pointer to string literal

4. How do you input a string using scanf? Why is gets avoided?


scanf is used to input strings, but it stops reading at whitespace.
char str[100];
scanf("%s", str); // Reads a single word
gets is avoided because it does not check the array bounds, leading to potential buffer
overflow. Use fgets instead:
fgets(str, sizeof(str), stdin); // Safe input

5. What is the purpose of the null character (\0) in strings?


The null character (\0) is used to mark the end of a string in C. It ensures functions like printf,
strlen, etc., know where the string terminates.

6. How do you find the length of a string in C?


Use the strlen function from the standard library.
Example: char str[] = "Hello";
int length = strlen(str); // Returns 5
printf("Length: %d", length);

7. How do you concatenate two strings in C?


Use the strcat function to concatenate two strings.
Example:
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2); // str1 becomes "Hello World"
printf("%s", str1);

8. How can you compare two strings in C?


Use the strcmp function to compare two strings. It returns:
o 0 if strings are equal
o Negative value if the first string is less
o Positive value if the first string is greater

9. How do you copy one string to another in C?


Use the strcpy function to copy one string into another.
Example:
char src[] = "Hello";
char dest[10];
strcpy(dest, src); // Copies "Hello" to dest
printf("%s", dest); // Output: Hello
Functions:

1. What is a function in C?
A function in C is a block of code that performs a specific task. It is defined once and can be
called multiple times to execute the task. Functions help in modularizing the code, improving
readability, and reusability.

2. What are the types of functions in C?


Functions in C can be categorized into two main types:
1. Library Functions: Predefined functions provided by C libraries, e.g., printf(), scanf(),
sqrt().
2. User-defined Functions: Functions created by the user to perform specific tasks.

3. What are the components of a function in C?


A function has the following components:
1. Function Declaration (Prototype): Specifies the function name, return type, and
parameters.
Example: int add(int, int);
2. Function Definition: Contains the actual code for the function.
Example:
int add(int a, int b) {
return a + b;
}
3. Function Call: Invokes the function to perform its task.
Example: int result = add(5, 3);

4. What is the difference between call by value and call by reference?


Call by Value: The actual value is passed to the function, and changes made in the function do
not affect the original value.
Example: void change(int x) { x = 10; }
Call by Reference: The address of the variable is passed, and changes made in the function
affect the original value.
Example: void change(int *x) { *x = 10; }

5. What is a recursive function? Provide an example.


A recursive function is a function that calls itself to solve a smaller instance of the same
problem until a base condition is met.
Example (Factorial Calculation):
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
6. What is the difference between a function declaration and a function definition?
Function Declaration: Declares the function’s name, return type, and parameters without the
body.
Example: int add(int, int);
Function Definition: Contains the actual implementation of the function.
Example:
int add(int a, int b) {
return a + b;
}

7. Can a function return multiple values in C?


No, a function in C cannot return multiple values directly. However, you can use pointers,
structures, or arrays to return multiple values indirectly.

8. What is the default return type of a function in C if not specified?


In C, if the return type is not specified, the default return type is int. However, explicitly
specifying the return type is a good practice.

9. Can we have a function without arguments?


Yes, a function can be defined without arguments. Such functions do not take any input
parameters.
Example:
void greet() {
printf("Hello, World!\n");
}

10. What is the difference between void and int return types in functions?
void Return Type: Indicates that the function does not return any value.
Example: void display() { printf("Hello"); }
int Return Type: Indicates that the function returns an integer value.
Example: int add(int a, int b) { return a + b; }

Pointers:

1. What is a pointer in C?
A pointer is a variable that stores the memory address of another variable. Pointers allow
direct access and manipulation of memory.

2. How do you declare and initialize a pointer in C?


A pointer is declared using the * symbol.
Syntax:
int *ptr; // Declaring a pointer to an int
Initialization:
int a = 10;
int *ptr = &a; // Pointer initialized to the address of variable 'a'
3. What does the & (address-of) operator do?
The & operator is used to get the memory address of a variable.
Example:
int a = 5;
int *ptr = &a; // 'ptr' stores the address of 'a'

4. What does the * (dereference) operator do?


The * operator, when used with a pointer, dereferences the pointer, meaning it accesses the
value stored at the memory address.
Example:
int a = 5;
int *ptr = &a;
printf("%d", *ptr); // Outputs 5

5. What is a NULL pointer?


A NULL pointer is a pointer that does not point to any valid memory location. It is often used to
indicate that the pointer is not initialized or points to nothing.
Example:
int *ptr = NULL; // Pointer initialized to NULL

6. What are dangling pointers?


A dangling pointer is a pointer that points to a memory location that has been deallocated or
freed. Using a dangling pointer can cause undefined behavior.
Example:
int *ptr = (int *)malloc(sizeof(int));
free(ptr); // 'ptr' is now a dangling pointer

7. What is pointer arithmetic?


Pointer arithmetic involves operations such as addition or subtraction on pointers.
Example:
int arr[] = {10, 20, 30};
int *ptr = arr;
ptr++; // Moves the pointer to the next integer in the array

8. What is the size of a pointer?


The size of a pointer depends on the architecture of the system:
• 32-bit system: Pointer size is 4 bytes.
• 64-bit system: Pointer size is 8 bytes.

9. Can a pointer point to another pointer?


Yes, a pointer can point to another pointer. This is called a pointer to a pointer (double
pointer).
Example: int a = 10;
int *ptr = &a;
int **ptr2 = &ptr; // Pointer to a pointer
10. What is a function pointer?
A function pointer is a pointer that stores the address of a function. It can be used to call
functions dynamically.
Example:
void display() {
printf("Hello, World!\n");
}
void (*funcPtr)() = display;
funcPtr(); // Calls the function 'display'

11. What is the difference between malloc() and calloc() in terms of pointer behavior?
malloc(): Allocates memory without initializing it.
Example: int *ptr = (int *)malloc(5 * sizeof(int));
calloc(): Allocates and initializes memory to zero.
Example: int *ptr = (int *)calloc(5, sizeof(int));

12. What is a wild pointer?


A wild pointer is a pointer that has not been initialized and points to a random memory
location, leading to undefined behavior.
Example:
int *ptr; // Wild pointer (uninitialized)

Files:
1) What is a file in C? Why are files used?
A file in C is a collection of data stored on disk. Files are used to store data permanently so that
it can be retrieved and processed later. Unlike variables, data in files is retained even after the
program terminates.

2) How do you open a file in C? What are the modes available?


Use the fopen() function to open a file.
The syntax is:
FILE *fptr = fopen("filename", "mode");
Modes:
• "r": Read (file must exist)
• "w": Write (creates/overwrites file)
• "a": Append (adds to the end)
• "r+": Read/Write
• "w+": Write/Read (creates/overwrites)
• "a+": Append/Read

3) What is the difference between text files and binary files?


Text Files: Store data as readable characters with newline characters separating lines.
Binary Files: Store data in raw binary format, more compact and faster to read/write.
4) What is the difference between fopen() and fclose()?
fopen(): Opens a file and returns a FILE * pointer.
fclose(): Closes an open file and releases resources.

5) How do you write data to a file in C?


Use fprintf(), fputs(), or fwrite().
Example using fprintf():
FILE *file = fopen("example.txt", "w");
fprintf(file, "Hello, World!");
fclose(file);

6) How do you read data from a file in C?


Use fscanf(), fgets(), or fread().
Example using fgets():
FILE *file = fopen("example.txt", "r");
char buffer[100];
while (fgets(buffer, 100, file) != NULL) {
printf("%s", buffer);
}
fclose(file);

7) What is the purpose of ftell() and fseek()?


ftell(FILE *stream): Returns the current position of the file pointer in bytes from the start of
the file.
fseek(FILE *stream, long offset, int origin): Moves the file pointer to a specific location.
Ex: fseek(file, 0, SEEK_SET); // Move to the beginning

8) What happens if you try to open a file that doesn’t exist?


In "r" mode: fopen() returns NULL and sets errno.
In "w" or "a" mode: A new file is created.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy