Professional Documents
Culture Documents
ENG1002 Introduction To C Programming Lab Exercises 2022 23 Solutions For Demonstrators
ENG1002 Introduction To C Programming Lab Exercises 2022 23 Solutions For Demonstrators
ENG1002 Introduction To C Programming Lab Exercises 2022 23 Solutions For Demonstrators
Solution:
/*This program calculates the product of three integers*/
#include <stdio.h>
int main(void){
result= x*y*z;
Exercise 2: Write a program that requires the user to enter two integers, obtains the two numbers,
and prints their sum, product, difference, quotient and remainder.
1. State that a program will calculate the product, difference, quotient and remainder of two
integers;
2. Define the input variables x and y and output variables sum, product, difference,
quotient and remainder to be of type int;
3. Prompt the user to enter two integers;
4. Read two integers from the keyboard and store them in the variables x and y;
1
5. Compute and print the results.
Solution:
/* This program calculates the sum, product, quotient, reminder of two
integers*/
#include <stdio.h>
int main(void){
sum = x + y;
product = x * y;
quotient = x / y;
reminder = x % y;
Feel free to experiment with input/output format. Try to implement more interaction with the user if
you have time.
2
Solution:
/*This program calculates and prints user’s age*/
#include <stdio.h>
int main(void){
// Variable Declaration
// input
char x[30]; //name of user
int a; // day of birth
int b; // month or birth
int c; // year of birth
int TodaysDay; // current day
int TodaysMonth; // current month
int CurrentYear; // current year
//output
int age = 0;
3
ENG1002: Introduction to C Programming
Exercise 1: Write a program that requires the user to enter a two-digit integer, e.g., 42 and prints its
first and second digit separately.
Hint: Use the modulus operator % and the division operator /.
Successful result: if the user types in 42, the program should print: 4 2
Solution:
/*Print first and second digit separately from a two-digit int number */
#include <stdio.h>
int main(){
Exercise 2: Write a program that requires the user to enter two float numbers and calculates their
average.
Solution:
/* Given two float numbers, calculate their average */
#include <stdio.h>
int main(){
avg= (num1+num2)/2;
4
//%.2f is used for displaying output up to two decimal
printf("Average of %.2f and %.2f is: %.2f",num1, num2, avg);
return 0;
}
Exercise 3: Write a program that requires the user to enter a float number. Calculate a circumference
using the given number as a radius. Declare the number Pi as a global constant outside the main
function, like this: #define Pi 3.1415926 .
Solution:
/*Calculate circumference and area for a given radius*/
#include <stdio.h>
#define Pi 3.1415926
int main(){
ci = 2 * Pi * rad;
printf("Circumference : %f \n", ci);
Exercise 4: Write a program that requires the user to enter two integers, obtains the two numbers,
prints the largest one followed by the words "is the largest.". If the numbers are equal, print the
message "These numbers are equal." Use if statements.
Solution:
/* Enter two integers and print the largest*/
#include <stdio.h>
int main(void){
int x, y;
return 0;
}
Exercise 5: Write a program that reads an integer and determines and prints whether it is odd or even.
[Hint: Use the remainder operator %. An even number is a multiple of two. Any multiple of two leaves
a remainder of zero when divided by 2.]
Solution:
/* Enter an integer and print if is even or odd*/
#include <stdio.h>
int main(void){
int x, y;
printf("Enter an integer:\n");
scanf("%d", &x);
y= x%2;
Exercise 1-extra: Write a program that reads in two integers, determines, and prints if the first is a
multiple of the second. Use if and if…else statements.
Hint: Again, use the remainder operator %.
Solution:
/*Print if the first int is a multiple of the second int*/
#include <stdio.h>
int main(void){
int a, b, result;
if(a>b){
result=a%b;
if(result==0){
printf("%d is a multiple of %d\n", a, b);
6
}
else{
printf("%d is not a multiple of %d\n", a, b);}}
if(b>a){
result=b%a;
if(result==0){
printf("%d is a multiple of %d\n", b, a);
}
else{
printf("%d is not a multiple of %d\n", b, a);}}
return 0;
}
Exercise 2-extra: You are given three integers: a, b and c. Print True if the inequality a < b < c holds
and False otherwise.
Hint: Use the modulus operator % and the division operator /.
Solution:
/* Check if the inequality a < b < c holds */
#include <stdio.h>
int main()
{
int a, b, c;
7
Exercise 3-extra: You are given three integers. Print “They are equal” if they are equal and “They are
not equal” otherwise.
Hint: Use the != operator to check for inequality and the local or (disjunction) || operator.
Solution:
/* Check if three numbers are equal */
#include <stdio.h>
int main(){
int a, b, c;
if((a!=b) || (b!=c)){
printf("They are not equal\n");
}
else{printf("They are equal\n");}
return 0;
}
8
ENG1002: Introduction to C Programming
Exercise 1: Given an input temperature and its scale (Celsius or Fahrenheit), convert the
corresponding temperature to the other scale by using if...else statements.
Solution:
/*This program converts the input temperature to the other scale
(Celsius or Fahrenheit)*/
#include <stdio.h>
int main() {
int c, f, temp;
char type;
if(type!='F'){
c=temp; f=SH+temp*F1/F2;
printf("The temperature in Fahrenheit is : %d\n", f);
}
else{
f=temp; c=F2/F1*(temp-SH);
printf("The temperature in Celsius is : %d\n", c);
}
return 0;
}
Exercise 2: Given an input temperature and its scale (Celsius or Fahrenheit), convert the
corresponding temperature to the other scale by using switch…case statements.
Solution:
/*This program converts the input temperature to the other scale
(Celsius or Fahrenheit)*/
#include <stdio.h>
int main() {
9
printf("Enter the type: F or C\n");
scanf("%c", &type);
switch(type)
{
case 'C': c=temp; f=SH+temp*F1/F2;
printf("The temperature in Fahrenheit is : %d\n", f);
break;
Exercise 3: Given three values a ≤ b ≤ c, which are the lengths of three segments, test if they
can be the sides of a triangle using if statements. Insert the values from keyboard and print
"It's a triangle" or "It's not a triangle". Use if…else statements.
Solution:
/*This program tests if three segments can form a triangle and which
type of triangle*/
#include <stdio.h>
int main() {
triangle = (a+b>c);
if (triangle){
if((a==b) && (b==c)){
equilateral=1; isosceles=0; scalene=0;
printf("It's an equilateral triangle\n");
}
else{
if((a==b)||(b==c)||(a==c)){
equilateral=0; isosceles=1; scalene=0;
printf("It's an isosceles triangle\n");
}
else{
equilateral=0; isosceles=0; scalene=1;
10
printf("It's a scalene triangle\n");
}
}
}
else printf("It's not a triangle\n");
return 0;
}
Exercise 1-extra: Given three values a, b, c, which represent the coefficients of a second-
degree equation: a x2 + b x + c = 0 calculate the two solutions (if real) using quadratic formula
and conditional statements.
int main(){
delta = b*b-4*a*c;
if (delta>=0){
d = sqrt(delta);
x1 = (-b+d)/(2*a);
x2 = (-b-d)/(2*a);
return 0;
}
Exercise 2-extra: Write a program to input a char and check whether given character is
alphabet, digit or special character using if…else statements and ASCII values.
11
Solution:
#include <stdio.h>
int main()
{
char ch;
if((ch >= 97 && ch <= 122) || (ch >= 65 && ch <= 90))
{
printf("'%c' is alphabet.", ch);
}
else if(ch >= 48 && ch <= 57)
{
printf("'%c' is digit.", ch);
}
else
{
printf("'%c' is special character.", ch);
}
return 0;
}
12
ENG1002: Introduction to C Programming
Exercise 1: Write a program that calculates the sum of the integers from 1 to n (n is entered
by keyboard). First check with a do…while loop if the number n entered by the user is positive.
Then use the while loop for the calculation.
Solution:
/* This program calculates the sum of the integers from 1 to n */
#include <stdio.h>
int main()
{
int n, i = 1, sum = 0;
do{
printf("Enter a positive integer:\n");
scanf("%d", &n);
}while(n<=0);
while(i <= n)
{
sum += i; // sum = sum+i;
i++;
}
printf("Sum = %d",sum);
return 0;
}
Exercise 2: Write a program that utilizes a for to print the numbers from 1 to 10 side-by-side
on the same line with three spaces between numbers. Use for loop.
Solution:
/*************************************************************
* This program utilizes looping to print the numbers from
* 1 to 10 side-by-side on the same line with 3 spaces
* between each number
*************************************************************/
#include <stdio.h>
int main(void)
{
int i;
13
// start counter at 1 and repeat loop until it gets to 10
for (i = 1; i <= 10; i++)
{
/* print counter */
printf("%d ", i); //three spaces
}
Result: 1 2 3 4 5 6 7 8 9 10
Exercise 3: Write a program that utilizes loops to print the following table of values:
The tab escape sequence \t can be used in the loop to separate the columns with tabs.
Solution:
/This program prints the table above*/
#include <stdio.h>
int main() {
int n = 1, ten = 10, hundred = 100, thousand = 1000, a, b, c, d;
14
Exercise 4: Write a program to input a number and check whether the number is prime
number or not using for loop.
Example:
Input
Input any number: 17
Output
17 is prime number
Solution:
/* This program calculates if a number is prime or not*/
#include <stdio.h>
int main() {
int n, i, flag = 0;
if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}
Exercise 1-extra: Write a program that calculates a raised to the n power. The program
should use a while loop.
15
Solution:
/* This program calculates a raised to the n power*/
#include <stdio.h>
int main()
{
// Variable Declaration
int a, i, n, E;
// Initialisation
E=1;
i=1;
while(i <= n)
{
E=E*a;
i++;
}
printf("Result = %d",E);
return 0;
}
Exercise 2-extra: Write a program to read 10 numbers from keyboard and find their sum and
average.
/* This program calculates the sum and average of 10 integers*/
#include <stdio.h>
int main() {
sum = sum + a;
printf("The sum is %d\n", sum);
n++;}
while(n<10);
16
Exercise 3-extra: Write a program to input an integer and count the n of digits using loops:
Solution:
int main(){
temp = a;
Exercise 4-extra: Write a program to count frequency (total occurrences) of each digit in a
given number using loops.
Example:
17
Solution:
#include <stdio.h>
int main(){
temp = a;
if(reminder==1) one++;
if(reminder==2) two++;
if(reminder==3) three++;
if(reminder==4) four++;
if(reminder==5) five++;
if(reminder==6) six++;
if(reminder==7) seven++;
if(reminder==8) eight++;
if(reminder==9) nine++;
if(reminder==0) zero++;
temp = temp/10;
count++;
}
18
ENG1002: Introduction to C Programming
Lab 5: Functions
Exercise 1: Write a program to find the square of any number. This should be achieved by
defining a dedicated function, e.g., double square(double num), to calculate the
square, which is called in the main function. The initial number is given by the user.
Example:
Input a number: 20
The square of 20 is: 400.00
Solution:
/* This program finds the square of a number */
#include <stdio.h>
// Function declaration
double square(double num);
int main(){
double num;
double n;
n = square(num);
// Function body
double square(double num){
double sqr = num * num; //Local variable for squre
return sqr;
}
Exercise 2: Write a program that calculates the sum of the following series:
1!/1+2!/2+3!/3+4!/4+5!/5. This should be achieved by defining a dedicated function, e.g., int
fact (int n), to calculate the factorial, which is called in the main function.
Successful result:
19
Solution:
/* This program calculates the sum of the following series:
1!/1+2!/2+3!/3+4!/4+5!/5 */
#include <stdio.h>
// Function declaration
int fact(int n);
int main(){
int sum;
sum=fact(1)/1+fact(2)/2+fact(3)/3+fact(4)/4+fact(5)/5;
// Function body
int fact(int n){
int num = 0, f = 1;
while(num <= n-1){
f =f+f*num;
num++;
}
// For debugging: print the factorial
printf("Factorial: %d\n", f);
return f;
}
Exercise 3: Write a program that verifies if a three-digit number given by the user,e.g., 371, is
an armstrong number and/or a perfect number. This should be achieved by defining two
dedicated functions, e.g., int checkArmstrong(int n) and int checkPerfect(int n) , which are
called in the main function.
Example:
Input any number: 371
The 371 is an armstrong number.
The 371 is not a perfect number.
20
Solution:
#include <stdio.h>
// Functions declaration
int checkArmstrong(int n1);
int checkPerfect(int n1);
int main()
{
int n1;
printf("Function: check Armstrong and perfect numbers :\n");
21
// Checks whether a three-digits number is Armstrong number or not.
int checkArmstrong(int n1)
{
int ld, sum, num;
sum = 0;
num = n1;
while(num!=0)
{
ld = num % 10; // find the last digit of the number
22
ENG1002: Introduction to C Programming
Exercise 1: Write a program to find the length of a string without using a library function.
Optional: you can define your own function, int mystringlength(const char str[]);,
which returns the length of the passed string char str[].
Example:
Input the string : domenico.balsamo
Expected Output :
Length of the string is : 16
Solution:
#include <stdio.h>
// Function declaration
int mystringlength(const char str[]);
int main(){
int mycount = 0;
while(str[mycount]!='\0') mycount++;
return mycount;}
Exercise 2: Write a program to sort a string in ascending order. Optional: You can define
your own function, void mystringsort(char str[], int length); .
Example:
Input the string : domenico
After sorting the string appears like : cdeimnoo
23
Solution:
int main(){
char str[MAX];
int l;
gets(str);
l=strlen(str);
mystringsort(str, l);
Exercise 3: Write a program to find the sum of all elements of the array. Optional: You can
define your own function, int mysumarray(int a[], int length); for the sum operation.
Example:
Input the number of elements to be stored in the array : 3
Input 3 elements in the array :
element - 0 : 22
element - 1 : 2
element - 2 : 8
24
Expected Output :
Sum of all elements stored in the array is : 32
Solution:
// Function declaration
int mysumarray(int mya[], int length);
int main(){
int a[MAX];
int l;
int mysum = 0;
Exercise 1-extra: Write a program to find the max element in an array. Optional: You can
define your own function, int myfindmax(int a[], int length); which returns the max.
Example:
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 45
element - 1 : 25
25
element - 2 : 21
Maximum element is : 45
Solution:
// Function declaration
int myfindmax(int mya[], int length);
int main(){
int a[MAX];
int l;
return mymax;}
26
ENG1002: Introduction to C Programming
Lab 7: Files
Exercise 1: Write a program for searching a module catalogue that performs these tasks:
1. It prompts the user to enter a string to search for, for example “microprocessor”.
2. It proceeds by reading the module catalogue stored in the file modules.txt, where
each line contains a description of one module. Here is a short fragment from the file:
ENG1002 C Programming
EEE1009 Communication Skills and Innovation
EEE2007 Computer Systems and Microprocessors
3. For every line in the file, the program checks whether it contains the string. If yes, it
prints out this line.
4. When all lines have been processed, the program prints the number of found matches.
Example:
Advanced:
Implement your own string matching function, e.g., int match(char source[MAX], char
input[MAX]) , rather than using the one from <string.h> library.
Solution (Advanced):
#include <stdio.h>
#include <ctype.h>
int main(){
27
if (f == NULL) { printf("Error: cannot open file\n"); return
1;}
int x=0,y=0,z;
z=x;
while (toupper(input[y]) != '\0'){ //This loop will continue
// until sub string is
// zero
//check whether main string and
// sub string do not equal
if(toupper(source[z])!=toupper(input[y]))
break; // if yes break the loop
y++; // if no increase y and z by 1 and
// repeat
z++;}
if(toupper(input[y]) == '\0') //check whether sub
// string is zero or not
return 1; //if yes return 1
else
//anything else increase x by 1 and make y zero
{
x++;
y=0;
}
}
return 0;
// if main string is not found it returns 0
}
28
ENG1002: Introduction to C Programming
Lab 7: Pointers
#include <stdio.h>
int main(void)
{
int val[7] = {11, 22, 33, 44, 55, 66, 77};
Pictorial Presentation:
Solution:
#include <stdio.h>
int main(){
29
int e1,e2,e3;
swapNumbers(&e1,&e2,&e3);
30