You are on page 1of 95

1a)

Write a Cprogramtoreadthe nameandmarksof nnumberofstudentsfromKB andthen


store themin afile.

#include <stdio.h>

#include <stdlib.h>

struct student{

charname[50];

int marks;

};

intmain(){

int n, i;

struct students[100];

FILE*fp;

printf("Enter the number ofstudents: ");

scanf("%d", &n);

for(i =0;i <n;i++) {

printf("Enter thename ofstudent %d: ", i +1);

scanf("%s", s[i].name);

printf("Enter themarksofstudent %d: ", i+ 1);

scanf("%d", &s[i].marks);

fp= fopen("students.txt", "w");

if(fp == NULL) {

printf("Error openingfile!\n");

exit(1);

for(i =0;i <n;i++) {

fprintf(fp, "Name: %s\n", s[i].name);

fprintf(fp, "Marks: %d\n", s[i].marks);


}

fclose(fp);

printf("Data savedtostudents.txt\n");

return 0;

1b)

Write aprograminC todemonstratetheuse of&(addressof) and*(valueat address)


operators.

#include <stdio.h>

intmain(){

int x=10;

int *ptr;

ptr= &x;

printf("Addressofx: %p\n", &x);

printf("Value ofptr: %p\n", ptr);

printf("Value storedat addressof ptr: %d\n", *ptr);

return 0;

1c)

Write a Cprogramtofindthe sumofthefirst Nnatural numbersusinga user-define

function int sum(int)

#include <stdio.h>

intsum(intn) {

int i, s=0;

for(i =1;i <= n;i++){

s+= i;

}
return s;

intmain(){

int n;

printf("Enter the value ofN: ");

scanf("%d", &n);

printf("Sumoffirst %dnaturalnumbers: %d\n", n, sum(n));

return 0;

2a)

Write a Cprogramtoreadthe namesandmarksof nnumberofstudentsfromKB andthen


appendthemtoapreviously existingfile.

#include <stdio.h>

#include <stdlib.h>

struct student{

charname[50];

int marks;

};

intmain(){

int n, i;

struct students;

FILE*fptr;

printf("Enter the number ofstudents: ");

scanf("%d", &n);

fptr =fopen("students.txt", "a");

if(fptr == NULL){

printf("Error openingfile!\n");

exit(1);

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

printf("Enter thename ofstudent %d: ", i +1);

scanf("%s", s.name);

printf("Enter themarksofstudent %d: ", i+ 1);

scanf("%d", &s.marks);

fprintf(fptr, "%s%d\n", s.name, s.marks);

fclose(fptr);

return 0;

Thisprogramfirstpromptstheusertoenterthe numberof studentsthey want toenter.It then


opensafile namedstudents.txt inappendmodeusing fopen().The a mode flag tellsthe
programtoopen the filein appendmode, whichmeansthatthedata writtentothe filewillbe
appendedtotheendofthefile, insteadofoverwritingthe existingcontents.

In the loop, the programpromptsthe usertoenter the nameandmarksof each student, and
writesthe information tothefile usingfprintf().Finally, the programclosesthe fileusing
fclose().

2b)

Write a programinC toaddtwonumbersusingpointers.

#include <stdio.h>

intmain(){

int num1, num2, sum;

int *ptr1, *ptr2;

printf("Enter twonumbers: ");

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

ptr1 =&num1;

ptr2 =&num2;

sum=*ptr1+ *ptr2;

printf("Sumofthetwonumbers= %d\n", sum);


return 0;

2c)

Write a Cprogramtofindthe product ofthefirstN naturalnumbersusinga user-define


function int factorial(int).

#include <stdio.h>

intfactorial(int n){

int result =1;

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

result *=i;

return result;

intmain(){

int n;

printf("Enter apositive integer: ");


scanf("%d", &n);

int product =factorial(n);

printf("The productof the first%dnaturalnumbersis%d\n", n, product);

return 0;

In thisprogram, the factorialfunction calculatesthe factorialofthe given numbernby


multiplying allthe numbersfrom1 ton. The main function readsthe value ofn fromthe user,
callsthe factorialfunction, andthenprintstheresult.

3a)

Write a Cprogramtowrite the employeedetailsasshown inthefollowingformat:

Emp.NoEmp.Name Emp.Sal

1 XYZ100000.00
2 ABC200000.00

3 PQR300000.00

.. .

.. .

.. .

#include <stdio.h>

struct Employee {

int empNo;

char empName[50];

float empSal;

};

intmain(){

int n;

printf("Enterthenumberof employees: ");

scanf("%d", &n);

structEmployeeemp[n];

for(inti = 0;i <n;i++) {

printf("Enter the detailsof employee%d\n", i+1);

printf("Enter Employee Number: ");

scanf("%d", &emp[i].empNo);

printf("Enter Employee Name: ");

scanf("%s", emp[i].empName);

printf("Enter Employee Salary: ");

scanf("%f", &emp[i].empSal);

printf("Emp.No Emp.NameEmp.Sal\n");

for(inti = 0;i <n;i++) {

printf("%d%s%.2f\n", emp[i].empNo, emp[i].empName, emp[i].empSal);

}
return0;

3b)

Write a Cprogramtoaddnumbersusingcallby reference.

#include <stdio.h>

void addNumbers(int *a, int *b, int*sum) {

*sum= *a +*b;

intmain(){

int a, b, sum;

printf("Enterthefirstnumber: ");

scanf("%d", &a);

printf("Enterthesecondnumber: ");

scanf("%d", &b);

addNumbers(&a, &b, &sum);

printf("Sumof%dand%dis%d\n", a, b, sum);

return0;

3c)

Write a Cprogramtofindthe GCDofgiven twonumbersusinga user-define function int


gcd(int, int).

#include <stdio.h>

intgcd(int a, int b) {

int remainder;

while (b!= 0) {

remainder= a%b;

a =b;
b=remainder;

returna;

intmain(){

int a, b, result;

printf("Enterthefirstnumber: ");

scanf("%d", &a);

printf("Enterthesecondnumber: ");

scanf("%d", &b);

result= gcd(a, b);

printf("TheGCDof%dand%dis%d\n", a, b, result);

return0;

4a)

Write a Cprogramtodemonstratereadingdatafroma text file"file1.txt".

#include <stdio.h>

intmain(){

FILE*fp;

char filename[]= "file1.txt";

char ch;

fp=fopen(filename, "r");

if (fp==NULL) {

printf("Couldnotopen file%s\n", filename);

return 1;

printf("Readingdata fromfile%s\n", filename);

while ((ch =fgetc(fp)) != EOF) {


putchar(ch);

fclose(fp);

return0;

4b)

Write a Cprogramtofindthe biggest oftwogiven numbersusingpointers.

#include <stdio.h>

void findBiggest(int *a, int *b, int*biggest) {

if (*a> *b) {

*biggest =*a;

} else{

*biggest =*b;

intmain(){

int a, b, biggest;

printf("Enterthefirstnumber: ");

scanf("%d", &a);

printf("Enterthesecondnumber: ");

scanf("%d", &b);

findBiggest(&a, &b, &biggest);

printf("Thebiggest of%dand%dis%d\n", a, b, biggest);

return0;

4c)
Write a Cprogramtofindthe LCMofgiven two numbersusinga user-definefunction int
lcm(int, int).

#include <stdio.h>

intgcd(int a, int b) {

if (b== 0)

return a;

returngcd(b, a %b);

intlcm(inta, int b) {

return(a * b) /gcd(a, b);

intmain(){

int a, b;

printf("Entertwonumbers: ");

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

printf("LCMof%dand%dis%d\n", a, b, lcm(a, b));

return0;

5a)

Write a Cprogramtodemonstratewritingdata toatextfile"file1.txt".

#include <stdio.h>

intmain(){

FILE*fp;

fp=fopen("file1.txt", "w");

if (fp==NULL) {

printf("Couldnotopen file");

return 0;
}

char str[100];

printf("Entera string: ");

scanf("%[^\n]s", str);

fprintf(fp, "%s", str);

printf("Datawrittentofilesuccessfully\n");

fclose(fp);

return0;

5b)

Write a Cprogramtoreadanarrayof Nnumbersandthen printthemusingpointers.

#include <stdio.h>

intmain(){

int n, i;

printf("Enterthenumberof elements: ");

scanf("%d", &n);

int arr[n];

printf("Enter%delements: \n", n);

for(i = 0;i <n;i++) {

scanf("%d", &arr[i]);

printf("Array elementsusingpointers: \n");

for(i = 0;i <n;i++) {

printf("%d", *(arr+ i));

return0;

}
5c)

Write a Cprogramtofindthe GCDofgiven three numbersusinga user-define functionint


gcd3(int, int, int).

#include <stdio.h>

intgcd(int a, int b) {

if (b== 0)

return a;

returngcd(b, a %b);

intgcd3(int a, intb, int c) {

returngcd(gcd(a, b), c);

intmain(){

int a, b, c;

printf("Enterthreenumbers: ");

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

printf("GCDof%d, %dand%dis%d\n", a, b, c, gcd3(a, b, c));

return0;

6a)

Write a Cprogramtodemonstrateappendingdata to atextfile"file1.txt".

#include <stdio.h>

intmain(){

FILE*fp;

char data[100];

fp=fopen("file1.txt", "a");//Open file inappendmode

if (fp==NULL) {

printf("Error openingfile\n");
return 1;

printf("Enterdatatoappend: ");

gets(data);//Readdata fromuser

fprintf(fp, "%s\n", data);//Writedatatofile

printf("Dataappendedtofile successfully\n");

fclose(fp);//Closethefile

return0;

Thisprogramopensthe file"file1.txt" inappendmodeusingthe fopen function, whichallows


newdata tobe written tothe endof the file. Theuserispromptedtoenter data toappend,
which isreadusinggetsandwritten tothefile usingfprintf.The fileisthen closedusingfclose.

6b)

Write a Cprogramtoprint allpermutationsof agivenstringusingpointers.

#include <stdio.h>

#include <string.h>

void swap(char *a, char *b) {

char temp= *a;

*a= *b;

*b=temp;

void permute(char*str, int l, intr){

int i;

if (l== r)

printf("%s\n", str);

else{

for(i =l;i <=r;i++) {

swap((str+ l), (str +i));


permute(str, l+ 1, r);

swap((str+ l), (str +i));

intmain(){

char str[100];

printf("Entera string: ");

scanf("%s", str);

int n= strlen(str);

permute(str, 0, n -1);

return0;

Thisprogramusesthe permutation algorithmtoprintallpossiblepermutationsofagiven


string.The permute functionusesrecursiontogenerate allpermutationsof the string.The
function takesthestringstrandthe indicesl andrasarguments.If land rare equal, it means
we havereachedtheendofthestring, sowe print the permutedstring. Otherwise, weuse a
loopto swapthecharactersat indexlwithallcharactersfroml tor, andrecursively call
permute for the substringfroml+1 tor. In the main function, the user ispromptedtoentera
string, whichispassedtothe permutefunction alongwiththe indices0andn-1 wheren isthe
lengthofthe string.

6c)

Write a Cprogramtofindthe LCMofgiven three numbersusing auser-define functionint


lcm3(int, int, int).

#include<stdio.h>

intlcm3(int a, int b, int c)

int lcm=1;

int i =2;

while (1)
{

if(i %a == 0&&i%b==0&&i%c==0)

lcm= i;

break;

i++;

return lcm;

intmain()

int a, b, c;

printf("Enter three numbers: ");

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

printf("The LCMof %d, %d, and%dis%d\n", a, b, c, lcm3(a, b, c));

return 0;

7a)

Write a Cprogramtocopythe content ofa file, "file1.txt,"intoanother file, "file2.txt.”

#include<stdio.h>

intmain()

FILE*fp1, *fp2;

charch;

fp1= fopen("file1.txt", "r");

fp2= fopen("file2.txt", "w");

if(fp1==NULL)
{

printf("File 1 doesn'texist.\n");

return0;

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

fputc(ch, fp2);

printf("File content copiedsuccessfully.\n");

fclose(fp1);

fclose(fp2);

return 0;

7b)

Write a Cprogramtofindthe largestelementusingDynamicMemoryAllocation.

#include <stdio.h>

#include <stdlib.h>

intmain()

int n, i, *ptr, max;

printf("Enter number ofelements: ");

scanf("%d", &n);

ptr= (int*) malloc(n* sizeof(int)); //allocatememory for nelements

if(ptr==NULL)

printf("Memoryallocationfailed.\n");

return1;

printf("Enter elements: ");

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


scanf("%d", &ptr[i]);

max=ptr[0];

for(i =1;i <n;i++)

if(ptr[i] >max)

max=ptr[i];

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

free(ptr); // deallocate memory

return 0;

7c)

Write a Cprogramtofindwhetherthe given numberisprime or notusinga user-define


function int isprime(int).

#include <stdio.h>

intisprime(intn) {

int i;

if(n <= 1)return 0;

for(i =2;i <n;i++) {

if(n%i == 0) return 0;

return 1;

intmain(){

int n;

printf("Enter apositive integer: ");

scanf("%d", &n);

if(isprime(n)) {

printf("%disa primenumber.\n", n);

}else {
printf("%disnot aprime number.\n", n);

return 0;

8a)

Write a Cprogramtocountthenumberofcharactersandthe number ofwordsin atextfile


"file1.txt".

#include <stdio.h>

#include <ctype.h>

intmain(){

FILE*fp;

int charCount =0, wordCount= 0;

charch;

fp= fopen("file1.txt", "r");

if(fp == NULL) {

printf("Couldnotopen file\n");

return0;

while ((ch= fgetc(fp))!=EOF) {

charCount++;

if(isspace(ch) || ch =='\n'){

wordCount++;

fclose(fp);

printf("Numberof characters: %d\n", charCount);

printf("Numberof words: %d\n", wordCount+ 1);


return 0;

8b)

Write a Cprogramtofindthe lengthofa stringusingpointers

#include <stdio.h>

intlength(char *str) {

int len =0;

while (*str !='\0') {

len++;

str++;

return len;

intmain(){

charstr[] ="Hello, world!";

printf("The length of the stringis: %d\n", length(str));

return 0;

8c)

Write a Cprogramtofindwhetherthe given numberisapalindrome or notusinga


user-define functionintispalindrome(int).

#include <stdio.h>

intispalindrome(int num) {

int reversed= 0, temp=num;

while (temp!=0){

reversed=reversed* 10+temp%10;

temp /=10;
}

returnnum== reversed;

intmain(){

int num;

printf("Entera number: ");

scanf("%d", &num);

if (ispalindrome(num))

printf("The number isa palindrome\n");

else

printf("The number isnot apalindrome\n");

return0;

9a)

Write a Cprogramtocountthenumberoflinesandsentencesina text file "file1.txt".

#include <stdio.h>

#include <ctype.h>

intmain(void) {

int lines=0, sentences=0;

charc;

FILE*file;

file= fopen("file1.txt", "r");

if(file==NULL) {

printf("Error openingfile!\n");

return1;

while ((c =getc(file)) != EOF) {

if(c=='\n') lines++;
if(c=='.' || c== '!' || c=='?') sentences++;

fclose(file);

printf("Lines: %d\nSentences: %d\n", lines, sentences);

return 0;

9b)

Write a Cprogramtofindthe reverse ofa string usingpointers

#include <stdio.h>

#include <string.h>

void reverse(char*str){

int len= strlen(str);

char *start= str;

char *end= str +len -1;

while (start< end){

chartemp=*start;

*start= *end;

*end=temp;

start++;

end--;

intmain(){

char str[100];

printf("Entera string: ");

scanf("%s", str);

reverse(str);

printf("Reversedstring: %s\n", str);


return0;

9c)

Write a Cprogramtofindwhetherthe given numberisperfector notusing auserdefine


function int isperfect(int)

#include <stdio.h>

intisPerfect(intnum)

int i, sum=0;

for(i=1;i<num;i++){

if(num%i == 0)

sum += i;

return (sum== num);

intmain()

int num;

printf("Enter apositive integer: ");

scanf("%d", &num);

if(isPerfect(num))

printf("%disa perfectnumber\n", num);

else

printf("%disnot aperfect number\n", num);

return 0;

}
10a)

Write a Cprogramtoreadthe linesfromatextfile intoanarrayof textlinesandthendisplay


themon output.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX_LINE_LEN 1024

#define MAX_LINES100

intmain(int argc, char *argv[]) {

char *lines[MAX_LINES];

char line[MAX_LINE_LEN];

int line_count= 0;

if (argc!= 2){

printf("Usage: %s<filename>\n", argv[0]);

return 1;

FILE*file= fopen(argv[1], "r");

if (file ==NULL) {

printf("Error openingfile %s\n", argv[1]);

return 1;

while (fgets(line, MAX_LINE_LEN, file)){

lines[line_count] = (char *) malloc(strlen(line) + 1);

strcpy(lines[line_count], line);

line_count++;

fclose(file);

for(inti = 0;i <line_count;i++) {


printf("%s", lines[i]);

free(lines[i]);

return0;

10b)

Write a Cprogramtofindwhetherthe given stringisa palindrome ornot usingpointers

#include <stdio.h>

#include <string.h>

intis_palindrome(char*str) {

int len= strlen(str);

char *end= str +len -1;

while (str<end) {

if(*str!= *end)return0;

str++;

end--;

return1;

intmain(){

char str[100];

printf("Entera string: ");

scanf("%s", str);

if (is_palindrome(str)) {

printf("The stringisa palindrome\n");

} else{

printf("The stringisnot apalindrome\n");

}
return0;

10c)

Write a Cprogramtofindwhetherthe given numberisan Armstrongnumberornot usinga


user-define functionintisarmstrong(int).

#include <stdio.h>

#include <math.h>

intisarmstrong(int num) {

int originalNum, remainder, n = 0, result =0;

originalNum=num;

while (originalNum !=0){

originalNum/= 10;

++n;

originalNum=num;

while (originalNum !=0){

remainder=originalNum%10;

result += pow(remainder, n);

originalNum/= 10;

if(result == num)

return1;

else

return0;

intmain(){

int num;

printf("Enter an integer: ");


scanf("%d", &num);

if(isarmstrong(num))

printf("%disan Armstrongnumber.", num);

else

printf("%disnot anArmstrongnumber.", num);

return 0;

11a)

Write a Cprogramtodeletea specific linefroma text file

#include <stdio.h>

#include <stdlib.h>

intmain(){

FILE*file_ptr1, *file_ptr2;

int line_num, count =0;

char filename[100], c;

printf("Enterthefilename: ");

scanf("%s", filename);

//Openfile inreadmode

file_ptr1= fopen(filename, "r");

c =getc(file_ptr1);

//If file doesnotexist

if (file_ptr1==NULL) {

printf("Couldnotopen file%s", filename);

return 0;

printf("Entertheline numberyou wanttodelete: ");

scanf("%d", &line_num);

//Openanother file inwrite mode


file_ptr2= fopen("temp.c", "w");

c =getc(file_ptr1);

while (c!= EOF) {

c= getc(file_ptr1);

if(c=='\n')

count++;

//Untiltheline tobedeletedisreached

if(count!=line_num) {

//Copyalllinesin File2

putc(c, file_ptr2);

fclose(file_ptr1);

fclose(file_ptr2);

//Remove originalfile

remove(filename);

//Rename the file

rename("temp.c", filename);

printf("\nLine %dhasbeendeletedsuccessfully", line_num);

return0;

11b)

Write a Cprogramtofindthe reverse ofa given number usingpointers

#include <stdio.h>

void reverse(int*num) {

int rev= 0;

while (*num) {
rev= rev* 10+ *num%10;

*num /=10;

*num=rev;

intmain(){

int num;

printf("Enter anumber: ");

scanf("%d", &num);

reverse(&num);

printf("Reverse: %d", num);

return 0;

n thisprogram, thereverse functiontakesa pointer toan integernum, andreversesthe


numberby performingrepeatedinteger division andmodulooperations.The result isstored
back intheoriginalintegerthrough the pointer.The mainfunction readsanumberfromthe
userandcallsthereverse functionwiththeaddressofthenumber. Finally, it printsthe
reversednumber.

11c)

Write a Cprogramtofindwhetherthe given numberisastrongnumberornotusinga


user-define functionintisstrong(int).

#include <stdio.h>

#include <math.h>

intfactorial(int n){

int f= 1;

while (n > 1) {

f*= n;
n--;

return f;

intisstrong(intn) {

int sum=0, t=n;

while (t) {

int d=t %10;

sum+= factorial(d);

t/=10;

return (sum== n);

intmain(){

int n;

printf("Enter anumber: ");

scanf("%d", &n);

if(isstrong(n)){

printf("%disa strongnumber", n);

}else {

printf("%disnot astrong number", n);

return 0;

In thisprogram, the factorialfunction calculatesthe factorialofa number n, andthe isstrong


function determineswhetheragivennumbern isastrongnumber ornot.Astrongnumberis
definedasa numbersuch thatthesumof the factorialsofitsdigitsisequaltothe number
itself. Themain functionreadsa numberfromtheuser, callsthe isstrongfunction with the
number, andprintswhether the number isa strongnumberor not.
12a)

Write a programinC toreplace a specificline with anothertext ina file

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void replaceLine(constchar*filename, int lineNumber, constchar*newLine) {

FILE*fptr1, *fptr2;

charbuffer[1024];

int lineCount= 0;

fptr1= fopen(filename, "r");

if(fptr1== NULL) {

printf("Error openingfile\n");

exit(1);

fptr2= fopen("replacement.tmp", "w");

if(fptr2== NULL) {

printf("Error openingfile\n");

fclose(fptr1);

exit(1);

while (!feof(fptr1)) {

strcpy(buffer, "\0");

fgets(buffer, 1024, fptr1);

lineCount++;

if(lineCount==lineNumber) {

fprintf(fptr2, "%s", newLine);

}else {

fprintf(fptr2, "%s", buffer);

}
}

fclose(fptr1);

fclose(fptr2);

remove(filename);

rename("replacement.tmp", filename);

intmain(){

charfilename[100];

int lineNumber;

charnewLine[1024];

printf("Enter the filename: ");

scanf("%s", filename);

printf("Enter the linenumbertoreplace: ");

scanf("%d", &lineNumber);

printf("Enter the newtext: ");

scanf("\n");

fgets(newLine, 1024, stdin);

replaceLine(filename, lineNumber, newLine);

printf("Line replacedsuccessfully\n");

return 0;

In thisprogram, the replaceLinefunction replacestheline specifiedby lineNumber with the


text specifiedby newLinein the file specifiedby filename.The function first opensthe original
fileforreadingandcreatesa newfile for writing.It thenreadseach line ofthe originalfile intoa
buffer, andifthe line number matchesthe targetline number, itwritesthe newtexttothe new
file. If the linenumberdoesnot match, it writestheoriginal linetothe newfile.Once alllines
have been processed, itclosesbothfiles, deletestheoriginalfile, andrenamesthenewfile to
the originalfile name. Themain functionpromptstheuserforthe filename, line number, and
newtext, andcallsthe replaceLinefunction withthese inputs. Finally, it displaysa message
indicatingthat the linewassuccessfullyreplaced.
12b)

Write a Cprogramtofindthe numberof digitsin agivenpositive integerusingpointers.

#include <stdio.h>

intmain(){

int n, count= 0;

int *ptr= &n;

printf("Enter apositive integer: ");

scanf("%d", ptr);

while (*ptr != 0){

*ptr/= 10;

count++;

printf("Numberof digits: %d", count);

return 0;

12c)

Write a Cprogramtoprint allArmstrongnumbersbetween 1toN usinga user-define


function voidall_armstrongs(int).

#include <stdio.h>

#include <math.h>

void all_armstrongs(intn) {

int num, originalNum, remainder, digits= 0;

for(inti = 1;i <=n;i++) {

num =i;

originalNum=num;

while (originalNum !=0){

originalNum/=10;

digits++;
}

originalNum=num;

int result =0;

while (originalNum !=0){

remainder= originalNum%10;

result+=pow(remainder, digits);

originalNum/=10;

if(result == num)

printf("%disanArmstrongnumber\n", num);

intmain(){

int n;

printf("Entera number: ");

scanf("%d", &n);

all_armstrongs(n);

return0;

13a)

Write a programinC tomerge twofilesandwrite itin anewfile

#include <stdio.h>

#include <stdlib.h>

intmain()

FILE*fp1, *fp2, *fp3;

charch;

//Open the firstfileforreading


fp1= fopen("file1.txt", "r");

if(fp1==NULL)

printf("Couldnotopen filefile1.txt\n");

exit(0);

//Open the secondfileforreading

fp2= fopen("file2.txt", "r");

if(fp2==NULL)

printf("Couldnotopen filefile2.txt\n");

exit(0);

//Open the thirdfile forwriting

fp3= fopen("output.txt", "w");

if(fp3==NULL)

printf("Couldnotopen fileoutput.txt\n");

exit(0);

//Copy the contentsoffirstfile tooutputfile

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

fputc(ch, fp3);

//Copy the contentsofsecondfiletooutputfile

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

fputc(ch, fp3);
}

printf("Filesmerged successfullyintooutput.txt\n");

//Close all files

fclose(fp1);

fclose(fp2);

fclose(fp3);

return 0;

13b)

Write a Cprogramtofindwhetherthe given numberisprime or notusingpointers

#include <stdio.h>

intis_prime(int num) {

int i;

if (num<=1) return 0;

for(i = 2;i < num;i++) {

if(num%i ==0) return 0;

return1;

intmain(){

int num, *p_num =&num;

printf("Entera number: ");

scanf("%d", p_num);

if (is_prime(*p_num))

printf("%disaprime number\n", *p_num);

else

printf("%disnot a prime number\n", *p_num);


return0;

13c)

Write a Cprogramtoprint allstrongnumbersbetween 1 toN usinga user-definefunction


void all_strongs(int).

#include<stdio.h>

#include<math.h>

intfactorial(int num){

int fact=1;

while(num> 0) {

fact *=num;

num--;

return fact;

intis_strong(intnum) {

int sum=0, n= num;

while(n> 0) {

int r= n%10;

sum+= factorial(r);

n/=10;

return sum== num;

void all_strongs(int n) {

for(inti =1;i <= n;i++) {

if(is_strong(i))

printf("%d", i);
}

intmain(){

int n;

printf("Enter anumber: ");

scanf("%d", &n);

printf("Strongnumbersbetween 1 to%d: ", n);

all_strongs(n);

return 0;

14a)

Write a programinC toencrypt atextfile

#include <stdio.h>

#include <stdlib.h>

#define ENCRYPT_KEY3 //Encryption key

intmain(int argc, char *argv[]) {

FILE*fp_in, *fp_out;

int ch;

if (argc!= 3){

printf("Usage: %sinput_file output_file\n", argv[0]);

return 1;

fp_in =fopen(argv[1], "r");

if (fp_in ==NULL) {

printf("Error openinginputfile\n");

return 1;

fp_out =fopen(argv[2], "w");


if (fp_out==NULL) {

printf("Error openingoutputfile\n");

return 1;

while ((ch =fgetc(fp_in)) != EOF) {

fputc(ch + ENCRYPT_KEY, fp_out);

fclose(fp_in);

fclose(fp_out);

return0;

}Thisprogram usesthe Caesarciphermethodofencryption, whichsimplyinvolvesshifting


eachcharacter in the text bya certainkeyvalue. In thiscase, the encryption keyisdefinedas
ENCRYPT_KEYandisset to3.

The programtakestwocommandline arguments: the input file nameandthe output file


name.The input file isopenedin readmode, andthe outputfileisopenedinwrite mode. The
fgetcfunctionisusedtoreadeach characterfromtheinputfile, andthefputcfunction isused
towritetheencryptedcharacter totheoutputfile.Finally, the programclosesboth filesand
returns0.

14b)

Write a Cprogramtofindthe factorialofa given numberusingpointers.

#include <stdio.h>

void factorial(int*result, int num) {

int i, res= 1;

for(i = 1;i <=num;i++) {

res*= i;

*result= res;

intmain(){

int num, result;


printf("Entera number: ");

scanf("%d", &num);

factorial(&result, num);

printf("Thefactorialof%dis%d\n", num, result);

return0;

In thisprogram, the factorialfunctiontakestwoarguments: apointerresultto an integerand


aninteger num.Thefunction calculatesthe factorialofnumby usinga for loopanda variable
resinitializedto1.The result isstoredin the memorylocation pointedtoby result.

In the mainfunction, the userispromptedtoentera number. Thisnumberispassedto the


factorialfunction, which calculatesthe factorialandstoresthe result in the resultvariable.The
result isthenprintedtothe screen.

14c)

Write a Cprogramtoprint allpalindrome numbersbetween 1toN usinga user-define


function voidall_palindromes(int).

#include <stdio.h>

#include <stdbool.h>

boolis_palindrome(int num){

int reverse = 0, original= num;

while (num!=0){

reverse= reverse* 10+ num%10;

num /=10;

returnreverse == original;

void all_palindromes(intn) {

for(inti = 1;i <=n;i++) {

if(is_palindrome(i))
printf("%d\n", i);

intmain(){

int n;

printf("EnterN: ");

scanf("%d", &n);

all_palindromes(n);

return0;

15a)

Write a programinC todecrypta previouslyencryptedfile

#include <stdio.h>

#include <stdlib.h>

intmain(int argc, char* argv[]) {

if(argc !=3) {

printf("Usage: %s<encrypted_file><decrypted_file>\n", argv[0]);

return1;

FILE* encrypted=fopen(argv[1], "rb");

if(!encrypted) {

printf("Error: Unable to openencryptedfile %s\n", argv[1]);

return1;

FILE* decrypted= fopen(argv[2], "wb");

if(!decrypted) {

printf("Error: Unable to create decryptedfile%s\n", argv[2]);

return1;
}

unsignedcharbuffer[1024];

size_t n;

while ((n = fread(buffer, 1, sizeof(buffer), encrypted)) > 0) {

for (size_t i= 0;i <n;i++) {

buffer[i]= ~buffer[i];

fwrite(buffer, 1, n, decrypted);

fclose(encrypted);

fclose(decrypted);

return 0;

Thisprogramtakestwocommandline arguments: the name of the encryptedfileandthe


nameofthe decryptedfile tobe created. It usesbitwiseNOToperationtodecrypt the
contentsoftheencryptedfile andwritesthedecrypteddatatoa newfile.

15b)

Write a Cprogramtofindwhetherthe given positive number isan Armstrongnumber ornot


usingpointers

#include <stdio.h>

#include <math.h>

intlength(int number) {

int count= 0;

while (number >0) {

count++;

number /= 10;

return count;

}
intisArmstrongNumber(intnumber) {

int length_of_number =length(number);

int original_number =number;

int sum=0;

while (number >0) {

int digit= number%10;

sum+= pow(digit, length_of_number);

number /= 10;

return (sum== original_number);

intmain(){

int number;

int *ptr= &number;

printf("Enter apositive integer: ");

scanf("%d", ptr);

if(isArmstrongNumber(number)) {

printf("%disan Armstrongnumber\n", number);

}else {

printf("%disnot anArmstrongnumber\n", number);

return 0;

}Inthisprogram, isArmstrongNumber functionisused tocheck whethera given number is


anArmstrongnumberor not. It usesthe lengthfunction tofindthe number ofdigitsinthe
inputnumber, andthen usesthe lengthtocalculate the sumofthecubesof itsdigits.If the
sumofthecubesof the digitsisequaltotheoriginalnumber, the numberisconsideredan
Armstrongnumber.Thepointerptrisusedtostore the addressof the variable numberand
then the value ofnumberisobtainedusingthe pointer.

15c)
Write a Cprogramtoprint allperfect numbersbetween1 toNusingauser-define function
void all_perfects(int).

#include <stdio.h>

void all_perfects(intn) {

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

int sum=0;

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

if (i%j == 0) {

sum+= j;

if(sum== i){

printf("%disa perfectnumber\n", i);

intmain(){

int n;

printf("Enter apositive integer: ");

scanf("%d", &n);

all_perfects(n);

return 0;

In thisprogram, the user-definedfunction all_perfectsisusedtoprint allperfect numbers


between 1andN.The functionusesanestedlooptocheck ifthe sumofallpositive divisorsof
a number isequaltothe number itself.Ifthe sumisequaltothe number, the numberis
considereda perfectnumber andisprinted.The value ofN istakenasinput fromthe userand
passedtothefunction all_perfects.
16a)

Write a Cprogramtoremove afile fromthe disk

#include <stdio.h>

#include <stdlib.h>

intmain(int argc, char *argv[])

if(argc !=2) {

printf("Usage: %s<file_name>\n", argv[0]);

return1;

if(remove(argv[1]) ==0) {

printf("%swassuccessfully deleted.\n", argv[1]);

}else {

perror("Error deletingfile");

return 0;

Thisprogramtakesa single argument, the nameofthe filetobe deleted, andusestheremove


function fromstdlib.htodelete it. If the file issuccessfullydeleted, amessage isprinted
indicatingthis. Ifthereisan error deletingthefile, the perrorfunction isusedtodisplay a
message indicatingthe error thatoccurred.

16b)

Write a Cprogramtofindwhetherthe given positive number isa strongnumberor notusing


pointers

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

intfactorial(int num)

{
int result =1;

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

result *=i;

return result;

intisStrongNumber(int*num)

int original= *num;

int sum=0;

while (*num> 0) {

int digit= *num%10;

sum+= factorial(digit);

*num /=10;

return (original== sum);

intmain()

int num;

printf("Enter apositive integer: ");

scanf("%d", &num);

if(isStrongNumber(&num)) {

printf("%disa strongnumber.\n", num);

}else {

printf("%disnot astrong number.\n", num);

return 0;

}
Thisprogramtakesa positiveinteger asinputandusesa pointer todetermine whether it isa
strongnumberor not. Astrongnumber isdefinedasa number wherethesumof the
factorialsofitsdigitsisequal totheoriginal number.The isStrongNumberfunction takesa
pointer toan integerasinput andreturnsa 1ifthe numberisastrongnumberanda 0if it isnot.
The factorialfunction isusedtocalculatethefactorialof anumber. The input integerispassed
toisStrongNumberusinga pointer, andtheresultisprintedtothe console indicatingwhether
the numberisastrongnumber ornot.

16c)

Write a Cprogramtoprint allprimenumbersbetween1 toNusingauser-define functionvoid


all_primes(int)

#include<stdio.h>

intis_prime(int n)

int i;

if(n <= 1)

return0;

for(i =2;i <n;i++)

if(n%i == 0)

return0;

return 1;

void all_primes(int n)

int i;

for(i =2;i <= n;i++)

if(is_prime(i))

printf("%d", i);

intmain()

{
int n;

printf("Enter the value ofN: ");

scanf("%d", &n);

printf("All prime numbersbetween 1to%dare: ", n);

all_primes(n);

return 0;

17a)

Write a Cprogramtocountthenumberofvowelsandconsonantsin a textfile file1.txt

#include <stdio.h>

#include <ctype.h>

intmain(){

int vowels=0, consonants=0;

charc;

FILE*file;

file= fopen("file1.txt", "r");

if(file==NULL) {

printf("Error openingfile!\n");

return0;

while ((c =fgetc(file)) !=EOF) {

if(isalpha(c)) {

if (c=='a' || c== 'e' || c== 'i' || c== 'o' || c=='u' ||

c== 'A' || c== 'E' || c=='I' || c == 'O' || c == 'U') {

vowels++;

}else {

consonants++;
}

fclose(file);

printf("Numberof vowels: %d\n", vowels);

printf("Numberof consonants: %d\n", consonants);

return 0;

17b)

Write a Cprogramtofindwhetherthe given positive number isa palindrome number ornot


usingpointers

#include <stdio.h>

#include <stdbool.h>

boolisPalindrome(intnum, int*digits, intlen) {

int i;

for(i =0;i <len/2;i++) {

if(digits[i] != digits[len-i -1]) {

returnfalse;

return true;

intmain(){

int num, len =0, digits[100];

int *p= digits;

printf("Enter apositive number: ");

scanf("%d", &num);
if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

while (num> 0) {

*p=num%10;

p++;

len++;

num/=10;

if(isPalindrome(num, digits, len)) {

printf("The number isa palindrome\n");

}else {

printf("The number isnot apalindrome\n");

return 0;

17c)

Write a Cprogramtofinda positiveinteger'sfactorial usinga recursivefunction.

#include <stdio.h>

unsignedlonglongfactorial(unsignedint n){

if(n == 0) {

return1;

return n* factorial(n -1);

intmain(){

unsignedintnum;
printf("Enter apositive integer: ");

scanf("%u", &num);

if(num<0) {

printf("Error: Nota positive integer\n");

return0;

printf("%u!=%llu\n", num, factorial(num));

return 0;

18a)

Write a Cprogramtocopya stringfrom str1tostr2 variablewithout usinga pre-defined


function

#include <stdio.h>

void copyString(char *str1, char*str2) {

while (*str1!='\0') {

*str2 =*str1;

str1++;

str2++;

*str2 ='\0';

intmain(){

charstr1[100], str2[100];

printf("Enter astring: ");

scanf("%s", str1);

copyString(str1, str2);

printf("Copiedstring: %s\n", str2);


return 0;

18b)

Write a Cprogramtofindwhetherthe given positive number isperfect ornot usingpointers

#include <stdio.h>

boolisPerfect(intnum, int*divisors, intlen) {

int i, sum=0;

for(i =0;i <len;i++){

sum+= divisors[i];

return (sum== num);

intmain(){

int num, len =0, divisors[100];

int *p= divisors;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

int i;

for(i =1;i <= num/ 2;i++) {

if(num%i == 0) {

*p=i;

p++;

len++;

}
}

if(isPerfect(num, divisors, len)) {

printf("The number isperfect\n");

}else {

printf("The number isnot perfect\n");

return 0;

18c)

Write a Cprogramtofindthe GCDofgiven twonumbersusinga recursivefunction.

#include <stdio.h>

intgcd(int num1, intnum2) {

if(num2== 0){

returnnum1;

return gcd(num2, num1%num2);

intmain(){

int num1, num2;

printf("Enter twopositive numbers: ");

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

if(num1<= 0|| num2<= 0) {

printf("Error: Notpositive numbers\n");

return0;

printf("GCD: %d\n", gcd(num1, num2));

return 0;

}
19a)

Write a Cprogramtocompare the given twostringswithout usinga pre-definedfunction and


then findwhetherthose twoare equalornot.

#include <stdio.h>

intcompareStrings(char*str1, char*str2) {

while (*str1!='\0' &&*str2!='\0') {

if(*str1 != *str2) {

return0;

str1++;

str2++;

return (*str1== '\0' &&*str2 == '\0');

intmain(){

charstr1[100], str2[100];

printf("Enter twostrings: ");

scanf("%s%s", str1, str2);

if(compareStrings(str1, str2)) {

printf("Stringsare equal\n");

}else {

printf("Stringsare not equal\n");

return 0;

19b)
Write a Cprogramtofindwhetherthe given positive number isa primenumber ornotusing
pointers

#include <stdio.h>

#include <stdbool.h>

boolisPrime(intnum, int *p) {

int i;

for(i =2;i <= *p;i++) {

if(num%i == 0) {

returnfalse;

return true;

intmain(){

int num;

int *p= &num;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 1){

printf("Error: Nota positive number\n");

return0;

*p= num/2;

if(isPrime(num, p)) {

printf("The number isprime\n");

}else {

printf("The number isnot prime\n");

return 0;
}

19c)

Write a Cprogramtofindthe LCMofgiven two numbersusinga recursivefunction

#include <stdio.h>

intgcd(int num1, intnum2) {

if(num2== 0){

returnnum1;

return gcd(num2, num1%num2);

intlcm(intnum1, int num2) {

return (num1 * num2) /gcd(num1, num2);

intmain(){

int num1, num2;

printf("Enter twopositive numbers: ");

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

if(num1<= 0|| num2<= 0) {

printf("Error: Notpositive numbers\n");

return0;

printf("LCM: %d\n", lcm(num1, num2));

return 0;

20a)

Write a Cprogramtofindthe lengthofa givenstringwithout usinga pre-definedfunction


#include <stdio.h>

intfindLength(char*str){

int count= 0;

while (*str !='\0') {

count++;

str++;

return count;

intmain(){

charstr[100];

printf("Enter astring: ");

scanf("%s", str);

printf("Length ofthestring: %d\n", findLength(str));

return 0;

20b)

Write a Cprogramtoprint allArmstrongnumbersbetween 1toN usingpointers

#include <stdio.h>

#include <math.h>

boolisArmstrong(int num, int*p) {

int sum=0;

int temp=*p;

int digits= 0;

while (*p!=0){

digits++;

p/= 10;
}

*p= temp;

while (*p!=0){

int lastDigit =*p%10;

sum+= pow(lastDigit, digits);

*p/= 10;

return sum== temp;

intmain(){

int num, i;

int *p= &num;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

printf("Armstrongnumbersbetween 1and%d:\n", num);

for(i =1;i <= num;i++){

*p=i;

if(isArmstrong(i, p)){

printf("%d\n", i);

return 0;

20c)
Write a Cprogramtofindthe sumofthefirst Nnatural numbersusingrecursion

#include <stdio.h>

intsum(intnum) {

if(num== 0) {

return0;

return num+ sum(num-1);

intmain(){

int num;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

printf("Sumoffirst %dnaturalnumbers: %d\n", num, sum(num));

return 0;

21a)

Write a Cprogramtoconcatenatethegiventwostringswithoutusingapre-definedfunction

#include <stdio.h>

void concatStrings(char *str1, char *str2, char*result) {

while (*str1!='\0') {

*result =*str1;

result++;

str1++;

}
while (*str2!='\0') {

*result =*str2;

result++;

str2++;

*result ='\0';

intmain(){

charstr1[100], str2[100], result[200];

printf("Enter first string: ");

scanf("%s", str1);

printf("Enter secondstring: ");

scanf("%s", str2);

concatStrings(str1, str2, result);

printf("Concatenatedstring: %s\n", result);

return 0;

21b)

Write a Cprogramtoprint allstrongnumbersbetween 1 toN usingpointers

#include <stdio.h>

#include <math.h>

intfactorial(int num){

if(num== 0) {

return1;

return num* factorial(num -1);

boolisStrong(intnum, int *p) {


int sum=0;

int temp=*p;

while (*p!=0){

int lastDigit =*p%10;

sum+= factorial(lastDigit);

*p/= 10;

return sum== temp;

intmain(){

int num, i;

int *p= &num;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

printf("Strongnumbersbetween 1 and%d:\n", num);

for(i =1;i <= num;i++){

*p=i;

if(isStrong(i, p)) {

printf("%d\n", i);

return 0;

21c)
Write a Cprogramtofindthe reverse ofa given number usingrecursion.

#include <stdio.h>

void reverse(intnum) {

if(num== 0) {

return;

printf("%d", num%10);

reverse(num/10);

intmain(){

int num;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

printf("Reverse ofthe number: ");

reverse(num);

printf("\n");

return 0;

22a)

Write a Cprogramtocopya stringfrom str1tostr2 variableusingapre-definedfunction

#include <stdio.h>

#include <string.h>

intmain(){
charstr1[100], str2[100];

printf("Enter astring: ");

scanf("%s", str1);

strcpy(str2, str1);

printf("Stringstr2: %s\n", str2);

return 0;

22b)

Write a Cprogramtoprint allpalindrome numbersbetween 1toN usingpointers

#include <stdio.h>

#include <stdbool.h>

boolisPalindrome(intnum, int*p){

int rev= 0, temp=*p;

while (*p!=0){

int lastDigit =*p%10;

rev= rev* 10+ lastDigit;

*p/= 10;

return temp==rev;

intmain(){

int num, i;

int *p= &num;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;
}

printf("Palindrome numbersbetween1 and%d:\n", num);

for(i =1;i <= num;i++){

*p=i;

if(isPalindrome(i, p)) {

printf("%d\n", i);

return 0;

22c)

Write a Cprogramtofindwhetherthe given positive number isan Armstrongnumber ornot


usingrecursion

#include <stdio.h>

#include <stdbool.h>

boolisPalindrome(intnum, int*p){

int rev= 0, temp=*p;

while (*p!=0){

int lastDigit =*p%10;

rev= rev* 10+ lastDigit;

*p/= 10;

return temp==rev;

intmain(){

int num, i;

int *p= &num;

printf("Enter apositive number: ");


scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

printf("Palindrome numbersbetween1 and%d:\n", num);

for(i =1;i <= num;i++){

*p=i;

if(isPalindrome(i, p)) {

printf("%d\n", i);

return 0;

23a)

Write a Cprogramtocompare the given twostringsusinga pre-definedfunction andthen


findwhetherthosetwoare equal ornot.

#include <stdio.h>

#include <string.h>

intmain(){

charstr1[100], str2[100];

int result;

printf("Enter first string: ");

scanf("%s", str1);

printf("Enter secondstring: ");

scanf("%s", str2);

result =strcmp(str1, str2);

if(result == 0) {
printf("Stringsare equal\n");

}else {

printf("Stringsare not equal\n");

return 0;

23b)

Write a Cprogramtoprint allperfect numbersbetween1 toNusingpointers

#include <stdio.h>

intfindSum(intnum, int*p){

int i, sum=0;

for(i =1;i <*p;i++){

if(*p%i== 0) {

sum += i;

return sum;

intmain(){

int num, i;

int *p= &num;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

printf("Perfectnumbersbetween 1 and%d:\n", num);


for(i =1;i <= num;i++){

*p=i;

if(findSum(i, p) ==i) {

printf("%d\n", i);

return 0;

23c)

Write a Cprogramtofindwhetherthe given positive number isa strongnumberor notusing


recursion

#include <stdio.h>

intfindFactorial(int num){

if(num== 0) {

return1;

return num* findFactorial(num -1);

intfindSum(intnum) {

int rem, sum= 0, temp=num;

while (num!= 0) {

rem= num%10;

sum+= findFactorial(rem);

num/=10;

return sum;

intmain(){
int num, sum;

printf("Enter apositive number: ");

scanf("%d", &num);

if(num<= 0) {

printf("Error: Nota positive number\n");

return0;

sum=findSum(num);

if(sum== num) {

printf("The number isa strongnumber\n");

}else {

printf("The number isnot astrongnumber\n");

return 0;

24a)

Write a Cprogramtofindthe lengthofa givenstringusingapre-definedfunction

#include <stdio.h>

#include <string.h>

intmain(){

charstr[100];

int length;

printf("Enter astring: ");

scanf("%s", str);

length= strlen(str);

printf("The length of the stringis: %d\n", length);

return 0;

}
24b)

Write a Cprogramtoprint allprimenumbersbetween1 toNusingpointers

#include <stdio.h>

#include <stdbool.h>

boolis_prime(int n) {

if(n <= 1)

returnfalse;

for(int i =2;i <n;i++) {

if(n%i == 0)

returnfalse;

return true;

void print_primes(int*n) {

for(int i =1;i <= *n;i++) {

if(is_prime(i)) {

printf("%d\n", i);

intmain(){

int n;

printf("Enter an integer: ");

scanf("%d", &n);

print_primes(&n);

return 0;

}
Thisprogramusesthe is_primefunctiontocheck ifa given number isprime, andthe
print_primesfunctiontoprint allprimenumbersbetween1 to N. ThevalueofN ispassedtothe
print_primesfunctionasapointer.

24c)

Write a Cprogramtofindwhetherthe given positive number isa palindrome number ornot


usingrecursion

#include <stdio.h>

boolis_palindrome(int n, int *original) {

if(n == 0) {

returntrue;

int last_digit =n %10;

int reduced_number =n /10;

if(!is_palindrome(reduced_number, original)){

returnfalse;

*original/=10;

if(last_digit !=*original%10){

returnfalse;

return true;

intmain(){

int n;

printf("Enter apositive number: ");

scanf("%d", &n);

if(is_palindrome(n, &n)) {

printf("The number isa palindrome.\n");

}else {
printf("The number isnot apalindrome.\n");

return 0;

Thisprogramusesthe is_palindromefunction tocheck if agivenpositive numberisa


palindrome number ornot.The function usesrecursiontoextractthelastdigit ofthenumber
andcompareit with the firstdigit.If the firstandlastdigitsare notequal, the numberisnota
palindrome.Ifthe firstandlastdigitsare equal, the functioncallsitselfwith the reduced
number(numberwiththelast digitremoved) untilalldigitshave beenchecked.

25a)

Write a Cprogramtoconcatenatethegiventwostringsusinga pre-definedfunction

#include <stdio.h>

#include <string.h>

void concatenate(char*destination, char*source){

int destination_length =strlen(destination);

int source_length= strlen(source);

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

destination[destination_length +i] = source[i];

intmain(){

charstr1[100], str2[100];

printf("Enter the first string: ");

scanf("%s", str1);

printf("Enter the secondstring: ");

scanf("%s", str2);

concatenate(str1, str2);

printf("The concatenatedstringis: %s\n", str1);

return 0;
}

Thisprogramusesthe concatenate function toconcatenate twostrings. Thefunction takes


twostringsasinputandaddsthe secondstring totheendofthefirst stringby copyingeach
characterfromthesource stringtothe destinationstring. Thelength ofthedestinationstring
iscalculatedusingthestrlen function fromthe string.h library, andtheforloopiteratesover
eachcharacter ofthe sourcestring, startingfromthe endof the destination string, andaddsit
tothe destination string.The finalconcatenatedstringisstoredin the str1variable andprinted.

25b)

Write a Cprogramtocountthenumberofvowelsandconsonantsin a stringusingapointer

#include <stdio.h>

#include <ctype.h>

void count_vowels_consonants(char*str, int*vowels, int*consonants) {

while (*str !='\0') {

if(isalpha(*str)){

if (toupper(*str) == 'A' || toupper(*str) =='E' || toupper(*str) =='I' ||

toupper(*str) == 'O' || toupper(*str)== 'U') {

(*vowels)++;

}else {

(*consonants)++;

str++;

intmain(){

charstr[100];

int vowels=0, consonants=0;

printf("Enter astring: ");

scanf("%s", str);
count_vowels_consonants(str, &vowels, &consonants);

printf("Vowels: %d\nConsonants: %d\n", vowels, consonants);

return 0;

Thisprogramusesthe count_vowels_consonantsfunction tocountthenumberof vowelsand


consonantsin astring. Thefunction takesastringandtwointeger pointersasinputand
iteratesovereach characterof thestringusingapointer. Ifa characterisan alphabet, the
function checksif it'sa vowel orconsonantandincrementsthecorresponding count. The
isalphafunctionfromthectype.hlibraryisusedtocheckifa characterisanalphabet, andthe
toupperfunctionisusedtoconvert the character touppercasefor checkingpurposes.The
finalcount ofvowelsandconsonantsisstoredin the vowelsandconsonantsvariablesand
printed.

25c)

Write a Cprogramtofindwhetherthe given positive number isa perfect number ornot using
recursion

#include <stdio.h>

intis_divisor(intnumber, inti) {

if(i == 1){

return1;

if(number%i== 0) {

returni + is_divisor(number, i -1);

return is_divisor(number, i -1);

intis_perfect_number(intnumber){

int sum=is_divisor(number, number /2);

if(sum== number) {

return1;

}
return 0;

intmain(){

int number;

printf("Enter apositive number: ");

scanf("%d", &number);

if(is_perfect_number(number)) {

printf("%disa perfectnumber\n", number);

}else {

printf("%disnot aperfect number\n", number);

return 0;

Thisprogramusestwofunctionsto findwhether agivenpositive numberisaperfect number


or not. Theis_divisorfunction takesanumberandaninteger asinputandrecursivelyfinds
the sumofalldivisorsofthenumber(excludingthenumberitself). Theis_perfect_number
function takesa numberasinput andcallsthe is_divisorfunction tofindthesumofdivisors.If
the sumofdivisorsisequal tothenumber, the function returns1, indicatingthatthenumberis
a perfectnumber, otherwise, itreturns0.Thefinalresultof whether the givennumber isa
perfectnumber ornotisstoredin the is_perfect_numberfunction'sreturnvalueandprinted.

26a)

Write a Cprogramtoreversethegivenstringusinga pre-definedfunction

#include <stdio.h>

#include <string.h>

void reverse_string(char *str, int start, intend) {

chartemp;

if(start>=end) {

return;

}
temp =*(str+ start);

*(str+start) =*(str+ end);

*(str+end) =temp;

reverse_string(str, start+ 1, end-1);

intmain(){

charstr[100];

printf("Enter astring: ");

scanf("%s", str);

reverse_string(str, 0, strlen(str) -1);

printf("Reversedstring: %s\n", str);

return 0;

Thisprogramusesthe reverse_stringfunctiontoreversea given string.The function takesa


stringandtwointegers(start andendindices) asinput andswapsthecharactersat the start
andendindicesusinga pointer.The functioniscalledrecursivelywithupdatedstartandend
indicesuntilthe startindexbecomesgreater thanorequaltotheendindex.The finalreversed
stringisstored in the strarray andprinted.

26b)

Write a Cprogramtosortanarrayof integersusingPointers

#include <stdio.h>

void sort_array(int*arr, intsize) {

int temp, i, j;

for(i =0;i <size-1;i++) {

for (j= i +1;j <size;j++) {

if (*(arr+ i)> *(arr +j)) {

temp= *(arr+ i);

*(arr+ i) = *(arr+ j);


*(arr+ j) = temp;

intmain(){

int arr[]= {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};

int size =sizeof(arr)/ sizeof(arr[0]);

sort_array(arr, size);

printf("Sortedarray: ");

int i;

for(i =0;i <size; i++){

printf("%d", *(arr+ i));

printf("\n");

return 0;

}Thisprogram usesthe sort_arrayfunctiontosortan arrayofintegers. Thefunction takesa


pointer toan array andthe size of the arrayasinput and sortsthe arrayusingabubble sort
algorithm. In eachiteration, thefunction comparestwoadjacentelementsandswapsthemif
the firstelementisgreaterthan the secondelement. Thefinalsortedarrayisstoredinthearr
array andprinted.

26c)

Write a Cprogramtofindwhetherthe given positive number isa primenumber ornot

#include <stdio.h>

intis_prime(int num) {

int i;

if(num<= 1){

return0;
}

for(i =2;i <num;i++) {

if(num%i == 0) {

return0;

return 1;

intmain(){

int num;

printf("Enter apositive number: ");

scanf("%d", &num);

if(is_prime(num)) {

printf("%disa primenumber\n", num);

}else {

printf("%disnot aprime number\n", num);

return 0;

Thisprogramusesthe is_primefunctiontocheck whethera givenpositivenumberisa prime


numberor not. Thefunction takesanumberasinputandreturns1 ifthenumberisprime, and
0otherwise.The functionchecksifthenumberislessthan orequalto1, andifso, it returns0.
If the number isgreaterthan 1, the functionchecksifthenumber isdivisible byanyinteger
from2 to num-1.Ifthe numberisdivisible by anyofthese integers, itreturns0, otherwise it
returns1.The result ofthe is_primefunction ischeckedin the mainfunction andtheoutputis
printedaccordingly.

27a)

Write a Cprogramtoreversethegivenstringwithout usinga pre-definedfunction

#include <stdio.h>

#include <string.h>
void reverse_string(char *str) {

int i, j;

chartemp;

for(i =0, j =strlen(str) -1;i< j;i++, j--){

temp= *(str+i);

*(str +i) =*(str+ j);

*(str +j) =temp;

intmain(){

charstr[100];

printf("Enter astring: ");

scanf("%s", str);

reverse_string(str);

printf("Reversedstring: %s\n", str);

return 0;

Thisprogramusesthe reverse_stringfunctiontoreversea given string.The function takesa


pointer toa stringasinputandreversesthestringin place. Thefunction usestwopointers, i
andj, totraversethestringfromboth ends. The functionswapsthe charactersatthetwo
pointersandmovesthe pointerstowardsthe centeruntilthepointersmeet. The reversed
stringisstored in the same strarrayandprinted.

27b)

Write a Cprogramtodemonstratehowa functionreturningapointer

#include <stdio.h>

int*largest(int*a, intn) {

int i, max=a[0];

int *p= &a[0];

for(i =1;i <n;i++) {


if(a[i] > max){

max=a[i];

p=&a[i];

return p;

intmain(){

int i, n;

int a[100];

printf("Enter the number ofelements: ");

scanf("%d", &n);

printf("Enter the elements: ");

for(i =0;i <n;i++) {

scanf("%d", &a[i]);

int *p= largest(a, n);

printf("Largest element: %d\n", *p);

return 0;

Thisprogramdemonstrateshowa functioncanreturn a pointer. The largestfunctiontakes


anarrayaofintegersandthenumberofelementsnasinputandreturnsapointertothe
largestelementin the array.The functioninitializesthemaxvariable tothefirst element ofthe
array andtheppointertothe addressof the first element. Thefunction then loopsthrough the
rest oftheelementsandupdatesmaxandpifa larger element isfound.The function returns
the ppointer atthe end.The mainfunction callsthe largestfunction, storestheresultin the p
pointer, andprintsthelargestelementusingthe ppointer.

27c)

Write a Cprogramtointerchange the largest andsmallestnumbersin aninteger array.

#include <stdio.h>
void interchange(int *a, intn) {

int i, min =a[0], max=a[0];

int min_index=0, max_index=0;

for(i =1;i <n;i++) {

if(a[i] < min){

min= a[i];

min_index= i;

if(a[i] > max){

max=a[i];

max_index= i;

a[min_index] = max;

a[max_index] = min;

intmain(){

int i, n;

int a[100];

printf("Enter the number ofelements: ");

scanf("%d", &n);

printf("Enter the elements: ");

for(i =0;i <n;i++) {

scanf("%d", &a[i]);

interchange(a, n);

printf("Interchangedarray: ");

for(i =0;i <n;i++) {

printf("%d", a[i]);
}

printf("\n");

return 0;

Thisprogramdemonstrateshowtointerchange the largest andsmallestnumbersin an


integerarray. Theinterchangefunction takesan arrayaofintegersandthe numberof
elementsn asinputandinterchangesthe largest andsmallestnumbersin the array inplace.
The functioninitializesthemin andmaxvariablesto thefirst element ofthearrayandthe
min_indexandmax_indexvariablestothe indexofthe firstelement.The functionthen loops
through the restofthe elementsand updatesmin, max, min_index, andmax_indexif a
smallerorlargerelement isfound.The functioninterchangesthesmallestandlargest
elementsusingthe indicesattheend. Themain functioncallsthe interchange function, prints
the interchangedarray, andreturns.

28a)

Write a Cprogramtosortanarrayof nstrings

#include <stdio.h>

#include <string.h>

void sort_strings(char**a, intn) {

int i, j;

char*temp;

for(i =0;i <n -1;i++) {

for (j= i +1;j <n;j++) {

if (strcmp(a[i], a[j]) > 0) {

temp= a[i];

a[i] =a[j];

a[j] =temp;

}
intmain(){

int i, n;

char*a[100];

charstr[100];

printf("Enter the number ofstrings: ");

scanf("%d", &n);

printf("Enter the strings: \n");

for(i =0;i <n;i++) {

scanf("%s", str);

a[i] = strdup(str);

sort_strings(a, n);

printf("Sortedstrings: \n");

for(i =0;i <n;i++) {

printf("%s\n", a[i]);

return 0;

Thisprogramdemonstrateshowtosortanarrayof nstrings. The sort_stringsfunction takes


anarrayof stringsaandthe number ofstringsnasinputandsortsthestringsinlexicographic
order. Thefunction usesthestrcmpfunction fromthestring.hlibrary tocompare twostrings
andsort them. Themain functioncallsthe sort_stringsfunction, printsthe sortedstrings, and
returns.Notethatthe stringsare storedinthearrayofpointersausingthestrdupfunction
fromthestring.hlibrary, whichduplicatesthe strings.

28b)

Write a Cprogramtocompute the sumofall elementsinan arrayusingpointers

#include <stdio.h>

intsum_array(int*a, intn) {

int i, sum=0;
for(i =0;i <n;i++) {

sum+= *(a+ i);

return sum;

intmain(){

int i, n, a[100], total;

printf("Enter the number ofelements: ");

scanf("%d", &n);

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

for(i =0;i <n;i++) {

scanf("%d", &a[i]);

total= sum_array(a, n);

printf("The sum ofallelementsis: %d\n", total);

return 0;

Thisprogramdemonstrateshowtocompute the sumofall elementsinan arrayusing


pointers.The sum_arrayfunctiontakesan arrayofintegersaand the number ofelementsn
asinput andcomputesthesumof allelementsin the array. The functionusesaloopto
traversetheelementsof the array andaddseach element tothesum. The main function calls
the sum_arrayfunction, printsthesumof allelements, andreturns.Notethatthe pointer a
pointstothe firstelement ofthe arrayandthepointerarithmeticisusedtoaccesseach
elementof the array.

28c)

Write a Cprogramtosearch foranelementin aninteger array

#include <stdio.h>

intsearch(int*a, intn, int key) {

int i;

for(i =0;i <n;i++) {


if(*(a +i) == key) {

returni;

return -1;

intmain(){

int i, n, a[100], key, index;

printf("Enter the number ofelements: ");

scanf("%d", &n);

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

for(i =0;i <n;i++) {

scanf("%d", &a[i]);

printf("Enter the key tosearch: ");

scanf("%d", &key);

index= search(a, n, key);

if(index== -1) {

printf("Elementnot found\n");

}else {

printf("Elementfoundat index%d\n", index);

return 0;

Thisprogramdemonstrateshowtosearch foranelementin aninteger array. The search


function takesan array ofintegersa, thenumberofelementsn, and thesearchkeykeyas
inputandreturnstheindexofthefirstoccurrence ofthe search keyinthearray. Ifthesearch
keyisnotfound, thefunction returns-1. The main function callsthesearchfunction, printsthe
result, andreturns. Note that the pointerapointstothefirstelement ofthe arrayandthe
pointer arithmeticisusedtoaccesseachelementofthe array.
29a)

Write a Cprogramtofindthe frequencyofeach unique characterina string.

#include <stdio.h>

#include <string.h>

#define MAX_CHARS256

void countFrequency(char*str) {

int count[MAX_CHARS];

int i, len =strlen(str);

for(i =0;i <MAX_CHARS;i++) {

count[i] =0;

for(i =0;i <len;i++){

count[str[i]]++;

for(i =0;i <MAX_CHARS;i++) {

if(count[i] > 0) {

printf("'%c' occurs%dtimes\n", i, count[i]);

intmain(){

charstr[100];

printf("Enter astring: ");

scanf("%s", str);

countFrequency(str);

return 0;

}
Thisprogramdemonstrateshowtofindthe frequencyofeach unique characterina string.
The countFrequencyfunctiontakesa stringstr asinput, createsanarraycount tostorethe
frequencyofeach character, initializesthe frequencyofeach characterto0, andthen
iteratesthroughthestringtocountthefrequencyof each character. Finally, thefunction
printsthe frequency ofeach uniquecharacter.The mainfunction readsthe stringfromthe
user, callsthe countFrequencyfunction, andreturns.

29b)

Write a Cprogramtoprint the elementsofan array in reverse orderusingpointers

#include <stdio.h>

void reverseArray(int*arr, intsize) {

int *end=arr +size-1;

while (end> arr) {

int temp= *arr;

*arr= *end;

*end= temp;

arr++;

end--;

intmain(){

int size, i;

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

scanf("%d", &size);

int arr[size];

printf("Enter %delements: ", size);

for(i =0;i <size; i++){

scanf("%d", &arr[i]);

reverseArray(arr, size);
printf("The elementsofthearrayin reverse orderare: ");

for(i =0;i <size; i++){

printf("%d", arr[i]);

return 0;

Thisprogramdemonstrateshowtoprint the elementsofan array in reverse orderusing


pointers.The reverseArrayfunctiontakesa pointertoaninteger arrayarranditssize sizeas
input, andreversestheorderof the elementsinthearray. Themain functionreadsthe sizeof
the array andtheelementsofthe array fromthe user, callsthe reverseArrayfunction to
reverse the order ofthe elements, andprintsthe elementsofthearrayin reverse order.

29c)

Write a Cprogramtosortanarrayof Nelements

#include <stdio.h>

void bubbleSort(int*arr, intsize) {

int i, j;

for(i =0;i <size-1;i++) {

for (j= 0;j <size-i -1;j++) {

if (arr[j] > arr[j +1]) {

int temp= arr[j];

arr[j] =arr[j +1];

arr[j +1] =temp;

intmain(){

int size, i;

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


scanf("%d", &size);

int arr[size];

printf("Enter %delements: ", size);

for(i =0;i <size; i++){

scanf("%d", &arr[i]);

bubbleSort(arr, size);

printf("The sortedarray in ascendingorderis: ");

for(i =0;i <size; i++){

printf("%d", arr[i]);

return 0;

Thisprogramdemonstrateshowtosortanarrayof Nelementsusinga bubble sortalgorithm.


The bubbleSortfunction takesa pointertoaninteger arrayarranditssize size asinput, and
sortstheelementsin ascendingorderusingabubble sort algorithm. Themain functionreads
the size ofthearrayandthe elementsofthearrayfromtheuser, callsthebubbleSort function
tosort the elements, andprintsthesortedelementsofthearray.

30a)

Write a Cprogramtodeletea characterfromall itsoccurrencesina string

#include <stdio.h>

#include <string.h>

void deleteChar(char *str, charc) {

int i, j;

int len =strlen(str);

for(i =0;i <len;i++){

if(str[i]== c) {

for (j= i;j< len -1;j++) {

str[j] = str[j+ 1];


}

len--;

i--;

str[len] ='\0';

intmain(){

charstr[100];

charc;

printf("Enter astring: ");

scanf("%s", str);

printf("Enter acharactertodelete: ");

scanf(" %c", &c);

deleteChar(str, c);

printf("The stringafterdeletingalloccurrencesof '%c' is: %s\n", c, str);

return 0;

Thisprogramdemonstrateshowtodeletea specifiedcharacterfrom allitsoccurrencesin a


string.The deleteCharfunction takesa pointertoastringstrandacharactercasinput, and
deletesalloccurrencesofthecharactercfromthe string.The mainfunction readsa string
andacharacterfrom the user, callsthedeleteCharfunctiontodeleteall occurrencesofthe
characterfromthestring, andprintsthe modifiedstring.

30b)

Write a CprogramtoreadN stringsandsortthemin lexicalorderusingan array ofpointers.

#include <stdio.h>

#include <string.h>

#define MAX_STRINGS100

#define MAX_LENGTH 100


intcompareStrings(const void*a, const void*b){

return strcmp(*(char **)a, *(char **)b);

intmain(){

int n;

charstrings[MAX_STRINGS][MAX_LENGTH];

char*sortedStrings[MAX_STRINGS];

printf("Enter the number ofstrings: ");

scanf("%d", &n);

printf("Enter %dstrings:\n", n);

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

scanf("%s", strings[i]);

sortedStrings[i] =strings[i];

qsort(sortedStrings, n, sizeof(char*), compareStrings);

printf("Sortedstrings:\n");

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

printf("%s\n", sortedStrings[i]);

return 0;

In thisprogram, the compareStringsfunctioncomparestwostringsandreturnsthe result of


the strcmpfunction, whichcomparestwostringslexicographically.The mainfunction reads
nstringsfromthe user, storestheminthestringsarray, andsetstheelementsofthe
sortedStringsarraytopointtothe correspondingelementsofthe stringsarray. Thenit sorts
the sortedStringsarrayusingthe qsortfunction, whichsortsan array ofelementsusingthe
comparison functionspecifiedasthefourthargument.Finally, it printsthesortedstrings.

30c)

Write a Cprogramtofindthe transpose ofa given matrix.


#include <stdio.h>

#define MAX_ROWS100

#define MAX_COLS100

void transpose(introws, intcols, intmat[][MAX_COLS], int transposed[][MAX_ROWS]) {

int i, j;

for(i = 0;i <rows;i++) {

for(j =0;j <cols;j++){

transposed[j][i] =mat[i][j];

intmain(){

int rows, cols, i, j;

int mat[MAX_ROWS][MAX_COLS], transposed[MAX_ROWS][MAX_COLS];

printf("Enternumberof rowsandcolumns: ");

scanf("%d%d", &rows, &cols);

printf("Enterthematrix:\n");

for(i = 0;i <rows;i++) {

for(j =0;j <cols;j++){

scanf("%d", &mat[i][j]);

transpose(rows, cols, mat, transposed);

printf("Thetransposedmatrixis:\n");

for(i = 0;i <cols;i++) {

for(j =0;j <rows;j++) {

printf("%d", transposed[i][j]);
}

printf("\n");

return0;

31a)

Write a CprogramtoDemonstrate call-by-value andcall-by-reference

#include <stdio.h>

void swap_val(inta, intb)

int temp=a;

a =b;

b=temp;

void swap_ref(int *a, int *b)

int temp=*a;

*a =*b;

*b= temp;

intmain()

int x=10, y =20;

printf("Before call-by-value: x= %d, y= %d\n", x, y);

swap_val(x, y);

printf("Aftercall-by-value: x=%d, y= %d\n", x, y);

printf("Before call-by-reference: x=%d, y =%d\n", x, y);

swap_ref(&x, &y);
printf("Aftercall-by-reference: x=%d, y =%d\n", x, y);

return 0;

The output oftheprogramwillbe:

Before call-by-value: x= 10, y= 20

Aftercall-by-value: x=10, y= 20

Before call-by-reference: x=10, y =20

Aftercall-by-reference: x=20, y =10

In the above program, swap_val demonstratescall-by-value andswap_refdemonstrates


call-by-reference.Incall-by-value, the valuesofthe variablesarepassedtothe function,
butanychangesmadetothevaluesinsidethefunction are notreflectedoutside the function.
Ontheotherhand, in call-by-reference, the addressesofthevariablesare passedtothe
function andanychangesmadetothe valuesinside the function are reflectedoutsidethe
function.

31c)

Write a Cprogramformultiplyingthe given twomatrices.

#include <stdio.h>

intmain(){

int m, n, p, q, c, d, k, sum=0;

int first[10][10], second[10][10], multiply[10][10];

printf("Enter the number ofrowsandcolumnsoffirst matrix\n");

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

printf("Enter the elementsoffirst matrix\n");

for(c= 0;c<m;c++)

for (d=0;d <n;d++)

scanf("%d", &first[c][d]);

printf("Enter the number ofrowsandcolumnsofsecond matrix\n");

scanf("%d%d", &p, &q);


if(n !=p)

printf("The matricescan'tbe multipliedwith eachother.\n");

else {

printf("Enter theelementsofsecondmatrix\n");

for (c=0;c<p; c++)

for (d=0;d< q;d++)

scanf("%d", &second[c][d]);

for (c=0;c<m;c++) {

for (d=0;d< q;d++){

for (k = 0;k <p;k++){

sum= sum+first[c][k] * second[k][d];

multiply[c][d]= sum;

sum= 0;

printf("Productofthe matrices:\n");

for (c=0;c<m;c++) {

for (d=0;d< q;d++)

printf("%d\t", multiply[c][d]);

printf("\n");

return 0;

Thisprogramfirsttakesthenumberofrowsandcolumnsofboth matricesasinput, thenthe


elementsof the matrices.It checksifthe matricescanbemultiplied, thencalculatesthe
product andprintsthe result.
31b)

Write a Cprogramtoprint the followingpattern usinga user-definedfunctionvoid

Pattern().

SRM-UNIVERSITY

SRM-UNIVERSIT

SRM-UNIVERSI

SRM-UNIVERS

SRM-UNIVER

SRM-UNIV

SRM-UNI

SRM-UN

SRM-U

SRMSRM

SR

SR

SRM

SRMSRM-U

SRM-UN

SRM-UNI

SRM-UNIV

SRM-UNIVE

SRM-UNIVER

SRM-UNIVERS

SRM-UNIVERSI

SRM-UNIVERSIT

SRM-UNIVERSITY

#include <stdio.h>

void Pattern(int n) {
int i, j;

for(i =0;i <n;i++) {

for (j= 0;j <n -i;j++)

printf("SRM-UNIVERSITY\n"[j]);

printf("\n");

for(i =0;i <n;i++) {

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

printf("SRM-UNIVERSITY"[j +12 -n]);

printf("\n");

intmain(){

int n =15;

Pattern(n);

return 0;

The functionPattern() takesaninteger argument n whichrepresentsthe numberof


characterstobe printed. It usestwonestedloopstoprint the firsthalfofthe pattern, andthen
the secondhalf. The secondloopprintsthecharactersstarting fromthe endofthe string
"SRM-UNIVERSITY", usingthe value ofn todetermine the startingposition.

You might also like