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

Codes

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

Codes

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

LAST GROUP EXERCISES

#include <stdio.h>

#include <ctype.h> // Include the ctype.h library for toupper() function

#define MAX_SIZE 1000 // Maximum string size

int main() {

char str[MAX_SIZE];

// Read string from user

printf("Enter a string: ");

fgets(str, MAX_SIZE, stdin); // Use stdin to read from the standard input

// Remove newline character if it's there (which fgets() reads)

size_t len = strlen(str); // Include the string.h library for strlen function

if (len > 0 && str[len - 1] == '\n') {

str[len - 1] = '\0';

// Convert string to uppercase using toupper() function

for (int i = 0; str[i]; i++) {

str[i] = toupper(str[i]);

// Print the converted string

printf("Uppercase String: %s\n", str); // Use %s to print a string

return 0;

#include <stdio.h>

#include <stdbool.h>

#include <ctype.h>

// Structure to store employee information

struct Employee {

char full_name[100];

char sex;
char cellphone_number[15];

int employee_id;

char marital_status;

};

// Function to validate and get employee information

void getEmployeeInfo(struct Employee *employee) {

printf("Enter Full Name: ");

fgets(employee->full_name, sizeof(employee->full_name), stdin);

do {

printf("Enter Sex (M/F): ");

scanf(" %c", &employee->sex);

employee->sex = toupper(employee->sex); // Convert input to uppercase

} while (employee->sex != 'M' && employee->sex != 'F');

printf("Enter Cellphone Number: ");

scanf("%s", employee->cellphone_number);

do {

printf("Enter Employee ID: ");

if (scanf("%d", &employee->employee_id) != 1) {

printf("Invalid input. Please enter a valid employee ID.\n");

while (getchar() != '\n'); // Clear input buffer

} while (employee->employee_id < 1000); // Assuming employee IDs must be at least 1000

do {

printf("Enter Marital Status (S for Single, M for Married): ");

scanf(" %c", &employee->marital_status);

employee->marital_status = toupper(employee->marital_status); // Convert input to uppercase

} while (employee->marital_status != 'S' && employee->marital_status != 'M');

// Function to display employee information


void displayEmployeeInfo(struct Employee employee) {

printf("\nEmployee Information:\n");

printf("Full Name: %s", employee.full_name);

printf("Sex: %c\n", employee.sex);

printf("Cellphone Number: %s\n", employee.cellphone_number);

printf("Employee ID: %d\n", employee.employee_id);

printf("Marital Status: %c\n", employee.marital_status);

int main() {

struct Employee employee;

printf("Welcome to the Employee Registration Page\n");

getEmployeeInfo(&employee); // Get employee information

displayEmployeeInfo(employee); // Display the entered information

return 0;

#include <stdio.h>

#include <ctype.h> // Include the ctype.h library for character type checking

void determineInputType(char input);

int main() {

char input;

// Request user input

printf("Enter a single character or digit: ");

scanf(" %c", &input); // Use %c to read a single character, and add a space before %c to skip leading

whitespace

// Determine the type of input

determineInputType(input);

return 0;

void determineInputType(char input) {


if (isdigit(input)) {

printf("You entered an integer.\n");

} else if (isalpha(input)) {

printf("You entered a character.\n");

} else {

printf("You entered a special character.\n");

#include <stdio.h>

#include <string.h>

// Function to provide responses based on user queries

void respondToUserQuery(const char* query) {

if (strstr(query, "programs") != NULL) {

printf("CPUT offers a wide range of programs in the faculties of engineering, computing, and

architecture.\n");

} else if (strstr(query, "registration") != NULL) {

printf("To register at CPUT, please visit our official website and follow the registration

instructions.\n");

} else if (strstr(query, "bursary") != NULL) {

printf("CPUT provides bursary opportunities to eligible students. You can find more information on

our financial aid office's website.\n");

} else {

printf("I'm sorry, I couldn't understand your query. Please ask about EBE programs, registration, or

bursary opportunities.\n");

int main() {

printf("Welcome to the CPUT Chatbot. How can I assist you today? (Type 'exit' to quit)\n");

char user_input[100];
while (1) {

printf("You: ");

fgets(user_input, sizeof(user_input), stdin);

user_input[strcspn(user_input, "\n")] = '\0'; // Remove the newline character

if (strcmp(user_input, "exit") == 0) {

printf("CPUT Chatbot: Goodbye!\n");

break;

respondToUserQuery(user_input);

return 0;

#include <stdio.h>

union Data {

int i;

float f;

char str[20]; // Use a character array to store a string

};

int main() {

union Data data;

data.i = 10;

printf("Data as integer: %d\n", data.i);

data.f = 3.14;

printf("Data as float: %f\n", data.f); // Use %f to print a float

strcpy(data.str, "Hello, Union!"); // Use the strcpy function to copy a string

printf("Data as string: %s\n", data.str);

return 0;

#include <stdio.h>
// Define a structure named "Person" to represent a person's information

struct Person {

char name[50];

int age;

float height;

};

int main() {

// Declare a variable of type "struct Person"

struct Person person1;

// Assign values to the members of the structure

strcpy(person1.name, "John");

person1.age = 30;

person1.height = 5.9;

// Access and display the structure members

printf("Name: %s\n", person1.name);

printf("Age: %d\n", person1.age);

printf("Height: %.1f feet\n", person1.height);

return 0;

Algorithm for Implementing Access Control on Registration Page:

Start

Define constants for username length limit and special characters.

Prompt the user to enter a username.

Read and store the username.

Check the length of the username.

If the length of the username is greater than 6 characters, display an error message and ask the user to

provide a valid username.

If the length is within the limit, prompt the user to enter a password.

Read and store the password.


Check the password for the presence of at least one special character.

If the password does not contain a special character, display an error message and ask the user to

provide a password with a special character.

If both the username length and password meet the criteria, display a success message and proceed

with the registration process.

End

#include <stdio.h>

#include <string.h>

#include <stdbool.h>

#define MAX_USERNAME_LENGTH 6

// Function to check if a character is a special character

bool isSpecialCharacter(char ch) {

// You can define your own set of special characters here

char specialCharacters[] = "!@#$%^&*()-_=+[]{}|;:',.<>?/";

for (int i = 0; specialCharacters[i] != '\0'; i++) {

if (ch == specialCharacters[i]) {

return true;

return false;

int main() {

char username[MAX_USERNAME_LENGTH + 1]; // +1 for the null terminator

char password[100]; // Assuming maximum password length is 100

printf("Registration Page\n");

// Get the username

printf("Enter a username (max 6 characters): ");

scanf("%s", username);
if (strlen(username) > MAX_USERNAME_LENGTH) {

printf("Username is too long. Please provide a username with a maximum of 6 characters.\n");

return 1; // Exit with an error code

// Get the password

printf("Enter a password (must contain at least one special character): ");

scanf("%s", password);

bool containsSpecialCharacter = false;

for (int i = 0; password[i] != '\0'; i++) {

if (isSpecialCharacter(password[i])) {

containsSpecialCharacter = true;

break;

if (!containsSpecialCharacter) {

printf("Password must contain at least one special character.\n");

return 1; // Exit with an error code

printf("Registration successful. Username: %s\n", username);

return 0; // Exit with success code

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define NUMBER_OF_ASSESSMENTS 5

#define PASSING_SCORE 50

#define TOTAL_STUDENTS 100000

// Macro to calculate the probability of failing the subject

#define PROBABILITY_OF_FAILURE(desired_outcomes, total_events) ((double)(desired_outcomes) /


(double)(total_events))

int main() {

srand(time(NULL)); // Seed the random number generator with the current time

int studentsBelowPassing = 0;

for (int student = 0; student < TOTAL_STUDENTS; student++) {

int totalScore = 0;

for (int assessment = 0; assessment < NUMBER_OF_ASSESSMENTS; assessment++) {

int assessmentScore = rand() % 101; // Generate a random score between 0 and 100

totalScore += assessmentScore;

int averageScore = totalScore / NUMBER_OF_ASSESSMENTS;

if (averageScore < PASSING_SCORE) {

studentsBelowPassing++;

double probability = PROBABILITY_OF_FAILURE(studentsBelowPassing, TOTAL_STUDENTS);

printf("Probability of failing the subject: %.2f\n", probability);

return 0;

#include <stdio.h>

#define VBE 0.7

#define BETA_DC 150

// Structure to store circuit components

struct CircuitComponents {

double VCC;

double RB;

double RC;

};

// Union to store calculated results


union CircuitOutput {

double IB;

double IE;

double IC;

double VCB;

double VCE;

};

// Function to calculate parameters based on user's choice

void calculateParameters(struct CircuitComponents components, union CircuitOutput *output, int

choice) {

double VB = (components.VCC * components.RB) / (components.RB + components.RC);

double VE = VB - VBE;

switch (choice) {

case 1:

output->IB = VE / components.RB;

break;

case 2:

output->IE = BETA_DC * output->IB;

break;

case 3:

output->IC = BETA_DC * output->IB;

break;

case 4:

output->VCB = VCB - VB;

break;

case 5:

output->VCE = VCB - VE;

break;

default:
printf("Invalid choice.\n");

// Function to print the calculated results

void printResult(const union CircuitOutput *output, int choice) {

switch (choice) {

case 1:

printf("Base Current (IB): %.6f A\n", output->IB);

break;

case 2:

printf("Emitter Current (IE): %.6f A\n", output->IE);

break;

case 3:

printf("Collector Current (IC): %.6f A\n", output->IC);

break;

case 4:

printf("Collector-to-Base Voltage (VCB): %.2f V\n", output->VCB);

break;

case 5:

printf("Collector-to-Emitter Voltage (VCE): %.2f V\n", output->VCE);

break;

default:

break;

int main() {

struct CircuitComponents components;

union CircuitOutput output;

printf("Enter circuit components:\n");


printf("VCC (Collector Voltage): ");

scanf("%lf", &components.VCC);

printf("RB (Base Resistor): ");

scanf("%lf", &components.RB);

printf("RC (Collector Resistor): ");

scanf("%lf", &components.RC);

printf("Choose an option to calculate:\n");

printf("1. Base Current (IB)\n");

printf("2. Emitter Current (IE)\n");

printf("3. Collector Current (IC)\n");

printf("4. Collector-to-Base Voltage (VCB)\n");

printf("5. Collector-to-Emitter Voltage (VCE)\n");

int choice;

scanf("%d", &choice);

calculateParameters(components, &output, choice);

printResult(&output, choice);

return 0;

#include <stdio.h>

struct Date {

unsigned int day;

unsigned int month;

unsigned int year;

};

int compareDates(struct Date date1, struct Date date2) {

if (date1.year > date2.year) return 1;


else if (date1.year < date2.year) return -1;

else {

if (date1.month > date2.month) return 1;

else if (date1.month < date2.month) return -1;

else {

if (date1.day > date2.day) return 1;

else if (date1.day < date2.day) return -1;

else return 0; // dates are equal

int main() {

struct Date date1 = {10, 11, 2023};

struct Date date2 = {12, 10, 2023};

int result = compareDates(date1, date2);

if (result > 0) {

printf("Date 1 is more recent.\n");

} else if (result < 0) {

printf("Date 2 is more recent.\n");

} else {

printf("Both dates are equal.\n");

return 0;

}
#include <stdio.h>

#include <string.h>

struct Employee {

char name[50];

int id;

float salary;

};

int main() {

struct Employee employees[3];

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

printf("Enter name: ");

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

printf("Enter ID: ");

scanf("%d", &employees[i].id);

printf("Enter salary: ");

scanf("%f", &employees[i].salary);

int highestSalaryIndex = 0;

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

if (employees[i].salary > employees[highestSalaryIndex].salary) {

highestSalaryIndex = i;

}
printf("Employee with highest salary:\n");

printf("Name: %s\n", employees[highestSalaryIndex].name);

printf("ID: %d\n", employees[highestSalaryIndex].id);

printf("Salary: %.2f\n", employees[highestSalaryIndex].salary);

return 0;

Write a program to store the roll no. (starting from 1), name and age of 5 students and then print the
details of the student with roll no. 2.

#include <stdio.h>

int main()

int i;

struct student

int roll_no;

char name[30];

int age;

};

struct student stud[5];

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

printf("Student %d\n",i+1);

stud[i].roll_no = i+1;

printf("Enter name :\n");

scanf("%s",stud[i].name);
printf("Enter age :\n");

scanf("%d", &stud[i].age);

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

if(stud[i].roll_no == 2)

printf("Student %d\n",i+1);

printf("Roll no. : %d\n", stud[i].roll_no);

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

printf("Age. : %d\n", stud[i].age);

return 0;

#include <stdio.h>

#include <string.h>

struct Customer {

char name[50];

int accountNumber;

float balance;

};

void printCustomersWithLowBalance(struct Customer customers[], int numCustomers) {

printf("Customers with balance less than $200:\n");


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

if (customers[i].balance < 200) {

printf("%s\n", customers[i].name);

void addBalanceForRichCustomers(struct Customer customers[], int numCustomers) {

printf("Updated balances for customers with more than $1000:\n");

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

if (customers[i].balance > 1000) {

customers[i].balance += 100;

printf("%s: $%.2f\n", customers[i].name, customers[i].balance);

int main() {

struct Customer customers[15] = {

{"Alice", 1001, 150.50},

{"Bob", 1002, 2200.75},

{"Charlie", 1003, 180.20},

{"David", 1004, 1200.00},

// Add more customers as needed

};

int numCustomers = 4; // Number of customers in the array

// Task 1: Print names of customers with balance less than $200


printCustomersWithLowBalance(customers, numCustomers);

// Task 2: Add $100 to balance of customers with more than $1000 and print updated balances

addBalanceForRichCustomers(customers, numCustomers);

return 0;

#include <stdio.h>

#include <string.h>

struct Customer {

char name[50];

int accountNumber;

float balance;

};

void printCustomersWithLowBalance(struct Customer customers[], int numCustomers) {

printf("Customers with balance less than $200:\n");

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

if (customers[i].balance < 200) {

printf("%s\n", customers[i].name);

void addBalanceForRichCustomers(struct Customer customers[], int numCustomers) {

printf("Updated balances for customers with more than $1000:\n");

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


if (customers[i].balance > 1000) {

customers[i].balance += 100;

printf("%s: $%.2f\n", customers[i].name, customers[i].balance);

int main() {

struct Customer customers[15] = {

{"Alice", 1001, 150.50},

{"Bob", 1002, 2200.75},

{"Charlie", 1003, 180.20},

{"David", 1004, 1200.00},

// Add more customers as needed

};

int numCustomers = 4; // Number of customers in the array

// Task 1: Print names of customers with balance less than $200

printCustomersWithLowBalance(customers, numCustomers);

// Task 2: Add $100 to balance of customers with more than $1000 and print updated balances

addBalanceForRichCustomers(customers, numCustomers);

return 0;

}
#include<stdio.h>

int main()

printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");

int n,i = 3, count, c;

printf("\nEnter the number of prime numbers required : ");

scanf("%d", &n);

if(n >= 1)

printf("\n\nFirst %d prime numbers are : ", n);

printf("2 ");

// iteration for n prime numbers

// i is the number to be checked in each iteration starting from 3

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

// iteration to check c is prime or not

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

if(i%c == 0)

break;

if(c == i) // c is prime

{
printf("%d ", i);

count++; // increment the count of prime numbers

printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");

return 0;

#include<stdio.h>

int main()

printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");

float a, b, c;

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

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

if(a >= b && a >= c)

/*

%.3f prints the floating number

upto 3 decimal places

*/

printf("\n\nLargest number = %.3f ", a);

else if(b >= a && b >= c)

{
printf("\n\nLargest number is = %.3f", b);

else

printf("\n\nLargest number is = %.3f", c);

printf("\n\n\t\t\tCoding is Fun !\n\n\n");

return 0;

#include <stdio.h>

struct Date {

int day;

int month;

int year;

};

void addDaysToDate(struct Date *date, int daysToAdd) {

date->day += daysToAdd;

// Update month and year if the day exceeds the maximum days in a month

while (date->day > 31) {

if ((date->month == 4 || date->month == 6 || date->month == 9 || date->month == 11) && date-


>day > 30) {

date->day -= 30;

date->month++;
} else if (date->month == 2) {

// Check for leap year

if ((date->year % 4 == 0 && date->year % 100 != 0) || (date->year % 400 == 0)) {

if (date->day > 29) {

date->day -= 29;

date->month++;

} else {

if (date->day > 28) {

date->day -= 28;

date->month++;

} else {

date->day -= 31;

date->month++;

// Update year if the month exceeds December

if (date->month > 12) {

date->month -= 12;

date->year++;

int main() {

struct Date currentDate = {5, 11, 2023}; // Assuming current date is November 5, 2023

int daysToAdd = 45;


// Add 45 days to the current date

addDaysToDate(&currentDate, daysToAdd);

printf("Current Date: %d/%d/%d\n", currentDate.day, currentDate.month, currentDate.year);

return 0;

#include <stdio.h>

#include <string.h>

int main() {

char sentence[100];

int vowelCount = 0;

printf("Enter a sentence: ");

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

for (int i = 0; i < strlen(sentence); i++) {

char ch = sentence[i];

// Check if the character is a vowel (lowercase or uppercase)

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

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

vowelCount++;

}
printf("Number of vowels in the sentence: %d\n", vowelCount);

return 0;

#include <stdio.h>

struct Person {

char name[50];

int age;

float height;

};

int main() {

struct Person person[3];

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

printf("Enter name: ");

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

printf("Enter age: ");

scanf("%d", &person[i].age);

printf("Enter height: ");

scanf("%f", &person[i].height);

int tallestPersonIndex = 0;

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


if(person[i].height > person[tallestPersonIndex].height) {

tallestPersonIndex = i;

printf("Details of the tallest person:\n");

printf("Name: %s\n", person[tallestPersonIndex].name);

printf("Age: %d\n", person[tallestPersonIndex].age);

printf("Height: %.2f\n", person[tallestPersonIndex].height);

return 0;

// C program to demonstrate

// example of toupper() function.

#include <ctype.h>

#include <stdio.h>

int main()

int j = 0;

char str[] = "geekforgeeks\n";

char ch;

while (str[j]) {

ch = str[j];

putchar(toupper(ch));

j++;

}
return 0;

#include<stdio.h>

#include<math.h>

#include "rlc.h"

#define pi 3.142

#define pi 3.142

#ifndef RLC_H_INCLUDED

#define RLC_H_INCLUDED

double Cal_impedance(double fc,double fl,double r,double *Xc,double *Xl,double *z);

double Cal_RMS_current(double z,double v);

double Cal_series_voltage(double r,double Xc,double Xl,double rms_i);

double Cal_Res_frequency(double l,double c);

double Cal_power(double rms_i, double r);

#endif // RLC_H_INCLUDED

void Cal_impedance(double fc,double fl,double r,double *Xc,double *Xl,double *z)

double Xz;

*Xc = 1/(2*pi*fc);

*Xl = 2*pi*fl;

Xz = *Xl-*Xc;

*z = sqrt((r*r)+(Xz*Xz));

double Cal_power(double rms_i, double r)


{

double P = rms_i*rms_i*r;

return P;

#define pi 3.142

double Cal_Res_frequency(double l,double c)

double f;

double s,result;

s=l*c;

result=sqrt(s);

f=1/(2*pi*result);

return f;

double Cal_RMS_current(double z,double v)

double rms_i;

rms_i=v/z;

return rms_i;

double Cal_series_voltage(double r,double Xc,double Xl,double rms_i)

double Vr = r*rms_i; double Vl = Xl*rms_i; double Vc = Xc*rms_i;

double Vz = Vl-Vc;

double Vs = sqrt((Vr*Vr)+(Vz*Vz));

return Vs;

}
int main(void)

// declare variable list

double r,l,c,f,v;

double Xc,Xl,z,rms_i,res_f,Vs,P;

// prompt user to enter circuit information

printf("Enter the value of Resistor(unit in ohm): ");

scanf("%lf",&r);

printf("Enter the value of Inductor(unit in henry): ");

scanf("%lf",&l);

printf("Enter the value of Capacitor(unit in farad): ");

scanf("%lf",&c);

printf("Enter the value of Source Voltage(unit in volt): ");

scanf("%lf",&v);

printf("Enter the value of AC Frequency(unit in Hertz): ");

scanf("%lf",&f);

// call function to perform RLC circuit calculation

Cal_impedance(f*c,f*l,r,&Xc,&Xl,&z);

rms_i=Cal_RMS_current(z,v);

Vs=Cal_series_voltage(r,Xc,Xl,rms_i);

P=Cal_power(rms_i,r);

res_f=Cal_Res_frequency(l,c);

printf("\n");

printf("************************ SOLUTION ************************\n\n");


// Print out the solution

printf("the value of XC, capacitive reactance:%f ohms\n",Xc);

printf("the value of XL, inductance reactance:%f ohms\n",Xl);

printf("the value of Z, impedance:%f ohms\n",z);

printf("the value of Irms, rms current:%f ampere\n",rms_i);

printf("the value of Vs, series voltage:%f volt\n",Vs);

printf("the value of P, power consumed:%f watts\n",P);

printf("the value of res_F, resonant frequency:%f hertz\n",res_f);

printf("\n**********************************************************\n");

#include <stdio.h>

#include <stdbool.h>

void printPrimes(int n) {

bool primes[n+1];

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

primes[i] = true;

for(int p = 2; p * p <= n; p++) {

if(primes[p] == true) {

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

primes[i] = false;

printf("Prime numbers between 2 and %d are: ", n);


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

if(primes[i]) {

printf("%d ", i);

printf("\n");

int main() {

int n;

printf("Enter the upper limit to find prime numbers: ");

scanf("%d", &n);

printPrimes(n);

return 0;

You might also like