Tut2 Sol
Tut2 Sol
Welcome!
I have written my first C exercise.
ANS-
#include <stdio.h>
int main() {
printf("Welcome!\n");
printf("I have written my first C exercise.\n");
return 0;
}
Exercise 2(*): Write a C program to declare one integer, one float and one character variables then
initialise them to 99, 12.34, and any letter of your choosing.
It then prints these values on the screen.
ANS-
#include <stdio.h>
int main() {
int number = 99;
float decimal = 12.34;
char letter = 'A';
printf("Integer value: %d\n", number);
printf("Float value: %.2f\n", decimal);
printf("Character value: %c\n", letter);
return 0;
}
Exercise 3(***): Write a program that asks the user to enter a two digit number andreturns as output the
number with its digits reversed. Think about how to use the right operators to do this. Display the
output as shown below.
+++++++++++++++++
*******************
ANS -
#include <stdio.h>
int main() {
int num, tens, ones, reversed;
printf("+++++++++++++++++\n");
printf("*******************\n");
return 0;
}
Exercise 4(*): Write a program that asks the user to enter a number in miles per hour and display it as
kilometres per hour.
(use or improve your programme design from last week)
ANS-
#include <stdio.h>
int main() {
float mph, kmh;
return 0;
}
Exercise 5(*): Write a program that computes the perimeter and area of a right angled triangle. Program
prompts the user to enter the height and length (not the hypotenuse).
ANS-
#include <stdio.h>
#include <math.h>
int main() {
scanf("%lf", &height);
scanf("%lf", &base);
printf("\nResults:\n");
return 0;
0.253.5355
/**************************************************/
ANS-
#include <stdio.h>
#include <math.h> // Include math library for sin() and cos()
int main() {
double x, interval, fx;
int i, num_values = 5; // Number of values to compute (modify if
needed)
// Print result
printf(" %.2f %.4f\n", x, fx);
printf("*****************************************\n");
Exercise 7(*): Write a program that prints a random number between 0 and X inclusive.The program
must prompt the user to enter the value of X.
Hint: use the rand() function.
ANS-
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int x, random_number;
srand(time(NULL));
if (x < 0) {
printf("Error: Please enter a non-negative number.\n");
return 1;
}
return 0;
}
Exercise 8(***): Write a program that takes as input two integer numbers and perform a swap
operation and displays the swapped numbers. Hint, use a third variable.
/******************************
ANS-
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter first number (a): ");
scanf("%d", &a);
temp = a;
a = b;
b = temp;
printf("\nAfter swapping:\n");
printf("a = %d, b = %d\n", a, b);
return 0;
}