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


  



Saturday, 24 February 2024

Tutorial 10

 Tutorial 10

Question 01

Print the following shapes using loop construct of C programming.

(i)

*

* *

* * *

* * * *

* * * * *

* * * * * *

Code

#include<stdio.h>

int main()

{

int i,j;

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

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

printf(" *");

}

printf("\n");

}

return 0;

}

Result

 *

 * *

 * * *

 * * * *

 * * * * *

 * * * * * *

(ii)

* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *

Code

#include<stdio.h>

int main()

{

int i,j;

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

for (j=1; j<=7; j++){

printf(" *");

}

printf("\n");

}

return 0;

}

Result

 * * * * * * *

 * * * * * * *

 * * * * * * *

 * * * * * * *

 * * * * * * *

(iii)

 * * * * * *

 * * * * *

 * * * *

 * * *

 * *

 *

Code

#include <stdio.h>

int main()

{

int i,j;

for (i=6; i>=1; i--){

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

printf(" *");

}

printf("\n");

}

return 0;

}


Result

* * * * * *

 * * * * *

 * * * *

 * * *

 * *

 *

(iv)

     *

    **

   ***

  ****

 *****

******

 Code

#include <stdio.h>

int main() {

    int rows = 6; 

    int i, j, k;

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

        for (k = 1; k <= rows - i; k++) {

printf(" ");

}

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

            printf("*");

        }

        printf("\n"); 

    }

    return 0;

}

Result

      *

    **

   ***

  ****

 *****

******

(v)

******

  *****

   ****

    ***

     **

      *

Code

#include <stdio.h>

int main()

{

int i,j,k;

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

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

printf(" ");

}

for(k=0; k<(6-i); k++){

printf("*");

}

printf("\n");

}

return 0;

}


Result

******

  *****

   ****

    ***

     **

      *

(vi)

1

12

123

1234

12345

Code

#include <stdio.h>

int main()

{

int i,j;

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

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

printf("%d",j);

}

printf("\n");

}

return 0;

}

Result

1

12

123

1234

12345

Question 02

Find the minimum and maximum of sequence of 10 numbers.

Code

#include <stdio.h>


int main() {

    int numbers[10];

    int i;

    int min, max;


    printf("Enter 10 numbers:\n");

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

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

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

    }

    min = max = numbers[0];

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

        if (numbers[i] < min) {

            min = numbers[i];

        }

        if (numbers[i] > max) {

            max = numbers[i];

        }

    }


    printf("Minimum number: %d\n", min);

    printf("Maximum number: %d\n", max);


    return 0;

}


Result

Enter 10 numbers:

Number 1: 45

Number 2: 60

Number 3: 70

Number 4: 25

Number 5: 20

Number 6: 10

Number 7: 12

Number 8: 68

Number 9: 55

Number 10: 90

Minimum number: 10

Maximum number: 90

*This code prompts the user to enter 10 numbers one by one. It then iterates through the array to find the minimum and maximum numbers. Finally, it prints out the minimum and maximum values. This is only for example output.

Question 03

Find the total and average of a sequence of 10 numbers.

Code

#include <stdio.h> int main() { int numbers[10]; int i; int total = 0; float average; printf("Enter 10 numbers:\n"); for (i = 0; i < 10; i++) { printf("Number %d: ", i + 1); scanf("%d", &numbers[i]); total += numbers[i]; } average = (float)total / 10; printf("Total: %d\n", total); printf("Average: %.2f\n", average); return 0; }

Result

Enter 10 numbers: Number 1: 10 Number 2: 15 Number 3: 20 Number 4: 30 Number 5: 35 Number 6: 25 Number 7: 86 Number 8: 77 Number 9: 43 Number 10: 58 Total: 399 Average: 39.90

*This version retains the functionality of the original code but removes the detailed comments for brevity. It reads 10 numbers from the user, calculates the total and average, and then prints them out. This is only for example output.

Question 04

Write a program to generate and display a table of n and n2, for integer values of n ranging from 1 to 10. Be certain to print appropriate column headings.

Code

#include <stdio.h> int main() { int n; printf(" n n^2\n"); printf("----------\n"); for (n = 1; n <= 10; n++) { printf("%2d %2d\n", n, n * n); } return 0; }

Result

 n    n^2

----------

 1     1

 2     4

 3     9

 4    16

 5    25

 6    36

 7    49

 8    64

 9    81

10    100

Question 05
A triangular number can also be generated by the formula triangular Number = n (n + 1) / 2 for any integer value of n. For example, the 10th triangular number, 55, can be generated by substituting 10 as the value for n in the preceding formula. Write a program that generates a table of triangular numbers using the preceding formula. 

Code
#include <stdio.h>

int main() {
    int n;

    printf(" n    Triangular Number\n");
    printf("------------------------\n");

    for (n = 1; n <= 10; n++) {
        int triangular_number = n * (n + 1) / 2;
        printf("%2d        %d\n", n, triangular_number);
    }

    return 0;
}


Result
 n    Triangular Number
------------------------
 1        1
 2        3
 3        6
 4        10
 5        15
 6        21
 7        28
 8        36
 9        45
10       55

Question 06
The factorial of an integer n, written n!, is the product of the consecutive integers 1
through n. For example, 5 factorial is calculated as
5! = 5 x 4 x 3 x 2 x 1 = 120

Code
#include <stdio.h>

// Function to calculate the factorial of a number
int factorial(int n) {
    int result = 1;
    for (int i = 1; i <= n; ++i) {
        result *= i;
    }
    return result;
}

int main() {
    int n;
    
    // Read the input from the user
    printf("Enter a non-negative integer: ");
    scanf("%d", &n);
    
    // Check if the input is non-negative
    if (n < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        // Calculate and print the factorial
        printf("%d! = %d\n", n, factorial(n));
    }

    return 0;
}

Result
Enter a non-negative integer: 5
5! = 120

*This code defines a function factorial that recursively calculates the factorial of a given integer n. In the main function, it prompts the user to enter a non-negative integer, calculates its factorial using the factorial function, and then prints the result. It also includes a check to ensure that the factorial is not calculated for negative numbers, as factorials are not defined for negative integers.

Question 07

Write a program to generate and print a table of  the first 10 factorials.
Code
#include <stdio.h>

int factorial(int n) {
    int result = 1;
    for (int i = 1; i <= n; ++i) {
        result *= i;
    }
    return result;
}

int main() {
    printf("Factorial Table:\n");
    printf(" n   |  Factorial\n");
    printf("-----|------------\n");
    
    for (int n = 0; n <= 9; ++n) {
        printf("%2d   |  %d\n", n, factorial(n));
    }

    return 0;
}

Result
Factorial Table:
 n   |  Factorial
-----|------------
 0   |  1
 1   |  1
 2   |  2
 3   |  6
 4   |  24
 5   |  120
 6   |  720
 7   |  5040
 8   |  40320
 9   |  362880

*This program calculates and prints a table of the first 10 factorials. It iterates from 0 to 9, calculates the factorial of each number using the factorial function, and then prints the number n and its corresponding factorial in a formatted table.

Question 08
Display the n terms of harmonic series and their sum.

1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms
Test Data :
Input the number of terms : 5
Expected Output :
1/1 + 1/2 + 1/3 + 1/4 + 1/5 +
Sum of Series up to 5 terms : 2.283334

Code
#include <stdio.h> int main() { int n; double sum = 0.0; printf("Input the number of terms: "); scanf("%d", &n); printf("Harmonic Series: "); for (int i = 1; i <= n; ++i) { if (i == n) { printf("1/%d ", i); } else { printf("1/%d + ", i); } sum += 1.0 / i; } printf("\n Sum of Series up to %d terms: %f\n", n, sum); return 0; }

Result

Input the number of terms: 10 Harmonic Series: 1/1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9 + 1/10 Sum of Series up to 10 terms: 2.928968

Question 09

Write a program to generate students repot as shown below.
Index Number     Name     Maths     Physics     Chemistry     Total     Average     Grade

In this program, for each student you have to input marks of three subjects. Students’ grade is determined according to following criteria:

a. Average >= 90% : Grade A
b. Average >= 80% : Grade B
c. Average >= 70% : Grade C
d. Average >= 60% : Grade D
e. Average >= 40% : Grade E
f. Average < 40% : Grade F  

Code
#include <stdio.h> int main() { int num_students; printf("Enter the number of students: "); scanf("%d", &num_students); printf("Index Number\tName\tMaths\tPhysics\tChemistry\tTotal\tAverage\tGrade\n"); for (int i = 0; i < num_students; ++i) { int index_number, number, maths, physics, chemistry, total; double average; char name[50], grade; printf("\nStudent %d:\n", i + 1); printf("Index Number: "); scanf("%d", &index_number); printf("Student Number: "); scanf("%d", &number); printf("Name: "); scanf("%s", name); printf("Maths Marks: "); scanf("%d", &maths); printf("Physics Marks: "); scanf("%d", &physics); printf("Chemistry Marks: "); scanf("%d", &chemistry); total = maths + physics + chemistry; average = (double) total / 3.0; if (average >= 90) grade = 'A'; else if (average >= 80) grade = 'B'; else if (average >= 70) grade = 'C'; else if (average >= 60) grade = 'D'; else if (average >= 40) grade = 'E'; else grade = 'F'; printf("%d\t%d\t%s\t%d\t%d\t%d\t%d\t%.2f\t%c\n", index_number, number, name, maths, physics, chemistry, total, average, grade); } return 0; }
Result

Enter the number of students: 10 Index Number Name Maths Physics Chemistry Total Average Grade Student 1: Index Number: 1234 Student Number: 6 Name: George Maths Marks: 75 Physics Marks: 80 Chemistry Marks: 78 1234 6 George 75 80 78 233 77.67 C Student 2: Index Number:

*This program prompts the user to input the number of students and then iterates over each student to input their information, including index number, student number, name, and marks in three subjects (Maths, Physics, and Chemistry). It then calculates the total marks and average marks of each student and determines their grade based on the average marks. Finally, it prints out the student report with all the details including total, average, and grade.

Question 10
Assume a village has 20 houses. Input electricity unit charges and calculate total
electricity bill according to the following criteria:
 For first 50 units Rs. 0.50/unit
 For next 100 units Rs. 0.75/unit
 For next 100 units Rs. 1.20/unit
 For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill
The output should be as follows:
Serial Number:     House Address     Units     Surcharge     Amount to be paid  

Code
#include <stdio.h>

int main() {
    const int num_houses = 20;
    const double surcharge_rate = 0.20;
    const double rate1 = 0.50, rate2 = 0.75, rate3 = 1.20, rate4 = 1.50;
    const int limit1 = 50, limit2 = 150, limit3 = 250;

    int units[num_houses];
    double surcharge[num_houses], total_bill[num_houses];

    printf("Enter electricity units for each house:\n");
    for (int i = 0; i < num_houses; ++i) {
        printf("House %d: ", i + 1);
        scanf("%d", &units[i]);
    }

    printf("\nSerial Number\tHouse Address\tUnits\tSurcharge\tAmount to be paid\n");

    for (int i = 0; i < num_houses; ++i) {
        double bill = 0.0;

        if (units[i] <= limit1)
            bill = units[i] * rate1;
        else if (units[i] <= limit2)
            bill = limit1 * rate1 + (units[i] - limit1) * rate2;
        else if (units[i] <= limit3)
            bill = limit1 * rate1 + 100 * rate2 + (units[i] - limit2) * rate3;
        else
            bill = limit1 * rate1 + 100 * rate2 + 100 * rate3 + (units[i] - limit3) * rate4;

        surcharge[i] = surcharge_rate * bill;
        total_bill[i] = bill + surcharge[i];

        printf("%d\t\t%d\t\t%d\t%.2lf\t\t%.2lf\n", i + 1, i + 101, units[i], surcharge[i], total_bill[i]);
    }

    return 0;
}

Question 11
Develop a program to a cashier system for a shop.
Your system should display following prompt for the cashier and the entire program is controlled according to the command given by the cashier.

Once you press S: System will display welcome message and ready for processing a bill by initializing required variables.

Once you press Q: You can shut down the cashier system.

Once you press P: Process the current customer’s shopping cart. Here, you can enter the item code, qty, unit price of the items in shopping cart and calculate and display the total

Once you finished serving to the current customer, you can press N to move to the prompt.

Code
#include <stdio.h>
#include <stdlib.h>

#define MAX_ITEMS 100

int main() {
    char option;
    int item_code, qty;
    float unit_price, total_price = 0.00;

    // Display the prompt and get the cashier's option
    do {
        printf("\nWelcome to shop name>\n");
        printf("\nPress S to Start\n");
        printf("Press Q to Quit\n");
        printf("Press P to Process Bill\n");
        printf("Your option: ");
        scanf(" %c", &option);

        switch (option) {
            case 'S':
                // Initialize variables for a new bill
                total_price = 0.00;
                printf("\nWelcome! System is ready for processing a bill.\n");
                break;
            case 'Q':
                // Quit the program
                printf("\nShutting down cashier system...\n");
                exit(0);
            case 'P':
                // Process the current customer's bill
                printf("\nEnter item code, quantity, and unit price for each item:\n");
                for (int i = 0; i < MAX_ITEMS; i++) {
                    printf("Item %d: ", i + 1);
                    scanf("%d %d %f", &item_code, &qty, &unit_price);
                    if (item_code == 0) {
                        // End of items
                        break;
                    }
                    total_price += qty * unit_price;
                }

                // Display the bill
                printf("\nTotal price: %.2f\n", total_price);
                break;
            default:
                printf("\nInvalid option. Please try again.\n");
        }
    } while (option != 'Q');

    return 0;
}

Result
Welcome to shop name>

Press S to Start
Press Q to Quit
Press P to Process Bill
Your option: S

Welcome! System is ready for processing a bill.

Welcome to shop name>

Press S to Start
Press Q to Quit
Press P to Process Bill
Your option: Q

Shutting down cashier system...

*This code is a basic example of a cashier system. It allows the cashier to start a new bill, process items, and calculate the total price. The code also includes some error checking, such as checking for invalid options and invalid item codes.

Tutorial 12

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