0% found this document useful (0 votes)
4 views31 pages

Ex. 4 Lab Programs

Uploaded by

carykim46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views31 pages

Ex. 4 Lab Programs

Uploaded by

carykim46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Exercise 4a

You're playing UNO cards, suddenly a person is getting a rev card. Write a C program to
reverse the round by storing the number of players in the array.
Algorithm
Start
Initialize an array to store player IDs.
Prompt the user to enter the number of players (numPlayers).
Create a loop to input player IDs and store them in the array.
a. For i from 1 to numPlayers:
i. Prompt the user to enter the player ID for Player i.
ii. Read and store the player ID in the array at index i-1.
Display the current order of players.
Reverse the order of players in the array.
a. For i from 0 to numPlayers/2:
i. Swap the elements in the array at indices i and numPlayers - i - 1.
Display the reversed order of players.
End
Pseudocode:
1. START
2. DECLARE AN ARRAY PLAYER IDS OF SIZE 100
3. DISPLAY "ENTER THE NUMBER OF PLAYERS: "
4. READ NUMPLAYERS
5. FOR I = 1 TO NUMPLAYERS
A. DISPLAY "ENTER THE PLAYER ID FOR PLAYER " + I + ": "
B. READ PLAYERID
C. SET PLAYERIDS[I - 1] = PLAYERID
6. DISPLAY "CURRENT ORDER OF PLAYERS:"
7. FOR I = 1 TO NUMPLAYERS
A. DISPLAY "PLAYER " + I + ": " + PLAYERIDS[I - 1]
8. FOR I = 0 TO NUMPLAYERS/2
A. SWAP PLAYERIDS[I] AND PLAYERIDS[NUMPLAYERS - I - 1]
9. DISPLAY "REVERSED ORDER OF PLAYERS:"
10. FOR I = 1 TO NUMPLAYERS
A. DISPLAY "PLAYER " + I + ": " + PLAYERIDS[I - 1]
11. END
Flowchart:
Program :

#include <stdio.h>

void reverseRound(int players[], int numPlayers) {


int temp;
for (int i = 0; i < numPlayers / 2; i++) {
temp = players[i];
players[i] = players[numPlayers - i - 1];
players[numPlayers - i - 1] = temp;
}
}

int main() {
int numPlayers;

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


scanf("%d", &numPlayers);

if (numPlayers <= 0) {
printf("Invalid number of players. Please enter a positive integer.\n");
return 1; // Exit with an error code
}

int players[numPlayers];

printf("Enter player IDs:\n");


for (int i = 0; i < numPlayers; i++) {
printf("Player %d: ", i + 1);
scanf("%d", &players[i]);
}

printf("Current order of players:\n");


for (int i = 0; i < numPlayers; i++) {
printf("Player %d: %d\n", i + 1, players[i]);
}

reverseRound(players, numPlayers);

printf("Reversed order of players:\n");


for (int i = 0; i < numPlayers; i++) {
printf("Player %d: %d\n", i + 1, players[i]);
}

return 0;
}

Output:
Enter the number of players: 5
Enter player IDs:
Player 1: 101
Player 2: 102
Player 3: 103
Player 4: 104
Player 5: 105
Current order of players:
Player 1: 101
Player 2: 102
Player 3: 103
Player 4: 104
Player 5: 105
Reversed order of players:
Player 1: 105
Player 2: 104
Player 3: 103
Player 4: 102
Player 5: 101
Exercise 4b
Write a C program for Vehicle Regulation System where odd number ending vehicles can
use the road on odd days and even number ending vehicles can use the road on even days
using two separate arrays to store and display the odd and even numbers.
Algorithm:
Start
Initialize two empty arrays: oddVehicles[] and evenVehicles[].
Prompt the user to enter the total number of vehicles: totalVehicles.
Loop for i from 1 to totalVehicles:
a. Prompt the user to enter the vehicle number: vehicleNumber.
b. If vehicleNumber is odd, add it to the oddVehicles[] array.
c. If vehicleNumber is even, add it to the evenVehicles[] array.
Prompt the user to enter the current day: currentDay.
If currentDay is an odd day:
a. Display the list of odd-number-ending vehicles (oddVehicles[]) that can use the road.
If currentDay is an even day:
a. Display the list of even-number-ending vehicles (evenVehicles[]) that can use the road.
End

Pseudocode:
Initialize empty arrays oddVehicles[], evenVehicles[]
Prompt user for totalVehicles
For i from 1 to totalVehicles:
Prompt user for vehicleNumber
If vehicleNumber is odd:
Add vehicleNumber to oddVehicles[]
Else:
Add vehicleNumber to evenVehicles[]
Prompt user for currentDay
If currentDay is odd:
Display oddVehicles[] as vehicles allowed today
Else:
Display evenVehicles[] as vehicles allowed today
Flowchart
Program:
#include <stdio.h>
int main() {
int oddVehicles[100], evenVehicles[100];
int oddCount = 0, evenCount = 0;
int vehicleNumber, day;

printf("Vehicle Regulation System\n");

while (1) {
printf("Enter the vehicle number (0 to quit): ");
scanf("%d", &vehicleNumber);

if (vehicleNumber == 0) {
break;
}
printf("Enter the day (1 for odd, 2 for even): ");
scanf("%d", &day);
if (vehicleNumber % 2 == 0 && day == 2) {
evenVehicles[evenCount] = vehicleNumber;
evenCount++;
} else if (vehicleNumber % 2 != 0 && day == 1) {
oddVehicles[oddCount] = vehicleNumber;
oddCount++;
} else {
printf("Invalid input. Vehicle cannot use the road on this day.\n");
}
}
printf("Odd Number Ending Vehicles:\n");
for (int i = 0; i < oddCount; i++) {
printf("%d\n", oddVehicles[i]);
}
printf("Even Number Ending Vehicles:\n");
for (int i = 0; i < evenCount; i++) {
printf("%d\n", evenVehicles[i]);
}
return 0;
}

Output:
Vehicle Regulation System
Enter the vehicle number (0 to quit): 526
Enter the day (1 for odd, 2 for even): 1
Invalid input. Vehicles cannot use the road on this day.
Enter the vehicle number (0 to quit): 54562
Enter the day (1 for odd, 2 for even): 2
Enter the vehicle number (0 to quit): 4587
Enter the day (1 for odd, 2 for even): 1
Enter the vehicle number (0 to quit): 448
Enter the day (1 for odd, 2 for even): 1
Invalid input. Vehicles cannot use the road on this day.
Enter the vehicle number (0 to quit): 0
Odd Number Ending Vehicles:
4587
Even Number Ending Vehicles:
54562

Exercise 4c
Write a C program to do the following applications in array:
(i). Get a set of positive and negative integers from the user, replace
positive integers by 0 in the array.
(ii). Reverse the floating point numbers stored in the array.
(iii). Return the smallest value and largest value position in the array.
(iv). Search the number '5' in array and replace it with '10'

#include <stdio.h>
int main() {
int n;
// Get the number of elements in the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Declare an array of size n
float arr[n];
// Get input from the user and replace positive integers with 0
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%f", &arr[i]);
if (arr[i] > 0) {
arr[i] = 0;
}
}

// Reverse the floating-point numbers stored in the array


for (int i = 0; i < n / 2; i++) {
float temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}

// Find the smallest and largest values and their positions in the array
float smallest = arr[0];
float largest = arr[0];
int smallestPos = 0;
int largestPos = 0;

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


if (arr[i] < smallest) {
smallest = arr[i];
smallestPos = i;
}
if (arr[i] > largest) {
largest = arr[i];
largestPos = i;
}
}

// Search for the number 5 in the array and replace it with 10


for (int i = 0; i < n; i++) {
if (arr[i] == 5) {
arr[i] = 10;
}
}

// Print the modified array


printf("Modified array:\n");
for (int i = 0; i < n; i++) {
printf("%.2f ", arr[i]);
}

// Print the smallest and largest values and their positions


printf("\nSmallest value: %.2f at position %d\n", smallest, smallestPos);
printf("Largest value: %.2f at position %d\n", largest, largestPos);

return 0;
}
Output:
Enter the number of elements in the array: 6
Enter the elements of the array:
3.5
-2.0
7.2
-4.8
5.0
1.2
Modified array:
1.20 10.00 -4.80 7.20 -2.00 0.00
Smallest value: -4.80 at position 3
Largest value: 10.00 at position 1

Exercise 4d
Write C program to do the following string handling applications. a.
(i). Get favourite actor and actress name, concatenate it and display
b.
(ii). Display your name in uppercase, lowercase and as fname and
lname. c.
(iii). Count the frequency of "the" in any sentence and delete it from
the sentence.
(iv). Check whether the given string is a palindrome or not.

ALGORITHM

STEP 1: Display a menu with options:

○ Concatenate actor and actress names


○ Display name in different formats
○ Count and delete 'the' from a sentence
○ Check if a string is a palindrome
○ Exit

STEP 2: Read the user's choice.

STEP 3: Perform the selected operation based on the user's choice:

○ For option 1, concatenate actor and actress names.


○ For option 2, display name in different formats.
○ For option 3, count and delete 'the' from a sentence.
○ For option 4, check if a string is a palindrome.
○ For option 5, exit the program.

STEP4: If the user chooses to continue, repeat from step 1.

STEP5: End the program.

Top of Form

Pseudo code

START

REPEAT

DISPLAY Menu

READ choice

SWITCH choice
CASE 1: CONCATENATE actor and actress names

CASE 2: DISPLAY name in different formats

CASE 3: COUNT and DELETE 'the' from a sentence

CASE 4: CHECK if a string is a palindrome

CASE 5: EXIT

DEFAULT: DISPLAY "Invalid choice"

END SWITCH

UNTIL choice is 5

END

Flow chart
Program

#include <stdio.h>

#include <string.h>

#include <ctype.h>
// Function to concatenate actor and actress names

void concatenateNames() {

char actor[50], actress[50];

printf("Enter your favorite actor's name: ");

scanf("%s", actor);

printf("Enter your favorite actress's name: ");

scanf("%s", actress);

strcat(actor, " ");

strcat(actor, actress);

printf("Concatenated name: %s\n", actor);

// Function to display name in different formats

void formatName() {

char name[50];

printf("Enter your name: ");

scanf("%s", name);

printf("Uppercase: %s\n", strupr(name));

printf("Lowercase: %s\n", strlwr(name));

char fname[50], lname[50];


sscanf(name, "%s %s", fname, lname);

printf("First name: %s\n", fname);

printf("Last name: %s\n", lname);

// Function to count and delete the word "the" from a sentence

void countAndDeleteThe() {

char sentence[1000];

printf("Enter a sentence: ");

getchar(); // Consume newline character

fgets(sentence, sizeof(sentence), stdin);

char *ptr = sentence;

int count = 0;

while ((ptr = strstr(ptr, "the")) != NULL) {

count++;

memmove(ptr, ptr + 3, strlen(ptr + 3) + 1);

printf("Frequency of 'the': %d\n", count);

printf("Sentence without 'the': %s\n", sentence);

// Function to check if a string is a palindrome


int isPalindrome(char *str) {

int len = strlen(str);

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

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

return 0; // Not a palindrome

return 1; // Palindrome

int main() {

int choice;

do {

printf("\nString Handling Menu:\n");

printf("1. Concatenate actor and actress names\n");

printf("2. Display name in different formats\n");

printf("3. Count and delete 'the' from a sentence\n");

printf("4. Check if a string is a palindrome\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:
concatenateNames();

break;

case 2:

formatName();

break;

case 3:

countAndDeleteThe();

break;

case 4: {

char str[50];

printf("Enter a string to check for palindrome: ");

scanf("%s", str);

if (isPalindrome(str)) {

printf("%s is a palindrome.\n", str);

} else {

printf("%s is not a palindrome.\n", str);

break;

case 5:

printf("Exiting the program. Goodbye!\n");

break;

default:

printf("Invalid choice. Please try again.\n");


}

} while (choice != 5);

return 0;

Output

Enter your choice: 1

Enter your favorite actor's name: Robert

Enter your favorite actress's name: Julia

Concatenated name: Robert Julia

Enter your choice: 2

Enter your name: John Smith

Uppercase: JOHN SMITH

Lowercase: john smith

First name: John

Last name: Smith

Enter your choice: 3

Enter a sentence: The quick brown fox jumps over the lazy dog.

Frequency of 'the': 2

Modified sentence: quick brown fox jumps over lazy dog.


Enter your choice: 4

Enter a string to check for palindrome: radar

radar is a palindrome.

Enter your choice: 5

Exiting the program. Goodbye!

Exercise 4e
Write a C program for counting the total number of duplicate elements in
an array, print all the unique elements in the same array as two different
functions.

Aim:

To write a C program for counting the total number of duplicate elements in an array,
print all the unique elements in the same array as two different functions.

Algorithm:
Step 1: Input the size of an array and store into the size variable.
Step 2: Use a for loop to read the elements of an array and store them.
Step 3: To get the duplicate elements from an array, use two for loops. Set the first loop
start from 0 to size.
Step 4: Set loop to select each element of the array and compare with the corresponding
element to get the duplicate elements.
Step 5: Set for (j = i + 1; j < size; j++) and the code to find the subsequent same element
is: if (arr[i] == arr[j]).
Step 6: If any duplicate element is encountered, delete the duplicate element from an
array and the size of array is decremented by 1 such that, size = size - 1.
Step 7: Print the unique elements of an array.
Step 8: End.

Flowchart:
Program:

#include <stdio.h>

int main()

int inputArray[20], uniqueArr[20];

int i,j,k,elementCount,count=0;

printf("Enter Number of Elements in Array:");

scanf("%d",&elementCount);

printf("\nEnter %d numbers:", elementCount);

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

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

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

for(j=i+1;j<elementCount;j++)

if(inputArray[i]==inputArray[j])

count++;

for(k=j;k<elementCount-1;k++)

inputArray[k]=inputArray[k+1];

elementCount--;

j--;

}
}

printf("\n Number of duplicate elements in the array is : %d", count);

printf(" \n Array elements after deletion of the duplicate elements: ");

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

printf("%d\t",inputArray[i]);

return 0;

Output:

Enter Number of Elements in Array:4

Enter 4 numbers:2 3 2 4

Number of duplicate elements in the array is : 1

Array elements after deletion of the duplicate elements: 2 3 4

Exercise 4f
Write a C program to sort the elements in an array in both ascending
and descending order using two different functions.
AIM: To write a C program to sort the elements in an array in both
ascending and descending order using two different functions.
Algorithm:

Step1: Start.
Step 2: Enter the array size and read as n.
Step 3: Enter the array elements and read as [i].
Step 4: Print the array elements before sorting.
Step 5: Take the first element(index = 0), compare the current element with the next
element.
Step 6: Describe function for Ascending order and If the current element is greater than
the next element, swap them in temp.
Step 7: Else, If the current element is less than the next element, then move to the next
element.
Step 8: Repeat Step 5 to Step 7 until all elements are sorted.
Step 9: Describe function for Descending order: If the current element is smaller than
the next element, swap them in temp.
Step 10: Else, If the current element is greater than the next element, then move to the
next element.
Step 11: Repeat Step 9 to Step 10 until all elements are sorted.
Step 12: Stop
Flowchart:
Program:

#include <stdio.h> //including stdio.h for printf and other functions


#include<conio.h>
int main() //default function for call
{
int a[100],n,i,j;
printf("Array size: ");
scanf("%d",&n);
printf("Elements: ");

for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for (int i = 0; i < n; i++) //Loop for ascending ordering
{
for (int j = 0; j < n; j++) //Loop for comparing other values
{
if (a[j] > a[i]) //Comparing other array elements
{
int tmp = a[i]; //Using temporary variable for storing last
value
a[i] = a[j]; //replacing value
a[j] = tmp; //storing last value
}
}
}
printf("\n\nAscending : "); //Printing message
for (int i = 0; i < n; i++) //Loop for printing array data after sorting
{
printf(" %d ", a[i]);
}
for (int i = 0; i < n; i++) //Loop for descending ordering
{
for (int j = 0; j < n; j++) //Loop for comparing other values
{
if (a[j] < a[i]) //Comparing other array elements
{
int tmp = a[i]; //Using temporary variable for storing last
value
a[i] = a[j]; //replacing value
a[j] = tmp; //storing last value
}
}
}
printf("\n\nDescending : "); //Printing message
for (int i = 0; i < n; i++) //Loop for printing array data after sorting
{
printf(" %d ", a[i]); //Printing data
}

return 0; //returning 0 status to system


getch();
}

SAMPLE OUTPUT:

Array size: 10

Elements : 3 4 7 6 5 1 2 8 10 9

Ascending : 1 2 3 4 5 6 7 8 9 10

Descending : 10 9 8 7 6 5 4 3 2 1

Exercise 4g
Write a C program to find the largest and smallest number in an
array using recursion and to convert the output into a binary number.

ALGORITHM

1. Input the array elements.

2. Initialize min = max = arr[0]

3. Repeat from i = 2 to n

4. if(arr[i] > max)

5. max = arr[i]

6. if(arr[i] < min)

7. min = arr[i]

8. Print min and max.


PROGRAM:

#include<stdio.h>

int main()
{

int a[50],i,n,min,max;

printf(“\nEnter the number of elements : “);

scanf(“%d”,&n);

printf(“\nInput the array elements : “);

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

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

max=min=a[0];

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

if(a[i]>max)

max=a[i];

if(a[i]<min)

min=a[i];

printf(“\nThe smallest element is %d\n”,min);

printf(“\nThe largest element is %d\n”,max);

return 0;

SAMPLE OUTPUT:

Enter the number of elements : 5


Input the array elements : 1 2 3 4 5

The smallest element is 1

The largest element is 5

Exercise 4h
Write a C program to swap two numbers using two functions, one
using pointers and the other one without using pointers.
AIM:
To write a C program to swap two numbers using two functions, one
using pointers and the other one without using pointers.
Flowchart:

Program:

#include <stdio.h>
// Function to swap two numbers without using pointers
void swapWithoutPointers(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Function to swap two numbers using pointers


void swapWithPointers(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int num1, num2;

printf("Enter two numbers: ");


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

printf("Before swapping without pointers: num1 = %d, num2 = %d\n", num1, num2);
swapWithoutPointers(&num1, &num2);
printf("After swapping without pointers: num1 = %d, num2 = %d\n", num1, num2);

printf("Before swapping with pointers: num1 = %d, num2 = %d\n", num1, num2);
swapWithPointers(&num1, &num2);
printf("After swapping with pointers: num1 = %d, num2 = %d\n", num1, num2);

return 0;
}

Output:

Enter two numbers: 10 20


Before swapping without pointers: num1 = 10, num2 = 20
After swapping without pointers: num1 = 20, num2 = 10
Before swapping with pointers: num1 = 20, num2 = 10
After swapping with pointers: num1 = 10, num2 = 20

You might also like