ENG1002 Introduction To C Programming Lab Exercises 2022 23 Solutions For Demonstrators

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

ENG1002: Introduction to C Programming

Lab 1: Data Types and Basic Input/output


Exercise 1: Write a program that calculates the product of three integers. The program should consider
each of the following steps:
1. State that a program will calculate the product of three integers;
2. Define the variables x, y, z and result to be of type int;
3. Prompt the user to enter three integers;
4. Read three integers from the keyboard and store them in the variables x, y and z;
5. Compute the product of the three integers contained in variables x, y and z, and assign the
result to the variable result;
6. Print "The product is" followed by the value of the integer variable result.

Solution:
/*This program calculates the product of three integers*/
#include <stdio.h>

int main(void){

int x, y, z, result; // Local Variables

printf("Enter the first integer:\n");


scanf("%d", &x);

printf("Enter the second integer:\n");


scanf("%d", &y);

printf("Enter the third integer:\n");


scanf("%d", &z);

result= x*y*z;

printf("The Product is: %d\n", result);


return 0;
}

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){

int x, y, sum, product, quotient, reminder;

printf("Enter the first integer:\n");


scanf("%d", &x);

printf("Enter the second integer:\n");


scanf("%d", &y);

sum = x + y;
product = x * y;
quotient = x / y;
reminder = x % y;

printf("The sum is: %d, product is %d, quotient is %d,


reminder is %d\n", sum, product, quotient, reminder);
return 0;
}

Exercise 3: Write a program that performs the following actions:


1. Prompts the user to input their name;
2. Prints a greeting to the user, calling them by their name;
3. Prompts the user to input the year they were born;
4. Calculates and prints the user's age.

This is an example of successful program execution:

What is your name? > Alan Turing


Hello, Alan Turing!
What year were you born? > 1912
Congratulations, you are 106 old!

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;

printf("Enter your name:");


scanf("%[^\n]", x); // This reads a string until user inputs a new
// line character, considering the white spaces
// also as string. Other option: use gets function

printf("Hello, %s!\n", x);

printf("Please enter your DOB in the format dd/mm/yyyy:\n");


scanf("%d/%d/%d", &a, &b, &c);

printf("Please enter current date in the format dd/mm/yyyy:\n");


scanf("%d/%d/%d", &TodaysDay, &TodaysMonth, &CurrentYear);

// We consider each month with an average of 30.4 days (≈365/12) to


// reach 365 days. To avoid using floats we can multiply these values
// for 10

age = ((CurrentYear*3650 + TodaysMonth*304 + TodaysDay*10) - (c*3650 +


b*304 + a*10))/3650;

printf("You are %d years old today!\n", age);


return 0;
}

3
ENG1002: Introduction to C Programming

Lab 2: Data Types and Conditional Statements

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(){

int a, units, tens;

printf("Enter two-digit int number:");


scanf("%d", &a); // Students can add checking
// on the number, is it really two-digit?

units = (a/1)%10; //Example (34/1)%10=4


tens=(a/10)%10; //Example (34/10)%10=3

printf("%d and %d \n", tens, units);


return 0;
}

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(){

float num1, num2;


float avg;

printf("Enter first float number: ");


scanf("%f",&num1);

printf("Enter second float number: ");


scanf("%f",&num2);

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(){

float rad, area, ci;

printf("Enter radius of circle:\n");


scanf("%f", &rad);

ci = 2 * Pi * rad;
printf("Circumference : %f \n", ci);

// Additional to the exercise


area = Pi * rad * rad;
printf("Area of circle : %f \n", area);
return 0;
}

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;

printf("Enter the first integer:\n");


scanf("%d", &x);

printf("Enter the second integer:\n");


scanf("%d", &y);
5
if(x==y)printf("These numbers are equal.\n");
if(x>y) printf("%d is the largest.\n", x);
if(y>x) printf("%d is largest.\n", 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;

if(y==0) printf("The number is even\n");


if(y!=0) printf("The number is odd\n");
return 0;
}

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;

printf("Enter the first integer:\n");


scanf("%d", &a);

printf("Enter the second integer:\n");


scanf("%d", &b);

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);}}

if(b==a)printf("The two numbers are equals\n");

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;

printf("Enter first number: ");


scanf("%d",&a);

printf("Enter second number: ");


scanf("%d",&b);

printf("Enter third number: ");


scanf("%d",&c);

if(a < b){


if(b < c){printf("True");}
else{printf("False");}
}
else{printf("False");}
return 0;
}

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;

printf("Enter the first int number:\n");


scanf("%d",&a);
printf("Enter the second int number:\n");
scanf("%d",&b);
printf("Enter the third int number:\n");
scanf("%d",&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

Lab 3: Data Types and Conditional Statements

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() {

const float F1 = 9.0, F2 = 5., SH=32;

int c, f, temp;
char type;

printf("Enter the type: F or C\n");


scanf("%c", &type);

printf("Enter the temperature:\n");


scanf("%d", &temp);

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() {

const float F1 = 9.0, F2 = 5., SH=32;


int c, f, temp;
char type;

9
printf("Enter the type: F or C\n");
scanf("%c", &type);

printf("Enter the temperature:\n");


scanf("%d", &temp);

switch(type)
{
case 'C': c=temp; f=SH+temp*F1/F2;
printf("The temperature in Fahrenheit is : %d\n", f);
break;

case 'F': f=temp; c=F2/F1*(temp-SH);


printf("The temperature in Celsius is : %d\n", c);
break;
default: printf("Error\n");
}
return 0;
}

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() {

//Students should get the values from input


float a = 1.5, b = 2.0, c = 4.0;

int triangle, equilateral, isosceles, scalene;

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.

/*Calculate the quadratic formula*/


#include <stdio.h>
#include <math.h>

int main(){

//Students should get the values from input


float a = 1.0, b = 2.0, c = - 15.0;
float delta, d, x1, x2;

delta = b*b-4*a*c;

if (delta>=0){
d = sqrt(delta);
x1 = (-b+d)/(2*a);
x2 = (-b-d)/(2*a);

printf("The two solutions are %f and %f\n", x1, x2);


}
else{
printf("The solutions are not real");
}

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:

/* This program checks alphabet, digit or special character using


ASCII value */

#include <stdio.h>

int main()
{
char ch;

// Input a character from user


printf("Enter any character: ");
scanf("%c", &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

Lab 4: Data Types and Loops

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);

if(n<=0) printf("ERROR: enter a positive number\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
}

// print newline character


printf("\n");
return 0;
}

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:

N 10*N 100*N 1000*N


1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
5 50 500 5000
6 60 600 6000
7 70 700 7000
8 80 800 8000
9 90 900 9000
10 100 1000 10000

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;

printf("N\t10*N\t\t100*N\t\t1000*N\n"); // \t used to shift a


// couple of spaces on the
while (n <= 10) { // same line
printf("%d\t\t", n );
a = n * ten;
printf("%d\t\t", a );
b = n * hundred;
printf("%d \t\t", b );
c = n * thousand;
printf("%d\n", c );
n++;}
return 0;}

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;

printf("Enter a positive integer: ");


scanf("%d", &n);

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

// condition for non-prime


if (n % i == 0) {
flag = 1;
break;
}
}

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;

printf("Enter a positive integer:\n");


scanf("%d",&a);

printf("Enter an n power integer:\n");


scanf("%d",&n);

// 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() {

int n=0, a, sum = 0;


float avarage = 1.0;
do{
printf("Enter the %d positive integer:", n+1);
if(scanf("%d", &a) != 1) return 1;

sum = sum + a;
printf("The sum is %d\n", sum);
n++;}
while(n<10);

avarage = (float) sum / 10.0;


printf("The avarage is %f\n", avarage);
return 0;
}

16
Exercise 3-extra: Write a program to input an integer and count the n of digits using loops:

Input: Number: 35419


Output: Number of digits: 5

Solution:

/*This program calculates the number of digits in an integer*/


#include <stdio.h>

int main(){

int a, temp, count = 0;

printf("Enter a positive integer:");


scanf("%d", &a);

temp = a;

while (temp > 10){


temp = temp/10;
count++;
}

printf("Number of digits: %d\n", count + 1);


return 0;
}

Exercise 4-extra: Write a program to count frequency (total occurrences) of each digit in a
given number using loops.

Example:

Input any number: 116540


Output:
Frequency of 0 = 1
Frequency of 1 = 2
Frequency of 2 = 0
Frequency of 3 = 0
Frequency of 4 = 1
Frequency of 5 = 1
Frequency of 6 = 1
Frequency of 7 = 0
Frequency of 8 = 0
Frequency of 9 = 0

17
Solution:

/* Write a program to count frequency (total occurrences) of each


digit in a given number */

#include <stdio.h>

int main(){

long int a, temp, reminder;


int count = 0; // this count can be used to count the total
// number of digits

int one = 0, two = 0, three = 0, four = 0, five = 0, six = 0,


seven = 0, eight = 0, nine = 0, zero = 0;

printf("Enter a positive integer:");


scanf("%ld", &a);

temp = a;

while (temp != 0){


reminder = temp % 10;

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++;
}

printf("Frequency of 0 = %d\n", zero);


printf("Frequency of 1 = %d\n", one);
printf("Frequency of 2 = %d\n", two);
printf("Frequency of 3 = %d\n", three);
printf("Frequency of 4 = %d\n", four);
printf("Frequency of 5 = %d\n", five);
printf("Frequency of 6 = %d\n", six);
printf("Frequency of 7 = %d\n", seven);
printf("Frequency of 8 = %d\n", eight);
printf("Frequency of 9 = %d\n", nine);

printf("Number of digits: %d", count);


return 0;
}

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;

printf("Input any number for square : ");


scanf("%lf", &num);

n = square(num);

printf("The square of %lf is : %.2lf\n", num, n);


return 0;
}

// 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:

The sum of the series is: 34

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;

printf("Function : find the sum of 1!/1+2!/2+3!/3+4!/4+5!/5:\n");

printf("The sum of the series is : %d\n",sum);


return 0;
}

// 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:

/* This program checks if check a number is an armstrong and/or


perfect numbers */

#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");

printf("Input a three-digits number:\n");


scanf("%d", &n1);

//Calls the checkArmstrong() function


// which returns true or false
if(checkArmstrong(n1))printf(" The %d is an Armstrong number.\n",
n1);
else printf(" The %d is not an Armstrong number.\n", n1);

//Calls the checkPerfect() function


// which returns true or false
if(checkPerfect(n1))printf(" The %d is a Perfect number.\n\n",
n1);
else printf(" The %d is not a Perfect number.\n\n", n1);
return 0;
}

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

sum += ld * ld * ld; //calculate the cube of the last digit


// and adds to sum
num = num/10;
}
return (n1 == sum);
}

// Checks whether the number is perfect number or not.


int checkPerfect(int n1)
{
int i, sum, num;
sum = 0;
num = n1;
for(i=1; i<num; i++)
{
/* If i is a divisor of n1 */
if(num%i == 0)
{
sum += i;
}
}
return (n1 == sum);
}

22
ENG1002: Introduction to C Programming

Lab 6: Strings(=arrays of characters) and Arrays

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>

#define MAX 100

// Function declaration
int mystringlength(const char str[]);

int main(){

char str[MAX]; // Declares a string of size 100

printf("\n\nFind the length of a string :\n");


printf("---------------------------------\n");
printf("Input the string : ");
gets(str);

int length = mystringlength(str);

printf("Length of the string is : %d\n\n", length);


return 0;}

int mystringlength(const char str[]){

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:

/* This program sorts an array of characters */


#include <stdio.h>
#include <string.h>

#define MAX 100

void mystringsort(char a[], int length);

int main(){

char str[MAX];
int l;

printf("\n\nSort a string array in ascending order :\n");


printf("--------------------------------------------\n");
printf("Input the string : ");

gets(str);
l=strlen(str);

mystringsort(str, l);

printf("After sorting the string appears like : \n");


printf("%s\n\n",str);
return 0;}

// My function for array sorting


void mystringsort(char a[], int size){

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


int k = i;
for(int j = i + 1; j < size; j++) if (a[j] < a[k]) k = j;
int tmp = a[i];
a[i] = a[k];
a[k] = tmp;
}
}

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:

/* This program sums an array of integers*/


#include <stdio.h>
#include <string.h>

#define MAX 100

// Function declaration
int mysumarray(int mya[], int length);

int main(){

int a[MAX];
int l;

printf("Input the number of elements to be stored in the


array:\n");
scanf("%d", &l);

printf("Input %d elements in the array:\n", l);

for (int I = 0; i < l; i++){


printf("Enter the element: %d\n", i+1);
scanf("%d", &a[i]);
}

int sum = mysumarray(a, l);

printf("Sum of all elements stored in the array is: %d \n", sum);


return 0;
}

// My function for array sum


int mysumarray(int mya[], int length){

int mysum = 0;

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


mysum = mysum + mya[i];}
return mysum;
}

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:

/* This program find the max element in an array */


#include <stdio.h>

#define MAX 100

// Function declaration
int myfindmax(int mya[], int length);

int main(){

int a[MAX];
int l;

printf("Input the number of elements to be stored in the array:\n");


scanf("%d", &l);

printf("Input %d elements in the array:\n", l);

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


printf("Enter the element: %d\n", i+1);
scanf("%d", &a[i]);
}

int max = myfindmax(a, l);

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


return 0;
}

// My function for array sum


int myfindmax(int mya[], int length){

int mymax = mya[0];

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


if(mymax < mya[i]) mymax = mya[i];}

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:

Enter a search string: microprocessor


EEE2007 Computer Systems and Microprocessors
EEE2206 Computer Systems and Microprocessors
EEE3010 Microprocessor Control
EEE8022 Microprocessor Systems
Number of matches: 4
Enter a search string: circuits
Number of matches: 0

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):

/* Write a program for searching a module catalogue */

#include <stdio.h>
#include <ctype.h>

#define MAX 100

int match(char source[MAX], char input[MAX]);

int main(){

// Open the file containing the module catalogue


FILE *f = fopen("modules.txt", "r");

27
if (f == NULL) { printf("Error: cannot open file\n"); return
1;}

char source[MAX], input[MAX];


int n = 0;

// Enter a input string to search for (e.g., microcontroller)


printf("Enter a search string: ");
scanf("%s", input);

// process each line and print the result


// for each result that is found n is ncrease by 1
while(fgets(source, MAX, f)){
if (match(source, input)) printf("%s", source), n++;
}

// In here, I have been using my own match function. Students


// can use the one from string library first.

//print the number of matches


printf("Number of matches: %d", n);
fclose(f);
return 0;
}
// My own match function body
int match(char source[MAX], char input[MAX]){

int x=0,y=0,z;

while (source[x] != '\0'){ //This loop will continue until


// main string is zero

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

Exercise 1: Print the address of array elements.

#include <stdio.h>

int main(void)
{
int val[7] = {11, 22, 33, 44, 55, 66, 77};

/* for loop to print value and address of each element of array*/


for ( int i = 0 ; i < 7 ; i++ )
{
/* The correct way of displaying the address would be using %p
format
* specifier like this:
* printf("val[%d]: value is %d and address is %p\n", i, val[i],
&val[i]);
* Just to demonstrate that the array elements are stored in
contiguous
* locations, I m displaying the addresses in integer
*/
printf("val[%d]: value is %d and address is %d\n", i, val[i],
&val[i]);
}
return 0;
}

Exercise 2: Write a program in C to swap elements using call by reference.

Pictorial Presentation:

Solution:

#include <stdio.h>

void swapNumbers(int *x,int *y,int *z);

int main(){

29
int e1,e2,e3;

printf("\n\n Pointer : Swap elements using call by reference


:\n");
printf(" Input the value of 1st element : ");
scanf("%d",&e1);

printf(" Input the value of 2nd element : ");


scanf("%d",&e2);

printf(" Input the value of 3rd element : ");


scanf("%d",&e3);

printf("\n The value before swapping are :\n");


printf(" element 1 = %d\n element 2 = %d\n element 3 =
%d\n",e1,e2,e3);

swapNumbers(&e1,&e2,&e3);

printf("\n The value after swapping are :\n");


printf(" element 1 = %d\n element 2 = %d\n element 3 =
%d\n\n",e1,e2,e3);
return 0;
}

void swapNumbers(int *x, int *y, int *z)


{
int tmp;
tmp=*y;
*y=*x;
*x=*z;
*z=tmp;
}

30

You might also like