Sunday, 25 February 2024

Tutorial 12

Functions 

Question 01

Display all prime numbers between two Intervals using a function.  

C Code

            #include <stdio.h>
            /*Function to check if a number is prime*/
            int isPrime(int num) 
            {
               if (num <= 1) return 0; /* 0 and 1 are not prime numbers*/
                if (num <= 3) return 1; /*2 and 3 are prime numbers*/
                /* Check if the number is divisible by any odd number from 3 to its square root*/
                for (int i = 2; i * i <= num; i++) 
                {
                    if (num % i == 0) return 0; /* If divisible, it's not prime*/
                }
                return 1; /* If not divisible by any number, it's prime*/
            }
            /*Function to display prime numbers between two intervals*/
            void displayPrimes(int lower, int upper) 
            {
                printf("Prime numbers between %d and %d are: ", lower, upper);
                for (int i = lower; i <= upper; i++) 
                {
                    if (isPrime(i)) printf("%d ", i);
                }
                printf("\n");
            }
            int main() 
            {
                int lower, upper;
                printf("Enter two intervals (separated by a space): ");
                scanf("%d %d", &lower, &upper);
                /* Validate the input*/
                if (lower >= upper) 
                {
                    printf("Invalid input. Please enter the lower limit first followed by the upper limit.\n");
                    return 1;
                }
                displayPrimes(lower, upper);
                return 0;
            }


Result

            Enter two intervals (separated by a space): 1 20
            Prime numbers between 1 and 20 are: 2 3 5 7 11 13 17 19

Explanation

*Any value can be entered. The isPrime function checks if a number is prime (1) or not (0). The  displayPrimes function finds and prints prime numbers between two given numbers. In the main function, users input two numbers and if they are valid (first is smaller than the second), it finds and prints prime numbers between them.


Question 02

Find sum of natural numbers using a recursive function.  

C Code

            #include <stdio.h>
            /* Function to calculate the sum of natural numbers using recursion*/
            int sumOfNaturalNumbers(int n) 
            {
                if (n == 1) 
                {
                    return 1;
                
                else 
                {
                    return n + sumOfNaturalNumbers(n - 1);
                }
            }
            int main() 
            {
                int n;
                printf("Enter a positive integer: ");
                scanf("%d", &n);
                if (n < 1) 
                {
                    printf("Please enter a positive integer.\n");
                
                else 
                {
                    printf("Sum of first %d natural numbers is %d.\n", n, sumOfNaturalNumbers(n));
                }
                return 0;
            }


Result 

            Enter a positive integer: 4
            Sum of first 4 natural numbers is 10.


Explanation

*Any value can be entered. This program takes a positive integer as input from the user and then calculates the sum of all natural numbers from 1 to that integer using recursion.


Question 03

Calculate the power of a number using a recursive function.  

C Code 

            #include <stdio.h>
            /* Function to calculate the power of a number using recursion*/
            double power(double base, int exponent) 
            {
                /* Base case: exponent is 0*/
                if (exponent == 0) 
                {
                    return 1;
                }
                /* If exponent is negative, invert the base and make the exponent positive*/
                if (exponent < 0) 
                {
                    base = 1 / base;
                    exponent = -exponent;
                }
                /* Recursive case: calculate power using recursion*/
                return base * power(base, exponent - 1);
            }
            int main() 
            {
                double base;
                int exponent;
                printf("Enter base and exponent: ");
                scanf("%lf %d", &base, &exponent);
                printf("Result: %.2lf^%d = %.2lf\n", base, exponent, power(base, exponent));
                return 0;
            }


Result 

            Enter base and exponent: 12 5
            Result: 12.00^5 = 248832.00


Explanation

*Any value can be used. This program takes the base and exponent as input from the user and then calculates the power of the exponent using recursion.


Question 04

Write a function to return the trip cost which calculated using the given distance in kilometers. Note: Take 35 LKR as travelling cost per kilometer. 

C Code

            #include <stdio.h>
            /* Function to calculate trip cost based on distance in kilometers*/
            double calculateTripCost(double distance) 
            {
                const double costPerKilometer = 35.0; // Cost per kilometer in LKR
                return distance * costPerKilometer;
            }
            int main() 
            {
                double distance;
                printf("Enter the distance in kilometers: ");
                scanf("%lf", &distance);
                if (distance < 0) 
                {
                    printf("Distance cannot be negative.\n");
                
                else 
                {
                    double tripCost = calculateTripCost(distance);
                    printf("The trip cost for %.2lf kilometers is %.2lf LKR.\n", distance, tripCost);
                }
                return 0;
            }


Result

            Enter the distance in kilometers: 12
            The trip cost for 12.00 kilometers is 420.00 LKR.

Explanation

*Any value can be entered. This program takes the distance in kilometers as input from the user and calculates the trip cost by multiplying the distance by the cost per kilometer (35LKR). Finally, it prints the calculated trip cost. It also includes a simple input validation to ensure that the distance entered by the user is not negative.


Question 05

Write a function to convert the LKR currency into US dollars.  

C Code

            #include <stdio.h>
            /*Function to convert LKR to USD*/
            double lkrToUsd(double lkrAmount) 
            {
                const double exchangeRate = 0.0050; /* 1 LKR = 0.0050 USD*/
                return lkrAmount * exchangeRate;
            }
            int main() 
            {
                double lkrAmount;
                printf("Enter amount in Sri Lankan Rupees (LKR): ");
                scanf("%lf", &lkrAmount);
                if (lkrAmount < 0) 
                {
                    printf("Amount cannot be negative.\n");
                
                else 
                {
                    double usdAmount = lkrToUsd(lkrAmount);
                    printf("%.2lf LKR is equal to %.2lf USD.\n", lkrAmount, usdAmount);
                }
                return 0;
            }


Result

            Enter amount in Sri Lankan Rupees (LKR): 200000
            200000.00 LKR is equal to 1000.00 USD.

Explanation

*Any value can be entered. This program takes the amount in Sri Lanka Rupees (LKR) as input from the user and converts it into US Dollars (USD) using the exchange rate. Finally, it prints the converted amount in USD. It also includes a simple input validation to ensure that the amount entered by the user is not negative.


Question 06

Write a function to input source and destination and print the ticket for the route. Note: You can decide the payment calculator logic and passengers can ask more than one ticket at a time for different destinations.

C Code

            #include <stdio.h>
            /* Function to calculate ticket price based on distance*/
            double calculateTicketPrice(char source[], char destination[]) 
            {
                /*Example logic: Assume a flat rate of 100 LKR per kilometer*/
                /*You can modify this logic as needed*/
                double distance = 0.0; // Calculate distance between source and destination
                double ticketPrice = distance * 100.0; /* 100 LKR per kilometer*/
                return ticketPrice;
            }
            /* Function to input source and destination and print the ticket*/
            void printTicket() 
            {
                char source[100], destination[100];
                printf("Enter source: ");
                scanf("%s", source);
                printf("Enter destination: ");
                scanf("%s", destination);
                /* Calculate ticket price*/
                double ticketPrice = calculateTicketPrice(source, destination);
                /* Print ticket details*/
                printf("\n********** Ticket **********\n");
                printf("Source: %s\n", source);
                printf("Destination: %s\n", destination);
                printf("Ticket Price: %.2lf LKR\n", ticketPrice);
                printf("*****************************\n\n");
            }
            int main() 
            {
                int numTickets;
                printf("How many tickets would you like to purchase? ");
                scanf("%d", &numTickets);
                if (numTickets <= 0) 
                {
                    printf("Invalid number of tickets.\n");
                
                else 
                {
                    for (int i = 0; i < numTickets; i++) 
                    {
                        printf("\n Ticket %d:\n", i + 1);
                        printTicket();
                    }
                }
                return 0;
            }


Result



Explanation

*This program allows passengers to input the source and destination for each ticket they want to purchase. It calculates the ticket price based on the distance between the source and destination. Finally, it prints the ticket details including the source, destination and ticket price.



Question 07

Write a function to input electricity unit charges and calculate total electricity bill according to the given condition: 
            a. For first 50 units Rs. 0.50/unit 
            b. For next 100 units Rs. 0.75/unit 
            c. For next 100 units Rs. 1.20/unit 
            d. For unit above 250 Rs. 1.50/unit 


C Code

            #include <stdio.h>
            /* Function to calculate the total electricity bill*/
            double calculateElectricityBill(int units) 
            {
                double bill = 0.0;   
                if (units <= 50) 
                {
                    bill = units * 0.50;
                }
                 else if (units <= 150) 
                {
                    bill = 50 * 0.50 + (units - 50) * 0.75;
                
                else if (units <= 250) 
                {
                    bill = 50 * 0.50 + 100 * 0.75 + (units - 150) * 1.20;
               
                else 
                {
                    bill = 50 * 0.50 + 100 * 0.75 + 100 * 1.20 + (units - 250) * 1.50;
                }
                return bill;
            }
            int main() 
            {
                int units;
               printf("Enter the number of units consumed: ");
               scanf("%d", &units);
                if (units < 0) 
                {
                    printf("Units consumed cannot be negative.\n");
                } 
                else 
                {
                    double billAmount = calculateElectricityBill(units);
                    printf("Total Electricity Bill: %.2lf LKR\n", billAmount);
                }
                return 0;
            }


Explanation

*This program takes the number of electricity units consumed as input from the user and calculates the total electricity bill based on the given condition. It also includes a simple input validation to ensure that the number of units entered by the user is not negative


  



No comments:

Post a Comment

Tutorial 12

Functions  Question 01 Display all prime numbers between two Intervals using a function.   C Code                #include <stdio.h>   ...