Au PPSC Lab Record 09-12-24
Au PPSC Lab Record 09-12-24
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;
return 0;
}
Input:
Output:
d) Conversion of Fahrenheit to Celsius and vice versa.
FileName: TempConversion.C
#include <stdio.h>
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>
int main()
{
float initialVelocity, time, acceleration, 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
return 0;
}
Input:
Output:
WEEK – 3 Date:
FileName: Expressions.C
#include <stdio.h>
int main()
{
// Variables for the first expression
int a, b, c, d, result1;
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
int main()
{
int choice;
float radius, side, length, width, base, height, area;
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;
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;
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;
return 0;
}
Input:
Output:
WEEK – 4 Date:
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;
}
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;
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;
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;
return 0;
}
Input:
Output:
WEEK – 5 Date:
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;
// 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);
return 0;
}
Input:
Output:
g) Construct a Pyramid pattern.
FileName: PyramidPattern.C
#include <stdio.h>
int main()
{
int n, i, j;
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;
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
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;
int arr[size];
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
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);
int main()
{
int size;
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 index position to insert the element (0 to %d): ", size);
scanf("%d", &position);
// Shift elements to the right to make space for the new element
for (int i = size; i > position; i--)
{
arr[i] = arr[i - 1];
}
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]);
Output:
g) Sorting of elements in an array using Bubble sort
FileName: BubbleSort.C
#include <stdio.h>
void bubbleSort(int[],int); //function declaration
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);
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);
}
Input:
Output:
b) Multiplication of two 2-D arrays
FileName: Multiplication.C
#include<stdio.h>
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;
}
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>
int main()
{
int size;
printf("Enter the size of the square matrix: ");
scanf("%d", &size);
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];
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);
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;
}
}
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
int main()
{
char str1[100], str2[100], concat[200];
// Concatenate strings
stringConcatenate(str1, str2, concat);
printf("Concatenated string: %s\n", concat);
Input:
Output:
b) With String functions:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[100], str2[100];
// Concatenate strings
strcat(str1, str2);
printf("Concatenated string: %s\n",str1);
return 0;
}
Input:
Output:
WEEK – 9 Date:
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>
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>
if (num < 0)
{
num = -num; // Handle negative numbers
}
return 0;
}
Input:
Output:
e) Program to Calculate LCM
FileName: LCM.C
#include <stdio.h>
int main()
{
int 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;
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;
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 main()
{
int number_of_students,i;
char gender;
int sum;
scanf("%d", &number_of_students);
int *marks = (int *) malloc(number_of_students * sizeof (int));
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>
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;
return 0;
}
Input:
Output:
e) Swap two numbers using functions and pointers - call by value and reference.
FileName: Swapping.C
#include <stdio.h>
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;
if (type == 1) {
int shelf, pages;
printf("Enter shelf and pages: ");
scanf("%d %d", &shelf, &pages);
} else if (type == 2) {
int shelf, bookIndex;
printf("Enter shelf and book index: ");
scanf("%d %d", &shelf, &bookIndex);
} else if (type == 3) {
int shelf;
printf("Enter shelf number: ");
scanf("%d", &shelf);
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);
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;
}
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;
Output:
Viva Question and Answers
C Fundamentals:
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
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);
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.
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);
}
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};
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";
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.
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.
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));
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.