Round Robin Scheduling Program - c

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

Related

How does a program run in c?

I'm just learning programming with c.
I wrote a program in c that had a bug in the body of the while loop
I did not put {}.
The program is as follows, but the question that came to me later is how to run the program in c? Why does error 2 not print while it is before the start of the while loop? If the c language is a compiler, why is it that the error of the whole program is not specified first, and up to line 15 the program is executed without any problems?
int main()
{
int n ,k;
float d ;
printf("please write your arithmetic sequence sentences ");
scanf("%d",&n);
printf("\n");
printf("please write your common differences");
scanf("%d",&k);
printf("\n");
printf("please write your initial element ");
scanf("%f",&d);
printf("error 1");
printf("\n");
printf("error 2");
printf("number \t sum");
printf("erorr 3");
int i = 0;
int j = 0;
int sum = 0;
while (i < n)
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
return 0;
}
Firstly, the program enters an infinite loop:
while (i < n)
j = d + i*k;
Since the values of i and n do not change, the condition never becomes false.
Secondly, the printing sequence:
printf("error 2");
printf("number \t sum");
printf("erorr 3");
does not display a line break at the end. The output is buffered (stored internally) waiting for the line break to be printed, which, naturally, never happens. Add \n at the end of "erorr 3" to see the difference.
#include <stdio.h>
int main()
{
int n ,k;
int i = 0;
int j = 0;
int sum = 0;
float d ;
// If the given values are not an integer, it wouldn't continue the sequence and end as an "error"
printf("please write your arithmetic sequence sentences ");
if(scanf("%d",&n)){
printf("please write your common differences");
if(scanf("%d",&k)){
printf("please write your initial element ");
if(scanf("%f",&d)){
printf("Number \tSum\n");
} else {
printf("error");
}
} else{
printf("error");
}
} else{
printf("error");
}
// This is where the values get solved
// You also forgot to add {} in your while statement
while (i < n){
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
}
return 0;
}

I'm trying to get the counter to work, how many months have a higher income than the same month from last year

The line of code I'm having trouble with has to do with counting a number of months, I'm passing a value up from a function that I thought would work but I'm not getting a proper readout from it. I'm sure I'm missing something stupid or the mistake I made is very basic but I can't seem to get it right. I would greatly appreciate any help I can get. please excuse the many printf statements, I was trying to find where the error was.
#include <stdio.h>
#include <stdlib.h>
void DisplayInstructions();//function 1
void HigherSales(float yearOne, float yearTwo, int k);//fuction 2
int months (float yearOne, float yearTwo);//function 3
void main()
{
float yearOne[12];//variables
float yearTwo[12];
int i = 0;
int j = 0;
int k = 0;
int count = 0;
DisplayInstructions();//calling first function
printf(" \n");
for (i = 0; i<12; i++)//scanf for entering sales values
{
j= i+1;
printf("enter the sales figures for month %d in year one \n",j);
scanf_s("%f",&yearOne[i]);
}
for (i = 0; i<12; i++)
{
j= i+1;
printf("enter the sales figures for month %d in year two \n",j);
scanf_s("%f",&yearTwo[i]);
} //end of entering sales
k=0;
for (i = 0; i<12; i++)//populating function 2
{
k++;
HigherSales(yearOne[i], yearTwo[i], k);
}
printf("\n count before going into the for loop is %d \n",count);
for (i = 0; i<12; i++)
{
months(yearOne[i], yearTwo[i]);//populating function 3
printf("before going into count calculation months is reading %f",months(yearOne[12], yearTwo[12]));
count = count + months(yearOne[12], yearTwo[12]); //calling function 3 so that i get the sum of times y1 < y2
printf(" \n after calc count is %d \n after calc monts is returning %f", count, months(yearOne[12], yearTwo[12]));
}
printf(" \n the number of months in year two where sales have increased is %d \n", count);
system("pause");
}
void DisplayInstructions() //function 1 printf's
{
printf("\n");
printf("this program consists of one function called 'DisplayInstructions' \n");
printf("the function takes no arguments and simply dispays this message \n");
printf("it is innitalised above main, called inside main and described below main \n");
}
void HigherSales(float yOne, float yTwo, int g)
{
if(yOne < yTwo) //function 2 comparing logic
{
printf("month %d in year two had higher sales than the same month the year prior \n", g);
}
}
int months(float monthOne, float monthTwo)
{
int m = 0;
if(monthOne < monthTwo )
{
m = m + 1;
printf("\n in the mothhs function, m loop, m is %d \n", m);
return m;
}
}
The function int months(float monthOne, float monthTwo) does not work as you probably expect.
With int m = 0; the variable m always is initialized with 0 every time this function is called, therefore m = m + 1 won't count up how often the condition is true - its either 0 or 1
To make the function remember the value of m from its last call you need to declare it static int m = 0;
But in your case this wouldn't be the best idea either because you would only want to know the last return value (when all months are iterated).
Furthermore function months only has a return value if the condition is true - your compiler should have complained about that.
So if you want to make this simple comparison within a function which is called within a loop:
int months(float monthOne, float monthTwo)
{
if (monthOne < monthTwo)
return 1;
else
return 0;
}
for (i = 0; i<12; i++)
{
count += months(yearOne[i], yearTwo[i]);
}
In your context I cant figure out the purpose of count = count + months(yearOne[12], yearTwo[12]); - beside the fact that you are accessing the 13th element of your array which is invalid, it makes no sense to increment your counter by the same comparison every loop.
The modified code below addresses the errors I commented under your post as well as some others (see comments in code.) I automated inputs using rand() to speed up testing, but left all your original code. Comment out the auto populate sections for your purposes.
Note: Not all logic errors are addressed, but enough to get you started. Read the comments left in the code.:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
void DisplayInstructions();//function 1
void HigherSales(float yearOne, float yearTwo, int k);//fuction 2
int months (float yearOne, float yearTwo);//function 3
const char month[][4] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
void main()
{
float yearOne[12];//variables
float yearTwo[12];
int i = 0;
int j = 0;
int k = 0;
int count = 0;
srand(clock());//seed pseudo random number generator
DisplayInstructions();//calling first function
printf(" \n");
for (i = 0; i<12; i++)//scanf for entering sales values
{
j= i+1;
printf("enter the sales figures for month %d in year one \n",j);
yearOne[i] = rand();//Added to automate populating monthly sales numbers...
while(yearOne[i] < 500)
{
yearOne[i] = rand()%10000;//Added to automate populating monthly sales numbers...
Sleep(100);//pause execution for 0.1 seconds
}
printf("YearOne - %s: %lf\n", month[i], yearOne[i]);
//scanf("%f",&yearOne[i]);
}
for (i = 0; i<12; i++)
{
j= i+1;
printf("enter the sales figures for month %d in year two \n",j);
yearTwo[i] = rand();//Added to automate populating monthly sales numbers...
while(yearTwo[i] < 500)
{
yearOne[i] = rand()%10000;//Added to automate populating monthly sales numbers...
Sleep(100);//pause execution for 0.1 seconds
}
printf("YearTwo - %s: %lf\n", month[i], yearOne[i]);
//scanf("%f",&yearTwo[i]);
} //end of entering sales
k=0;
for (i = 0; i<12; i++)//populating function 2
{
k++;
HigherSales(yearOne[i], yearTwo[i], k);
}
printf("\n count before going into the for loop is %d \n",count);
for (i = 0; i<12; i++)
{ //Hint: In this for loop, you are calling months function more
//than you want to. Consider assigning a variable to read it's
//output, then use that variable in the printf statements.
months(yearOne[i], yearTwo[i]);//populating function 3
// printf("before going into count calculation months is reading %f",months(yearOne[i], yearTwo[i]));
printf("before going into count calculation months is reading %d",months(yearOne[i], yearTwo[i]));//changed format type to match variable type
count = count + months(yearOne[i], yearTwo[i]); //calling function 3 so that i get the sum of times y1 < y2
//printf(" \n after calc count is %d \n after calc monts is returning %f", count, months(yearOne[i], yearTwo[i]));
printf(" \n after calc count is %d \n after calc monts is returning %d", count, months(yearOne[i], yearTwo[i]));//changed format type to match variable type
}
printf(" \n the number of months in year two where sales have increased is %d \n", count);
// system("pause");
printf("hit any key to continue.");
getchar(); //this method is more idomatic and portable to pause code
}
void DisplayInstructions() //function 1 printf's
{
printf("\n");
printf("this program consists of one function called 'DisplayInstructions' \n");
printf("the function takes no arguments and simply dispays this message \n");
printf("it is innitalised above main, called inside main and described below main \n");
}
void HigherSales(float yOne, float yTwo, int g)
{
if(yOne < yTwo) //function 2 comparing logic
{
printf("month %d in year two had higher sales than the same month the year prior \n", g);
}
}
int months(float monthOne, float monthTwo)
{
static int m = 0;//use static here to allow m to keep value from call to call.
//static extends life of variable until program ends.
if(monthOne < monthTwo )
{
m = m + 1;
printf("\n in the mothhs function, m loop, m is %d \n", m);
}
return m;//moved from inside loop, otherwise return will not occur
//for some evaluations.
//Perhaps you would prefer an else statement
}

Using if else statements instead of while

Is there any way to write this program by only using if-else, else if statements instead of using while.
And I also want all the inputs just in one line, instead of
enter the number1:
enter the number2:
enter the number3:
enter the number4:
enter the number5:
it should be like
Enter 5 numbers: _ _ _ _ _
And when I write the same largest number twice, I want this program to show me the largest number as the second-largest number, too.
For example:
Enter 5 integers: -88 53 41 53 -17
The largest one is: 53
The second largest one is: 53
53 is the multiple of 53
53 and 53 is equal to each other.
53 is an odd number.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sayi = 0;
int sayac = 1;
printf("Sayiyi Girin:");
scanf("%d", &sayi);
//ilk sayinin en buyuk oldugunu kabul ediyoruz.
int enbuyuk = sayi;
int ikinci_buyuk = sayi;
while (sayac != 5)
{
sayac++;
printf("Sayiyi Girin:");
scanf("%d", &sayi);
/*kitapligi ilk sayinin en buyuk oldugunu farz ediyor
* eger ikinci sayi daha buyukse buyuk olanın yerini alacak
* ayrica ikincisinide kontrol edecek
*/
if (sayi > enbuyuk)
{
ikinci_buyuk = enbuyuk;
enbuyuk = sayi;
}
else if (sayi < enbuyuk)
{
// This to avoid if numbers are arranges descending
if (sayac == 2)
{
ikinci_buyuk = sayi;
}
else if (sayi > ikinci_buyuk)
{
ikinci_buyuk = sayi;
}
//This to avoid if the user entered two equal numbers
else if (enbuyuk == ikinci_buyuk)
{
ikinci_buyuk = enbuyuk;
}
}
}
printf("sayac: %d\n", sayac);
printf("En buyuk sayi: %d\n", enbuyuk);
printf("İkinci en buyuk sayi: %d\n", ikinci_buyuk);
if (enbuyuk % ikinci_buyuk != 0)
{
printf("%d %d nin tam kati degildir. is not the multiple of", enbuyuk, ikinci_buyuk);
}
else
{
printf(" %d %d nin tam katidir. is the multiple of", enbuyuk, ikinci_buyuk);
}
if (enbuyuk != ikinci_buyuk)
{
printf(" %d ve %d birbirine esit degildir. not equal each other", enbuyuk, ikinci_buyuk);
}
else
{
printf(" %d ve %d birbirine esitir. equal each other", enbuyuk, ikinci_buyuk);
}
if (enbuyuk % 2 != 0)
{
printf("%d tek sayidir. odd number", enbuyuk);
}
else
{
printf("%d cift sayidir.even number", enbuyuk);
}
system("pause");
return 0;
}
From the title of your question:
if-else are a conditional code flow structure without any repetition. Without any other instruction (like goto for example) you can't make it a loop like while.
But I think this is not the core of your question. You seem to want to read 5 numbers and check them. For now you do this in a loop and you like to replace that loop with something else.
You can print the one and only prompt and then call a function for each of the 5 numbers to check them.
Since your variables are not translated and your intend is not clear, I'll leave the code inside the function as an exercise for you.
printf("Enter 5 integers: ");
for (int i = 1; i <= 5; ++i)
{
readnumber(/* you might need arguments */);
}
The function will read and check one number. scanf() will read just one number and leave the remainder of the input line for some next call.
void readnumber(/* see above */)
{
if (scanf("%d", &number) == 1)
{
/* handle the number */
}
else
{
/* handle the scan error */
}
}
You can read 5 numbers simply by prompting with a single printf() and reading into 5 variables, or 5 array elements with a single scanf():
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a[5];
int first, second, i, j;
printf("Enter 5 numbers: ");
if (scanf("%d%d%d%d%d", &a[0], &a[1], &a[2], &a[3], &a[4]) != 5) {
printf("Invalid input\n");
return 1;
}
/* I cannot adapt the rest of the code because I cannot understand your language */
/* Here is my quick implementation from the desired output */
/* select the 2 largest numbers */
for (i = 0; i < 2; i++) {
for (j = i + 1; j < 5; j++) {
if (a[i] < a[j]) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
first = a[0];
second = a[1];
printf("The largest one is: %d\n", first);
printf("The second largest one is: %d\n", second);
if (second != 0 && first % second == 0)
printf("%d is a multiple of %d\n", first, second);
if (first == second)
printf("%d and %d are equal\n", first, second);
if (first % 2 != 0)
printf("%d is an odd number.\n", first);
return 0;
}

Can't Print " * " in C

for some reason I am unable to print out "* " in my program. I want to print out * if the condition is met. the condition is if the rainfall that day is greater than the average.
under the mean column, i am getting weird symbols. i tried debugging to decimals and get -112 for ascii. i dont understand but i tried researching!
I am new to C so please be understanding. Just learned like 2 days ago!!.
Here is my code :
//Assignment one 9/20/2018
//Anthony Lomaistro and David Luong
//luongd5#student.lasalle.edu
//lomaistroa1#student.lasalle.edu
#include <stdio.h>
main() {
int n = 0; //counters for the loops
int x = 0; // counter for the loops
int counter = 0; // counter whenever i need to keep track of increments
int days_input = 0; // how many days we are keeping track of
int number_of_days = 0;
double rainfall_input = 0;
double rainfall_amount = 0; // how much rainfall per day
double rainfall_average = 0; // average of rainfall
double rainfall_total = 0;
double rainfall_counter = 0; // count how many days it rained above the average
int correct = 0;
double rainfall_array[50];//array that contains the user input
char rainfall_condition[50]; // array that contains the *
double sum = 0;
double average = 0;
double percent_days = 0; //rainfall % above average
double valid = 0;
double valid2 = 0;
printf("Welcome to Lomaistro and Luong's Rainfall Program \n");
printf("How many days would you like to keep track of? Please enter a value between 1 and 50: #%d:", n + 1);
//printf(number_of_days);
while (valid == 0) {
scanf_s("%d", &number_of_days);
if ((number_of_days > 50) || (number_of_days <= 0)) { // come back to this, this doesnt do anytihng
printf("Invalid value, please enter in a day that is between 1 and 50 \n");
}
else {
valid = 1;
}
}
//getting the user to enter in the rainfall
for (x = 0; x < number_of_days; x = x + 1) {
valid2 = 0;
while (valid2 == 0) {
printf("Enter rainfall (in inches): ");
scanf_s("%lf", &rainfall_amount);
if ((rainfall_amount >= 0) && (rainfall_amount <= 10)) {
valid2 = 1;
rainfall_array[x] = rainfall_amount;
}
else
printf("Please enter in a valid rainfall amount between 1 and 10");
}
}
//computing average
for (n = 0; n < number_of_days; n = n + 1) {
sum += rainfall_array[n];
average = sum / number_of_days;
}
printf("Mean daily rainfall(in inches): %lf", average);
//seeing if the * should be the array or not
for (n = 0; n < number_of_days; n = n + 1) {
if (rainfall_array[n] > average) {
rainfall_condition[n] = "*";
rainfall_counter = rainfall_counter + 1;
}
else
rainfall_condition[n] = "empty";
}
// print out the thing
printf("\n Days \t Amount \t >Mean \n");
printf("==============================\n");
for (n = 0; n < number_of_days; n = n + 1) {
printf("%d \t %f \t %c \n", n + 1, rainfall_array[n], rainfall_condition[n]);
}
percent_days = rainfall_counter / number_of_days;
percent_days = percent_days * 100;
printf("Number of days that rained above average : %f \n", rainfall_counter);
printf("Percentage of days that rained above average: %f%% \n", percent_days);
system("pause");
}
rainfall_condition is an array of char, but you're putting a pointer to a string literal in there when you use "*". Use '*' for a character literal instead. To be more specific, this line:
rainfall_condition[n] = "*";
Should be:
rainfall_condition[n] = '*';
Turn some warnings on in your compiler; the first line (what you have now) isn't valid C code and you should be seeing a diagnostic message to that effect.
Edit: now that I've read more of the code, it appears you want either a * or an empty in that column? In that case you want to change the variable declaration to:
char *rainfall_condition[50]; // array that contains the *
And then change the print statement to:
printf("%d \t %f \t %s \n", n + 1, rainfall_array[n], rainfall_condition[n]);

My loop won't finish

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

Resources