Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

i/ (Use while loop and no vectors (arrays)). Write a program to performing the f

ID: 3633473 • Letter: I

Question


i/

(Use while loop and no vectors (arrays)).

Write a program to performing the following:
• Enter a positive integer n from the keyboard. Assume n is always an even number
• Enter n positive integers from the keyboard.
• Find the maximum of the first half of integers and the minimum of the last half of integers.
• Find the sum of all even numbers and the average of all odd numbers
• All output should be directed to the screen monitor.


ii/

(use files)
Rewrite the exercise above using files.
A. Your program should read data from a file that you should fill with 100 generated random numbers between 512 and 1024.
B. All output should be directed to a file.

Explanation / Answer

Note: Follow the instructions i gave you in previous answer to execute the scripts

i)

n = input('Enter a positive even number ', 's');
n = str2num(n);
evensum = 0;
oddsum = 0;
oddAvg = 0;
oddcount = 0;
maximum = 0;
minimum = -1;
counter = 1;
while counter <= n
inputnum = input('Enter a positive integer ', 's');
inputnum = str2num(inputnum);

%finding minimum and maximum
if counter <= (n/2)
     if maximum < inputnum
        maximum = inputnum;
     end;
else
     if minimum == -1
   minimum = inputnum;
     elseif minimum > inputnum
        minimum = inputnum;
     end;
end;
if rem(inputnum,2) == 0
     evensum = evensum + inputnum;
else
     oddsum = oddsum + inputnum;
     oddcount = oddcount + 1;
end;
counter = counter + 1;
end;
oddAvg = oddsum/oddcount;
printf('Minimum in second half of numbers is %s ',num2str(minimum));
printf('Maximum in first half of numbers is %s ',num2str(maximum));
printf('Sum of even numbers is %s ',num2str(evensum));
printf('Average of odd numbers is %s ',num2str(oddAvg));

ii)

close all; clear all; clc;

disp('Generating Random number and writing to some text file');
r = 512 + (1024-512) * rand(100,1);
fid = fopen('InputData.txt', 'w');
fprintf(fid,'%g ', r');
fclose(fid);

disp('Reading the text file and storing the data in to a variable');
fid = fopen('InputData.txt');
A = fscanf(fid, '%g %g', [1 inf]);
fclose(fid);

disp('Writing the data back to an output file');
fid = fopen('OutputData.txt', 'w');
fprintf(fid,'%g ', A);
fclose(fid);
disp('Completed');