My loop won't finish - c

I want the user to choose when to finish inputting so i initialized " int finish". But the loop bypasses that.
I have tried while, do while loops but it doesn't do it for me
char snails[8][11];
int count;
int finish;
do
{
for (count = 0; count < 8; count++)
{
printf("Enter the snail's name:");
scanf("%10s", &snails[count]);
int timea;
int timeb;
int timec;
int timed;
printf("Enter %s 's time for the first leg:", snails[count]);
scanf("%d", &timea);
printf("Enter %s 's time for the second leg:", snails[count]);
scanf("%d", &timeb);
printf("Enter %s 's time for the third leg:", snails[count]);
scanf("%d", &timec);
printf("Enter %s 's time for the fourth leg:", snails[count]);
scanf("%d", &timed);
int timef = timea + timeb + timec + timed;
int time1 = timef / 60;
int time2 = timef % 60;
printf("%s finished in %d minutes and %d seconds \n", snails[count], time1, time2);
printf("Type 1 if you have finished inputting or 0 if you have not:");
scanf("%d", &finish);
}
} while (finish == 0);
return 0;
}

If your intention is to execute the loop up to 8 times, unless they indicate they are finished:
1.Remove the do while loop.
2.Do one of the following:
change the condition of the for look to:
count < 8 && finish != 1
or break from the for loop :
if (finish == 1) break;
then it will execute the for loop until either:
it does it 8 times
or they enter 1 when asked if finished

Related

Finding average for 2 students

I am running a program to calculate average for 2 students. I am having trouble running this. For some reason it says it cannot be found. It's my first time using Visual Studio and I am not sure if my code is the problem or the program.
Please check if there's a mistake and let me know.
#include <stdio.h>
int main(void)
{
int firstGrade1;
int sGrade1;
int tGrade1;
int fGrade1;
int TotalGrade1 = (firstGrade1 + sGrade1 + tGrade1 + fGrade1);
int AveGrade1 = (TotalGrade1 / 4);
printf("Please enter Student 1 first grade:\n");
scanf("%d", &firstGrade1);
printf("Please enter Student 1 second grade:\n");
scanf("%d", &sGrade1);
printf("Please enter Student 1 third grade:\n");
scanf("%d", &tGrade1);
printf("Please enter Student 1 fourth grade:\n");
scanf("%d", &fGrade1);
int firstGrade2;
int sGrade2;
int tGrade2;
int fGrade2;
int TotalGrade2 = (firstGrade2 + sGrade2 + tGrade2 + fGrade2);
int AveGrade2 = (TotalGrade2 / 4);
printf("Please enter Student 2 first grade:\n");
scanf("%d", &firstGrade2);
printf("Please enter Student 2 second grade:\n");
scanf("%d", &sGrade2);
printf("Please enter Student 2 third grade:\n");
scanf("%d", &tGrade2);
printf("Please enter Student 2 fourth grade:\n");
scanf("%d", &fGrade2);
printf("1. Student 1 grades:");
printf("%d", firstGrade1, sGrade1, tGrade1, fGrade1);
printf(". Average is ");
printf("%d\n", AveGrade1);
printf("2. Student 2 grades:");
printf("%d", firstGrade2, sGrade2, tGrade2, fGrade2);
printf(". Average is ");
printf("%d", AveGrade2);
system("pause");
return (0);
}
This here
int TotalGrade1 = (firstGrade1 + sGrade1 + tGrade1 + fGrade1);
Doesn't tell it that TotalGrade1 will just always be the value of those 4 variables added up. It assigns to TotalGrade1 the sum of those variables' current values. Since those are uninitialized, that's undefined behavior. Move the calculation of TotalGrade1 and AveGrade1 to after you read in those values, and likewise for TotalGrade2 and AveGrade2, of course.
Also, consider this print:
printf("%d", firstGrade1, sGrade1, tGrade1, fGrade1);
You are printing four int, why is there only one format specifier? The format string should be "%d %d %d %d".
I suggest always paying attention to your compiler's warnings. Usually your compiler should warn you about incorrect printf format strings as well as using uninitialized variables.
On a side note, you have a lot of code duplication. What if you didn't have two students and four grades, but a hundred students with ten grades each? Imagine the amount of code, and the amount of work copy/pasting the code. Instead, try something like this:
int main(void)
{
int Grade[2][4];
int AveGrade[2];
int TotalGrade[2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
printf("Please enter Student %d j. grade:\n", i + 1, j+1);
scanf("%d", &Grade[i][j]);
}
TotalGrade[i] = 0;
for (int j = 0; j < 4; j++)
TotalGrade[i] += Grade[i][j];
AveGrade[i] = (TotalGrade[i] / 4);
}
for (int i = 0; i < 2; i++) {
printf("%d. Student %d grades:", i+1, i+1);
for (int j = 0; j < 4; j++)
printf("%d ", Grade[i][j]);
printf(". Average is ");
printf("%d\n", AveGrade[i]);
}
system("pause");
return (0);
}

C While loop does not exit correctly

I have to take a university course on C and I shall read in some integers with a while loop. The code is:
#include <stdio.h>
#define max 100
int main(){
int a[max];
int i,n;
printf("Enter the number of persons: ");
do{
scanf("%i", &n);
}while((n < 1) || (n > max));
i = 0;
while (i < n){
printf("Enter the age of the %i th Person", i+1);
scanf("%i", &a[i]);
i = i + 1;
}
/* further code */
It compiles (with the gcc compiler), but as soon as I get into the loop, it reads in the numbers correctly, but after the last input, nothing is executed anymore.
Initialise i
int i = 0;
int n;
[edit: I see now that you have edited your code as I suggested]
Initialize i = 0
Here is the working code.
#define max 5
int main()
{
int a[max];
int i = 0,n;
printf("Enter the number of persons:\n");
do{
scanf("%d", &n);
}while((n < 1) || (n > max));
while (i < n){
printf("Enter the age of the %i th Person:\n", i+1);
scanf("%i", &a[i]);
i = i + 1;
}
return 0;
}
i has a garbage value at first you should write i=0 at first
and than scanf("%d", &n); Because you are calling a while loop with a garbage value of i at the beginning and code executes if the belove statistics satisfied while((n < 1) || (n > max)) but i has no value so you do not increment it. Think about sum,count I'm sure you know what i mean. if you want to increment something you should define first. An integer i defined with no value cant increment. Use for loop at last loop, instead of while

Printing the average of combined student marks using C

I've made this program below to calculate the average mark of a student.
Everything works well until I use -1, it is supposed to stop the program as is display the average of all students that have been entered, say Goodbye! and then terminate.
I think my calculations might be wrong though because it is printing the wrong result for the average marks of the students.
Thanks in Advance.
#include <stdio.h>
int main(void)
{
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark);
int i, a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark;
float average_mark = 0.0;
do
{
for (i = 0; i < 2; i++)
{
printf("Enter assignment 1 mark (-1 to quit): ");
scanf("%d", &a_mark1);
if(a_mark1 == -1)
{
average_mark += final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark);
if ((average_mark > 1 ) && (average_mark < 100 ))
{
printf("The average student mark is %.2f%% \n", average_mark);
}
printf("Goodbye! \n");
return 0;
}
printf("Enter assignment 2 mark: ");
scanf("%d", &a_mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab_mark);
printf("Enter quiz mark: ");
scanf("%d", &quiz_mark);
printf("Enter exam mark: ");
scanf("%d", &exam_mark);
printf("Student %d final mark: %.2f \n", i + 1, final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark));
}
}
while(a_mark1 != -1);
return 0;
}
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark)
{
float final_mark = a_mark1 * 0.1 + a_mark2 * 0.15 + lab_mark * 0.15 + quiz_mark * 0.1 + exam_mark * 0.5;
return final_mark;
}
I think you need to rethink your logic a little bit. Why not use a while loop to control the flow. Then you can bail out of the program immediately if user inputs -1 right away. You should use an array to store the averages for each student, then you can loop through and find the class average as well.
-Your float final_mark function seems a little sketchy without any parenthesis.
-You should put your function prototype outside of main as well. See below changes.
#include <stdio.h>
#define MAX_STUDENTS 10 //define what the max number of students is
float final_mark(int mark1, int mark2, int lab, int quiz, int exam);
int main()
{
int i = 0, mark1 = 0, mark2 = 0,
lab = 0, quiz = 0, exam = 0;
int num_students;
float students_avg[MAX_STUDENTS] = {0}; //array to hold averages for students
float average = 0;
while (i < MAX_STUDENTS) {
printf("Enter assignment 1 mark (enter -1 to quit):\n");
scanf("%d", &mark1);
if (mark1 == -1)
break; //no more students, break out of while loop
printf("Enter assignment 2 mark: ");
scanf("%d", &mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab);
printf("Enter quiz mark: ");
scanf("%d", &quiz);
printf("Enter exam mark: ");
scanf("%d", &exam);
average = final_mark(mark1, mark2, lab, quiz, exam);
students_avg[i] = average; //add this average to array
printf("Student # %d average was %.2f\n", i, students_avg[i]);//debug info
i++;
}
num_students = i; //how many students grades did we read?
average = 0; //reset to 0 so we can use below
for (i = 0; i < num_students; i++)
average += students_avg[i];
if (num_students > 0)
printf("Class average is %.2f\n", average/num_students);
else
printf("Goodbye!\n");
return 0;
}
float final_mark(int mark1, int mark2, int lab, int quiz, int exam)
{
//we can just return the calculation
return ((mark1 * 0.1) + (mark2 * 0.15) + (lab * 0.15) + (quiz * 0.1) + (exam * 0.5));
}
Just erase two lines above printf("GOODBYE! \n"); you will get what you want.
maybe you have to initialized mark s variables to 0. and a_mark1 to 0 too if the user enter -1

Why is this for loop getting ignored? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm not sure what i'm doing wrong but the for loop is not initializing
The code just goes immediately to displaying the printfs. That have no values in them since the for loop didn't activate
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("Pause")
main() {
// INITALIZE VARIABLES
int number = 0;
int i = 0;
int odd = 0;
int even = 0;
int totalNum = 0;
int tempNum = 0;
int count;
printf("Enter a number between 2 and 25\n");
scanf("%i", &number);
do{
if (number < 2 || number > 25)
printf("That was an invalid number please try again\n");
scanf("%i", &number);
} while (number < 2 || number > 25);
printf("Enter how many numbers you want to input\n");
scanf("%i", &count);
for (i = 1; i == count; ++i){
printf("input numbers\n");
scanf("%i", &tempNum);
if (tempNum % 2 == 0)
even++;
else
odd++;
totalNum = totalNum + tempNum;
} // END FOR LOOP
// DISPLAY OUTPUT
printf("You entered %i numbers\n", count);
printf("The sum of the %i numbers is %i\n", count, totalNum);
printf("The average of the %i numbers is %i\n", count, totalNum / count);
printf("You entered %i odd numbers and %i even numbers\n", odd, even);
PAUSE;
} // END MAIN
Your loop will only execute at best once, when count == 1 as you initialize i to 1.
If you enter a 1 for count,
printf("Enter how many numbers you want to input\n");
scanf("%i", &count);
the loop will run exactly once, until i increments to 2
You probably want:
for (i = 1; i <= count; ++i){
do{
if (number < 2 || number > 25)
printf("That was an invalid number please try again\n");
scanf("%i", &number);
} while (number < 2 || number > 25);
it should be...
do{
if (number < 2 || number > 25){
printf("That was an invalid number please try again\n");
scanf("%i", &number);
}
} while (number < 2 || number > 25);
else it asks always another number
i = 1, so i == count; gives false therefore the loop is ignored.
A for loop in C works like this:
for ( variable initialization; condition; variable update ) {
/* Do something... */
}
The loop will execute for as long as condition is true. So, when you do:
for (i = 1; i == count; ++i)
The loop will execute for as long as i == count is true. So, unless count holds 1 when this line is executed, the loop will never run.
As others pointed out, you probably want this:
for (i = 1; i <= count; ++i)
So your loop will run for all values of i, until it reaches count.
As a side note i should point out that the usual way to write for loops in C is something like this:
for (i = 0; i < count; i++)
We start with i = 0 because C arrays are zero-based, so the Nth element of an array has index n-1
You were so close. In addition to fixing your loop test clause for (i = 1; i <= count; i++), I would suggest using " %d" for your format specifier. Your do loop need only be a while loop to avoid printing your invalid number message every time.
Additionally, While not an error, the standard coding style for C avoids caMelCase variables in favor of all lower-case. See e.g. NASA - C Style Guide, 1994.
With those changes, (and changing your odd/even check to a simple &) you could write your code as follows.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
// #define PAUSE system("Pause")
int main (void)
{
int number, i, odd, even, totalnum, tempnum, count;
number = i = odd = even = totalnum = tempnum = count = 0;
printf ("enter a number between 2 and 25: ");
scanf (" %d", &number);
while (number < 2 || number > 25) {
printf ("invalid number, again (between 2 and 25): ");
scanf (" %d", &number);
}
printf ("numbers to input: ");
scanf (" %d", &count);
for (i = 1; i <= count; i++) {
printf ("input number %2d: ", i);
scanf (" %d", &tempnum);
if ((tempnum & 1) == 0)
even++;
else
odd++;
totalnum = totalnum + tempnum;
}
printf ("You entered %d numbers\n", count);
printf ("The sum of the %d numbers is %d\n",
count, totalnum);
printf ("The average of the %d numbers is %d\n",
count, totalnum / count);
printf ("You entered %d odd numbers and %d even numbers\n",
odd, even);
// PAUSE;
return 0;
}
note: main is type int (e.g. int main (int argc, char **argv) or simply int main (void) to indicate no arguments taken). Since it is type int it will return a value to the shell. While historic implementations may have allowed void main that is no longer the case for portable code.
Example Use/Output
$ /bin/forskipped
enter a number between 2 and 25: 4
numbers to input: 4
input number 1: 1
input number 2: 2
input number 3: 3
input number 4: 4
You entered 4 numbers
The sum of the 4 numbers is 10
The average of the 4 numbers is 2
You entered 2 odd numbers and 2 even numbers
Look it over and let me know if you have any questions.

Round Robin Scheduling Program

I have been working on a Round Robin Scheduling Program. My inputs are:
Process Arrival Time Burst Time
1 0 4
2 2 2
3 4 3
4 6 5
5 7 1
Time Slice is 3 units!
My output must be:
Process AT BT WT TT FT
1 0 4 9 13 13
2 2 2 1 3 5
3 4 3 1 4 8
4 6 5 4 9 15
5 7 1 4 5 12
But I am not getting the correct results(WT & FT) for Process 1, 4 & 5. Here's my code, can anyone please help me fix it and get the above results?
#include<stdio.h>
#include<conio.h>
struct proc
{
int id;
int arrival;
int burst;
int rem;
int wait;
int finish;
int ti;
int turnaround;
float ratio;
}process[10];
int no,k;
int chkprocess(int);
void main()
{
int i,j,t,time = 0,n;
struct proc temp;
int nextprocess(int);
clrscr();
printf("\n \n Enter the number of processes: ");
scanf("%d", &n);
printf("\n \n Enter the time slice of the CPU: ");
scanf("%d", &t);
for(i = 1; i <= n; i++)
{
process[i].id = i;
printf("\n\nEnter the arrival time for process %d: ", i);
scanf("%d", &(process[i].arrival));
printf("\nEnter the burst time for process %d: ", i);
scanf("%d", &(process[i].burst));
process[i].rem = process[i].burst;
process[i].ti=0;
process[i].wait=0;
process[i].finish=0;
}
for(i = 1; i <= n; i++)
{
for(j = i + 1; j <= n; j++)
{
if(process[i].arrival > process[j].arrival)
{
temp = process[i];
process[i] = process[j];
process[j] = temp;
}
}
}
no = 0;
j = 1;
while(chkprocess(n) == 1)
{
if(process[no + 1].arrival == time)
no++;
if((process[j].ti<=t)&&(process[j].rem !=0))
{
process[j].rem--;
process[j].ti++;
for(i = 1; i <= no; i++)
{
if((i!=j) && (process[i].rem != 0))
process[i].wait++;
}
}
if(process[j].rem==0)
process[j].finish=time;
if((process[j].ti >= t)||(process[j].rem==0))
{
process[j].ti = 0;
j=nextprocess(j);
}
time++;
}
process[n].finish = time;
printf("\n\n Process Arrival Burst Waiting Finishing turnaround Tr/Tb \n");
printf("%5s %9s %7s %10s %8s %9s\n\n", "id", "time", "time", "time", "time", "time");
for(i = 1; i <= n; i++)
{
process[i].turnaround = process[i].wait + process[i].burst;
process[i].ratio = (float)process[i].turnaround / (float)process[i].burst;
printf("%5d %8d %7d %8d %10d %9d %10.1f ", process[i].id, process[i].arrival,
process[i].burst,
process[i].wait, process[i].finish,
process[i].turnaround, process[i].ratio);
printf("\n\n");
}
getch();
}
int chkprocess(int s)
{
int i;
for(i = 1; i <= s; i++)
{
if(process[i].rem != 0)
return 1;
}
return 0;
}
int nextprocess(int k)
{
int i;
i=k+1;
while(chkprocess(i) && i!=k)
{
if(process[i].rem != 0)
return i;
else
i=(i+1)%no;
}
}
Thank You
I'm sure there are many bugs (starting with not caring if the user wants to enter 11 or more processes even though your array of processes is limited to 10).
However; I spent 10 minutes trying to decipher your code and still don't really know what it thinks it's doing - there's no comments at all and the variable names and function names don't help (e.g. no is not a boolean "yes/no" variable, checkprocess() doesn't check one process but checks all processes to see if all processes have finished, etc). Mostly, if I were being paid to fix this code I'd simple throw it out and rewrite it from scratch to save time. I thought about rewriting it from scratch and just posting the resulting code; but that's not going to help you with your homework.
My advice is, rewrite it from scratch instead of fixing it.
It should have a global currently_running_process variable, a global current_time variable, one function to increase the current time, and one function for the scheduler itself.
The function to increase the current time would:
for each process on the scheduler's linked list, increase the waiting time
do current_time++
find any processes that should be started (current_time == arrival_time) and append any started processes to the end of the scheduler's linked list
The scheduler function should:
remove the first process from the scheduler's linked list
determine how much time that process should use (the time slice length or the process' remaining time, whichever is lower)
subtract that amount of time from the process' remaining time
call the increase_time() function in a loop, until that amount of time has passed
if the process' remaining time is not zero; put the process back onto the end of the linked list
if the process` remaining time was zero, check if the scheduler's linked list is empty and exit the program if it is
Note: I'd start with current_time = -1; and call the function to increase the current time once before calling the scheduler function; so that any processes with arrival_time == 0 would be added to the scheduler's linked list before the scheduler starts working (and so that the scheduler function doesn't see an empty list as soon as it's started).
/* The following code doesn't take the arrival time of the processes in account.
HAPPY CODING */
#include<stdio.h>
void main()
{
int b[10],br[10],wo[10];
int n,i,bt,q,count;
float awt=0,att=0;
for (i=0;i<10;i++)
wo[i]=0;
printf("Input the nmbr of processes running....");
scanf("%d",&n);
printf("\n Input their burst tym in order..");
for(i=0;i<n;i++)
scanf("%d",&b[i]);
printf("\n Input the quantum time for the algorithm..");
scanf("%d",&q);
for(i=0;i<n;i++)
br[i]=b[i];
bt=0;
for(i=0;i<n;i++)
bt=bt+b[i];
count=0;
printf("\nThe Gantt Chart is as follows:\n");
printf("\n 0");
do
{
for(i=0;i<n;i++)
{
if(br[i]==0)
{}
else
{
if(br[i]>=q)
{
br[i]=br[i]-q;
if(br[i]==0)
wo[i]=count;
count=count+q;
printf("\t(P%d)",i);
printf("\t%d",count);
}
else
{
if(br[i]<q)
{
count=count+br[i];
br[i]=0;
wo[i]=count;
printf("\t(P%d)",i);
printf("\t%d",count);
}
}
}
}
}while(count<bt);
for(i=0;i<n;i++)
awt=awt+(wo[i]-b[i]);
awt=awt/n;
printf("\n The average waiting time is....%f",awt);
for(i=0;i<n;i++)
att=att+wo[i];
att=att/n;
printf("\n The average turnaround time is....%f",att);
}
You can use queue for doing the same, i am pasting a link which is written in ANSI CPP
You can check this link for more info. I was having same problem like you had but the code on the link helped me a lot it also contains many other Scheduling program but i extracted only round robin from it.
click here to see the code for round robin Scheduling
Round Robin Scheduling program in C
#include<stdio.h>
#include<conio.h>
main(){
int i, j, k, n, so, tq, sob, sum, swt, stat, tata, temp, count;
int bt[10], bth[10], wt[10], tat[10];
float awt=0.0, atat=0.0;
char new;
// i = loop controller
// j = loop controller
// k = loop controller
// n = number of process
// so = (burst time holder divided by time quantum) and added by one
// tq = time quantum
// awt =average waiting time
// new = hold the value of start command
// sob = gantt chart size from so
// swt = summation of waiting time l
// bt[] = burst time
// wt[] = waiting time
// atat = average turn around time
// gcps = gantt chart process sequence
// stat = summation of turn around time
// tata = accumulator of turn around time
// temp = time quantum holder
// count = counter
// bth[] = burst time holder
// tat[] = turn around time
printf("\n\n\n\n To start round robin scheduling press any key: ");
k = 0;
new = getche();
system("cls");
while(k < 7){
j = 0; sob = 0; count = 0; sum = 0; swt = 0; stat = 0; tata = 0;
printf("\n\n\n\t\t\t ROUND-ROBIN SCHEDULING");
printf("\n\t\t\t ======================");
printf("\n\n\n\n\n Enter number of processes: ");
scanf("%d", &n);
printf("\n");
for(i = 0; i < n; i++){
printf("\n Enter burst time for Process P%d: ", i+1);
scanf("%d", &bt[i]);
bth[i] = bt[i];
}
printf("\n\n Enter time quantum: ");
scanf("%d", &tq);
system("cls");
printf("\n\n\n\t\t\t ROUND-ROBIN SCHEDULING");
printf("\n\t\t\t ======================");
printf("\n\n\n\n\n Time quantum: %d", tq);
for(i = 0; i < n; i++){
if(bth[i] % tq == 0){
so = bth[i] / tq;
}
else{so = (bth[i] / tq) +1;}
sob = sob + so;
}
int gc[sob], gcps[sob];
while(1){
for(i = 0,count = 0; i < n; i++){
temp = tq;
if(bth[i] == 0){
count++;
continue;
}
if(bth[i] > tq){
gc[j] = tq;
gcps[j] = i+1; j++;
bth[i] = bth[i] - tq;
}
else if(bth[i] >= 0){
if(bth[i] == tq){gc[j] = tq; gcps[j] = i+1; j++;}
else{gc[j] = bth[i]; gcps[j] = i+1; j++;}
temp = bth[i];
bth[i] = 0;
}
tata = tata + temp;
tat[i ]= tata;
}
if(n==count){
break;
}
}
for(i = 0; i < n; i++){
wt[i] = tat[i] - bt[i];
swt = swt + wt[i];
stat = stat + tat[i];
}
awt = (float)swt/n;
atat = (float)stat/n;
printf("\n\n Process Burst time Waiting time Turn around time\n");
printf(" ------- ---------- ------------ ----------------\n");
for(i = 0; i < n; i++){
printf("\n\n P%d\t %d\t %d \t %d", i+1, bt[i], wt[i], tat[i]);
}
printf("\n\n\n\n Gantt Chart:\n");
printf(" ------------\n\n");
for(j = 0; j < sob; j++){
printf("\tP%d", gcps[j]);
}
printf("\n 0");
for(j = 0; j < sob; j++){
sum = sum + gc[j];
if(j == 0){printf(" %d", sum);}
else{printf("\t %d", sum);}
}
printf("\n\n\n\n Average waiting time: %.2f \n\n Average turn around time: %.2f",awt,atat);
printf("\n\n\n\n To start again press S and to exit press any key: ");
new = getche();
system("cls");
if(new == 'S'|| new == 's'){k++;}
else{printf("\n\n\n Program was terminated successfully\n\n Thank you\n\n\n"); break;}
}
}
This code will read data from file whose format should have one process info in a single line, arrival time, burst time, spaced, and file should terminate with -1. File name and time slice must be passed in command arguments. Like:
0 3
1 2
2 1
-1
The code is in C and variable names are self-descriptive.
#include<stdio.h>
int main(int argc, char *argv[])
{
int flag = 0;
int timeSlice = atoi(argv[2]);
printf("%d\n\n", timeSlice);
int arrivalTime[10], burstTime[10], responseTime[10], finishTime[10];
int remainingProcesses, processCount = 0;
FILE * file = fopen(argv[1], "r");
if (!(file == NULL))
{
while (fscanf(file, "%d", &arrivalTime[processCount]))
{
if (arrivalTime[processCount] == -1)
break;
fscanf(file, "%d", &burstTime[processCount]);
responseTime[processCount] = burstTime[processCount];
processCount++;
}
remainingProcesses = processCount;
fclose(file);
}
printf("Process\t| Arrival time\t| Finish Time\t| Burst\t| Turnaround\t|\n");
printf("-------------------------------------------------------------------------\n");
int i = 0; int time = 0;
while (remainingProcesses != 0)
{
if (responseTime[i] <= timeSlice && responseTime[i]>0)
{
time += responseTime[i];
responseTime[i] = 0;
flag = 1;
}
else if (responseTime[i] > 0)
{
responseTime[i] -= timeSlice;
time += timeSlice;
}
if (responseTime[i] == 0 && flag == 1)
{
finishTime[i] = time;
remainingProcesses--;
printf("P[%d]\t|\t%d\t|\t%d\t|\t%d\t|\t%d\t|\n", i + 1, arrivalTime[i], finishTime[i], burstTime[i], finishTime[i] - arrivalTime[i]);
flag = 0;
}
if (i == processCount - 1) // If its the last process go back to slicing process 1
{
i = 0;
}
else if (arrivalTime[i + 1] <= time) // If the next process has kicked in
{
i++;
}
else // If the process haven't kicked in yet
{
time++;
i = 0;
}
}
return 0;
}
specials thank to kanika
I just modified some code.
output:
#include<stdio.h>
void main()
{
int bt[10],btTmp[10],tat[10];
int n,i,btAll,quantum,count;
float awt=0,att=0;
for (i=0;i<10;i++)
tat[i]=0;
printf("Input the number of processes : ");
scanf("%d",&n);
printf("\n Input their burst time in order : ");
for(i=0;i<n;i++){
scanf("%d",&bt[i]);
btTmp[i]=bt[i];
}
printf("\n Input the quantum time : ");
scanf("%d",&quantum);
btAll=0;
for(i=0;i<n;i++)
btAll=btAll+bt[i];
count=0;
while(count<btAll)
{
for(i=0;i<n;i++)
{
if(btTmp[i]==0)
{}
else
{
if(btTmp[i]>=quantum)
{
btTmp[i]=btTmp[i]-quantum;
if(btTmp[i]==0)
tat[i]=count+quantum;
count=count+quantum;
}
else
{
count=count+btTmp[i];
btTmp[i]=0;
tat[i]=count;
}
}
}
}
printf("\nprocess \t bt time \t wt time \t TAT\n");
for(i=0;i<n;i++){
printf(" \tP%d \t\t %d \t\t %d \t \t %d\n",i, bt[i], tat[i]-bt[i], tat[i]);
awt=awt+(tat[i]-bt[i]);
att=att+tat[i];
}
printf("\n The average waiting time is %f : ",awt/n);
printf("\n The average turnaround time is....%f : ",att/n);
}

Resources