Technical Training Lab File
Name :- Ansh Saxena
Admission no. :- 19SCSE1010502
Submitted by:-AANCHAL AIJ
Experiment 1 :- Problem based on switch-case, if-else and loop
statements.
Code :-
#include <stdio.h>
int main()
{
int x = 2;
if(x == 2){
printf("The Number is equal to 2");
}
else{
printf("The Number is not equal to 2");
}
}
Output :-
Switch-case :-
#include <stdio.h>
int main()
{
int day = 7;
switch(day){
case 1:
case 7:
printf("It's a Holiday. Enjoy!");
break;
case 2:
case 3:
case 4:
case 5:
case 6:
printf("Go to Work");
break;
default:
printf("I don't know what to say!");
}
}
Output:-
Experiment 2 :- Problem based upon nested for/while loop for printing
pattern.
Code :-
#include <stdio.h>
int main()
{
for(int i = 0 ; i<= 7; i++){
for(int j = i; j<=7 ; j++){
printf("* ");
}
printf("\n");
}
}
Output :-
Experiment 3:- Problem based recursive function.
Code :-
#include <stdio.h>
unsigned long long int factorial(unsigned int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
Output:-
Experiment 4:- Problem based upon dynamic memory allocation for n
no of inputs and performs following operations: sum of diagonal
elements, sum of all the outside elements of a 2-D array.
Code :-
#include<stdio.h>
#include<stdlib.h>
int main() {
int row , col ;
scanf("%d",&row);
scanf("%d",&col);
int *arr = (int *)malloc(row * col * sizeof(int));
int i, j,sum = 0;
for (i = 0; i< row; i++){
for (j = 0; j < col; j++){
scanf("%d",&*(arr + i*col + j));
sum += *(arr + i*col + j);
}
}
printf("The sum of all the elements is %d",sum);
free(arr);
return 0;
}
OUTPUT:-
Experiment 5 :- Problem based sorting of strings, which are inputted on
dynamic memory allocations
Code :-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char** names, int n)
{
Int i, j;
for (i = 0; i< n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (strcmp(names[j], names[j + 1]) > 0) {
char* temp;
temp = (char*)calloc(30, sizeof(char));
strcpy(temp, names[j]);
strcpy(names[j], names[j + 1]);
strcpy(names[j + 1], temp);
}
}
int main()
{
char** names;
int n, i;
printf("Enter the number of names to be printed: ");
scanf("%d\n", &n);
names = (char**)calloc(n, sizeof(char*));
for (i = 0; i< n; i++)
{
names[i] = (char*)calloc(30, sizeof(char));
scanf("%s", names[i]);
}
sort(names, n);
printf("\nArray after sorting:\n");
for (i = 0; i< n; i++)
printf("%s\n", names[i]);
return 0;
}
Output :-
Experiment 6 :- Problem based upon extracting numeric and characters
from an inputted alphanumeric inputted text.
Code :-
#include <stdio.h>
#include <ctype.h>
int main()
{
char var[50] ;
gets(var);
char num[50] = "";
char val[50] = "";
int i;
for(i=0; i<10; i++)
{
if( isdigit(var[i]) )
{
strncat(num, &var[i], 1);
}
else{
strncat(val, &var[i], 1);
}
}
printf("The numeric values are : %s \n",num);
printf("The character values are : %s",val);
return(0);
}
Output
Experiment 7 :- Problem based upon modifying the inputted strings
alternatively in lowercase and uppercase letter.
Code :-
#include <stdio.h>
#include <string.h>
void main()
{
char str[] = "Ansh";
int i;
int ln = strlen(str);
for(i = 0 ; i<ln; i++){
if(i%2 == 0){
str[i] = tolower(str[i]);
}
else {
str[i] = toupper(str[i]);
}
}
printf("%s",str);
}
Output :-
Experiment 8 :- Problem based upon 2-D dynamic arrays.
Code :- #include <stdio.h>
#include <stdlib.h>
#define FAIL 1
void freeAllocatedMemory(int **arr, int nRow)
{
int iRow = 0;
for (iRow =0; iRow<nRow; iRow++)
{
free(arr[iRow]);
}
free(arr);
}
int main(int argc, char *argv[])
{
int **arr = NULL;
int nRow = 0;
int nColumn = 0;
int iRow = 0;
int iCol = 0;
printf("\nEnter the number of Row = ");
scanf("%d",&nRow);
printf("\nEnter the number of Column = ");
scanf("%d",&nColumn);
arr = (int **)malloc(nRow * sizeof(int*));
if(arr == NULL)
{
return FAIL;
}
for (iRow =0 ; iRow<nRow ; iRow++)
{
arr[iRow] = (int *)malloc(nColumn * sizeof(int));
if(arr[iRow] == NULL)
{
freeAllocatedMemory(arr,iRow);
return FAIL;
}
}
for (iRow =0 ; iRow<nRow ; iRow++)
{
for (iCol =0 ; iCol<nColumn ; iCol++)
{
printf("\nEnter the value for [%d][%d] : ",iRow,iCol);
scanf("%d",&arr[iRow][iCol]);
}
}
for (iRow =0 ; iRow<nRow ; iRow++)
{
for (iCol =0 ; iCol<nColumn ; iCol++)
{
printf("\narr[%d][%d] = %d\n",iRow, iCol,arr[iRow][iCol]);
}
}
freeAllocatedMemory(arr,nRow);
return 0;
}
Output :-
Experiment 9 :- Problem based upon various operations on strings using
pointer and dynamic memory initialization.
Code :-
#include <stdio.h>
int main(void)
{
char name[] = "Ansh Saxena";
printf("%c\n", *name);
printf("%c\n", *(name+1));
printf("%c\n", *(name+7));
char *namePtr;
namePtr = name;
printf("%c\n", *namePtr);
printf("%c\n", *(namePtr+1));
printf("%c\n", *(namePtr+7));
int i;
char *sports[] = {"golf", "hockey",
"football","cricket","shooting" };
for(i = 0; i< 5; i++)
{
printf("String = %s", sports[i] );
printf("\tAddress of string literal = %u\n", sports[i]);
}
return 0;
}
Output :-
Experiment 10 :- Problem based on sorting using recursive and non-
recursive calls of function having pointer and arrays as an argument.
Code :-
//Using Recursion
#include <stdio.h>
void swap(int arr[], int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void selectionSort(int arr[], int i, int n)
{
int min = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] <arr[min])
min = j;
}
swap(arr, min, i);
if (i + 1 < n) {
selectionSort(arr, i + 1, n);
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i< n; i++) {
printf("%d ", arr[i]);
}
}
int main()
{
int arr[] = { 3, 5, 8, 4, 1, 9, -2 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, 0, n);
printArray(arr, n);
return 0;
}
Output :-
Not Using Recursion
#include <stdio.h>
// Utility function to swap values at two indices in the array
void swap(intarr[], inti, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Function to perform selection sort on arr[]
void selectionSort(intarr[], int n)
{
// run (n - 1) times
for (inti = 0; i< n - 1; i++)
{
// find the minimum element in the unsorted
subarray[i..n-1]
// and swap it with arr[i]
int min = i;
for (int j = i + 1; j < n; j++)
{
// if arr[j] element is less, then it is the new
minimum
if (arr[j] <arr[min])
min = j; // update index of min element
}
// swap the minimum element in subarray[i..n-1] with
arr[i]
swap(arr, min, i);
}
}
void printArray(intarr[], int n)
{
for (inti = 0; i< n; i++) {
printf("%d ", arr[i]);
}
}
int main(void)
{
intarr[] = { 3, 5, 8, 4, 1, 9, -2 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printArray(arr, n);
return 0;
}
Output :-
Experiment 11 :- Problem based on reading sets of values like students
record using structure and performs sorting based upon the entire record
based upon their performance in five subjects.
Code :-
#include <stdio.h>
#include <math.h>
struct student
{
char name[50];
int roll;
int marks[5];
double avg;
} s[5],t;
void main()
{
int i,j,n,m,tot;
n=2; // no. of students // Max 5
m=2; // no. of subjects // Max 5
printf("Enter information\n");
for(i=0;i<n;i++)
{
printf("\nEnter name of Student %d: ",i+1);
scanf("%s",s[i].name);
printf("Enter roll number: ");
scanf("%d", &s[i].roll);
tot=0;
for(j=0;j<m;j++)
{
printf("Enter marks of Subject %d: ",j+1);
scanf("%d", &s[i].marks[j]);
tot=tot+s[i].marks[j];
s[i].avg=(double)tot/m;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(s[j].avg<s[j+1].avg)
{
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
printf("Displaying Information:\n");
for(i=0;i<n;i++)
{
printf("Name: ");
printf("%s", s[i].name);
printf("\nRoll number: %d\n", s[i].roll);
for(j=0;j<m;j++)
{
printf("Marks: %d\n", s[i].marks[j]);
}
printf("Average marks %0.2f\n", s[i].avg);
}
}
Output :-
Experiment 12 :- Problem based upon nested/ self-referential structure.
Code :-
#include <stdio.h>
struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1;
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2;
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
ob1.link = &ob2;
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}
Output :-
Experiment 13 :- Problem based upon Union, passing it as an argument
inside the function.
Code :-
#include<stdio.h>
union data
{
char string[10];
};
void display(union data d)
{
printf("%s",d.string);
}
void main()
{
union data var;
strcpy(var.string,"hi Ansh");
display(var);
Output :-
Experiment 14 :- Problem based upon returning a pointer from a
function.
Code :-
#include<stdio.h>
int *return_pointer(int *, int);
void main()
{
int i, *ptr;
int arr[] = {11, 22, 33, 44, 55};
i = 4;
printf("Address of arr = %u\n", arr);
ptr = return_pointer(arr, i);
printf("\nAfter incrementing arr by 4 \n\n");
printf("Address of ptr = %u\n\n" , ptr);
printf("Value at %u is %d\n", ptr, *ptr);
int *return_pointer(int *p, int n)
{
p = p + n;
return p;
}
Output :-
Experiment 15 :- Problem based upon returning structure from a
function.
Code :-
#include <stdio.h>
struct student
{
char name[50];
int age;
};
struct student getInformation();
int main()
{
struct student s;
s = getInformation();
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);
return 0;
}
struct student getInformation()
{
struct student s1;
printf("Enter name: ");
scanf ("%[^\n]%*c", s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
return s1;
}
Output :-
Experiment 16 :- Problem based upon passing structure as an argument
from a function.
Code :-
#include<stdio.h>
struct company
{
char name[20];
char ceo[20];
float revenue; // in $
float pps; // price per stock in $
};
int main()
{
struct company companies[3] = {
{"Country Books", "Tim Green", 999999999,
1300 },
{"Country Cooks", "Jim Green", 9999999, 700 },
{"Country Hooks", "Sim Green", 99999, 300 },
};
print_struct(companies);
return 0;
}
void print_struct(struct company str_arr[])
{
Int i;
for(i= 0; i<3; i++)
{
printf("Name: %s\n", str_arr[i].name);
printf("CEO: %d\n", str_arr[i].ceo);
printf("Revenue: %.2f\n", str_arr[i].revenue);
printf("Price per stock : %.2f\n", str_arr[i].pps);
printf("\n");
}
}
Output :-
Experiment 17 :- Problem based upon file handling using fscanf and
fprintf.
Code :-
//Fscanf function
#include<stdio.h>
int main()
{
FILE *fp;
char buff[255];
fp=fopen("D:\\file.txt","r");
while(fscanf(fp,"%s",buff)!=EOF){
printf("%s",buff);
}
fclose(fp);
}
OUTPUT:-
//Fprintf function
#include<stdio.h>
int main()
{
FILE*fp;
fp=fopen("D:\\file.txt","w");
fprintf(fp,"Hello file by fprintf...\n");
fclose(fp);
}
Experiment 18:- Problem based upon file handling using fgets-fputs.
Code :-
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
fp=fopen("D:\\myfile.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}
Output :-
Experiment 19 :- Problem based upon file handling using fgetw and
fputw.
Code :-
#include <stdio.h>
int main ()
{
FILE *fp;
int i=1, j=2, k=3, num;
fp = fopen ("D:\\file1.txt","w");
putw(i,fp);
putw(j,fp);
putw(k,fp);
fclose(fp);
fp = fopen ("test.c","r");
while(getw(fp)!=EOF)
{
num= getw(fp);
printf("Data in test.c file is %d \n", num);
}
fclose(fp);
return 0;
}
Output :-
Example 20 :- Problem based upon file handling using fgetc-fputc.
Code :-
#include <stdio.h>
int main ()
{
FILE *fp = fopen("file1.txt","r");
if (fp == NULL)
return 0;
do
{
char c = fgetc(fp);
if (feof(fp))
break ;
printf("%c", c);
} while(1);
fclose(fp);
printf("\n");
int i = 0;
FILE *ft = fopen("output.txt","w");
if (ft == NULL)
return 0;
char string[] = "good bye", received_string[20];
for (i = 0; string[i]!='\0'; i++)
fputc(string[i], ft);
fclose(ft);
ft = fopen("file1.txt","r");
fgets(received_string,20,ft);
printf("%s", received_string);
fclose(ft);
return(0);
}
Output :-
Experiment 21 :- Problem based upon file handling using fread-fwrite.
Code :-
Fread Function
#include<stdio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
char ch;
struct Student Stu;
fp = fopen("file1.txt","r");
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
}
printf("\n\tRoll\tName\tMarks\n");
while(fread(&Stu,sizeof(Stu),1,fp)>0)
printf("\n\t%d\t%s\t%f",Stu.roll,Stu.name,Stu.marks);
fclose(fp);
}
OUTPUT:-
Fwrite function
#include<stdio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
char ch;
struct Student Stu;
fp = fopen("file1.txt","w");
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
}
do
{
printf("\nEnter Roll : ");
scanf("%d",&Stu.roll);
printf("Enter Name : ");
scanf("%s",Stu.name);
printf("Enter Marks : ");
scanf("%f",&Stu.marks);
fwrite(&Stu,sizeof(Stu),1,fp);
}while(ch=='y' || ch=='Y');
printf("\nData written successfully...");
fclose(fp);
}
Output :-
Experiment 22 :- Problem based upon file handling using ftell, fseek,
and rewind functions.
Code :-
Fseek function
#include <stdio.h>
int main()
{
FILE *fp = fopen("file.txt", "r");
if (fp==NULL){
/* Handle open error */
printf("Error occured");
}
else {
printf("good to go");
}
if ( fseek(fp, 0L, SEEK_SET) != 0 ) {
printf("errror");
}
return 0;
}
OUTPUT:-
Rewind function
#include <stdio.h>
int main()
{
FILE *fp = fopen("file.txt", "r");
if (fp==NULL){
/* Handle open error */
printf("Error occured");
}
else {
printf("good to go");
}
rewind(fp);
return 0;
}
Output :-
Exercise 23 :- Problem based upon classes and objects.
Code :-
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
string geekname;
void printname()
{
cout<< "Geekname is: " <<geekname;
}
};
int main() {
Geeks obj1;
obj1.geekname = "AKASH";
obj1.printname();
return 0;
}
Output :-
Experiment 24 :- Problem based upon array of objects.
Code :-
#include <iostream>
using namespace std;
class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};
int main()
{
MyClass obs[4];
int i;
for(i=0; i< 4; i++)
obs[i].setX(i);
for(i=0; i< 4; i++)
cout<< "obs[" <<i<< "].getX(): " <<obs[i].getX() << "\n";
return 0;
}
Output :-
Experiment 25 :- Problem based upon Friend function, static member
function.
Code :-
//Friend Function
#include <iostream>
#include <string>
using namespace std;
class sample{
int length, breadth;
public:
sample(int length, int breadth):length(length),breadth(breadth)
{}
friend void calcArea(sample s);
};
void calcArea(sample s){
cout<<"Area = "<<s.length * s.breadth;
}
int main()
{
sample s(10,15);
calcArea(s);
return 0;
}
Output:-
//Static function
#include <iostream>
using namespace std;
class test {
intobjNo;
static intobjCnt;
public:
test()
{
objNo = ++objCnt;
}
~test()
{
--objCnt;
}
void printObjNumber(void)
{
cout<< "object number :" <<objNo<< "\n";
}
static void printObjCount(void)
{
cout<< "count:" <<objCnt<< "\n";
}
};
int test::objCnt;
int main()
{
test t1, t2;
test::printObjCount();
test t3;
test::printObjCount();
t1.printObjNumber();
t2.printObjNumber();
t3.printObjNumber();
return 0;
}
Output :-