Sucessive integers using C programming - c

Example input: 20 10 5 20 2 20 20 20 2 2 0
Output:
(20*5)
(10*1)
(5*1)
(2*3)
I just started programming this semester and need help on a project. I apologize if my question is unclear.
So basically I have to input positive integers till I enter "0" would end the program. I'm not allowed to use arrays(whatever that means).
#include <stdio.h>
int main ()
{
int number, count=0
while(1)
{
scanf("%d",&number);
if (number!=0)
{
count++; continue;
}
else
{
printf("%d*%d",number,count);
break;
}
return 0;
}
How do I store these multiple numbers so that I wouldn't overlap the previous number and to increment duplicate numbers by 1 every time it's entered? I can't ask my professor for help; he just tells me to google it.
"A certain engineering apparatus is controlled by the input of successive numbers (integers).
If there is a run of the same number, the apparatus can optimize its performance. Hence we
would like to arrange the data so as to indicate that a run is coming. Write a C program that
reads a sequence of numbers and prints out each run of numbers in the form (n∗m) where
m is the number repeated n times. Note that a run can consist of just a single number. The
input numbers are terminated by a zero, which halts the apparatus."

This assignment seems to be based on half-baked knowledge of run length encoding (RLE). Anyway, here's a pseudo-code which does what it asks.
in = read next number from input
current_num = in // let the 1st number in list be current_num
count = 1
loop
in = read next number from input
if (in == 0) break // we are done, get out of loop
else if (in == current_num) count += 1
else // run has ended, print it and start new run
print current_num * count
current = in
count = 1
end loop
print current_num * count // we exited the loop before printing the last run
// so do it outside the loop
You can implement it in code and then "optimize" it to remove repeated code, and take care of corner cases (such as "empty" input, single number input, etc.)
Edit Just to be clear, the assignment asks for a 'run' of numbers, but the sample output shows a 'count' of numbers. These two are not the same.

Related

How do you prevent blank lines when checking answers in an array in C?

I am making a Bingo game in C for a project and have made it through the initial board creation:
B = 1-20, I = 21-40, N = 41-60, G = 61-80, O = 81-99.
I have also been able to randomly generate a letter/number pair that doesn't repeat that is to be used to play the game per the following:
int main()
{
srand(time(0));
int rollcount = 0, rollc, rollr, nohund, basec=5, base=20;
const char BINGO[5] = {'B','I','N','G','O'};
bool check[101];
//fills check array with falses that will change to true as numbers are picked.
for(int i = 0; I < 100; i++)
check[i]=false;
//marks free space as true, free = 100 on board
check[100]=true;
do
{
//test var to prevent duplicate "rolls" until a game is won
bool reroll=true;
rollcount++;
//here's where the problem starts
//This is meant to loop if the number rolled has been rolled before.
do
{
//getchar();
if(getchar() == 'q')
{
//future code to display stats and escape game
return 0;
}
rollc = rand() %basec; //pick random column
//pick random number in range of selected column
rollr = rand() %base + 1;
rollr += (rollc * 20);
//limits last col to 99 instead of 100
nohund = (rollr == 100 ? rollr -= 1 : rollr);
if (check[rollr] == false) //checks if number has been used
{
//prints the number of the roll, column letter, and random number
printf("%d: %c-%d", rollcount, BINGO[rollc], rollr);
check[rollr]=true; //prevents future use of that number
reroll=false; //escapes loop to roll another number
}
}
//roll current roll again when duplicate is generated
while(reroll==true);
}
//intended to roll with each press of 'ENTER'
while(getchar()=='\n');
}
I have tried a few things. As written above, the major problem is if a duplicate is found, it shows the blank line from the getchar() input in the if() statement. As more numbers are found, wider and wider gaps between lines appear (due to needing more ENTER presses to find a unique number), leaving a mostly blank screen. With a single ENTER press, I need it to loop until it finds a good number. If I get rid of all getchar() expressions, the program will do this, and I can press ENTER until I get 99 unique numbers, but I need to allow to press q to quit the program.
Example Output
1: B-15
2: G-78
3: I-37
4: G-62
To summarize, I need it to display numbers like it does without getchar(), make it through all 99 possibilities, and let me quit with q.
Please help, and thank you in advance.
Let's first apply some fixes to other parts of the code, to make sure it all works as intended. This is the typical signature for a main function without parameters:
int main(void)
The middle I here needs to be lowercase, otherwise the code won't compile or it will use the imaginary number from the complex numbers:
// Note: index 0 is not used
for(int i = 1; i < 100; i++)
The most direct way of making the program work, would be to move the getchar() == 'q' check to before the do-loop. The function of the do-loop is now to loop until it finds a number which hasn't been chosen before. The problem is now that this will loop forever if all numbers are taken. Therefore, we'll add an additional check: only loop if there are still numbers available.
if(getchar() == 'q')
{
return 0;
}
bool aNumberIsAvailable;
do
{
// ... same code as before ...
aNumberIsAvailable = false;
for(int i = 0; i < 100; i++)
{
if (!check[i])
{
aNumberIsAvailable = true;
break;
}
}
}
while(reroll==true && aNumberIsAvailable);
That said, there are better ways to design this program. One simple step is to combine the two getchars into one, as if it is a menu: A '\n' result means "roll another number" and a 'q' result means "quit". As user3386109 suggested, there are better ways to solve the "sample without replacement"-problem.
Finally, note that getchar does not detect key presses. It simply reads a single character from the (terminal) input buffer. If you would like see actual key up/down movements, you will need a library which gives you more direct access to the keyboard such as SDL2.

Array sorting using special XOR condition

I have a problem in understanding the condition of my program, I can hardly explain it in a sentence so I will explain the whole point of program.
So for my homework I got to make a program that will ask user to enter number N which will represent the number of elements in array, then user enters elements of that array (assuming that user will enter correct number of elements) program then needs compare every number from that array with a number X with XOR (^) Operator.
The task is to find a minimum value for that X in which will the resulting array have elements in ascending order. It sounds a bit complicated but this is how it should work:
You enter a number N: For example lets use 4.
Then you enter 1D array of 4 elements : Lets use 4 2 3 1
Then program needs to use a number X (do while loop) to test every number from
this array with that number and if that number is >= to the previous one, it
should continue to check the next and next until it reaches the number N
If every element is sorted in ascending(equal counts as ascending) order it
should display that number.
So for our example 4 2 3 1 when you use XOR operation with every one of them
with the X=6 you get array that looks like this 2 4 5 7 which is in ascending
order.
To explain: 4 in binary is 100 ; X in binary is 110 if you use XOR on
those you get 010 which is 2, and do as follows for the rest ( program does
everything)
So I made the program,everything works great returning good values for every example that we have for reference, my only problem is that I don't know when to stop looking for that number X, or how should I know that minimum X for that array of numbers doesn't exist. In that case my program runs forever and don't return any value,so basically an infinity loop.
I need to use code that is simple so nothing too complicated because this is a course "Introduction to programming" and they won't accept anything that was made using complex algorithms or something like that.
EDIt: The program should display -1 if there are no X.
Here is the code :
#include <stdio.h>
int main() {
int matrix[100];
int n;
int i;
int index=1;
int x=0;
int start=0;
int end=0;
printf("Enter N: ");
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&matrix[i]);
}
index=1;
x=0;
do {
start=matrix[index]^x;
if((matrix[index+1]^x) >= start)
index=index+1;
else x++;
if(index==n){
printf("X=%d",x);
end=1;
break;
}
} while(end!=1);
return 0; }

Having trouble understanding the for loop

#include <stdio.h>
int n, a[100001], x, y;
int main() {
scanf("%d", &n);
while (n--) {
scanf("%d.%d", &x, &y);
a[x*1000+y]++;
}
for (int i = 0, c = 0; i <= 100000; i++) {
while (a[i]) {
--a[i], ++c;
printf("%d.%03d\n", i / 1000, i % 1000);
if (c == 7) return 0;
}
}
return 0;
}
This is the code that receives an integer n, then the program is expected to receive n number of double or integer variables.
The program is supposed to print out the smallest 7 variables among the input variables to 3 decimal points.
Now the question is i can't seem to figure out how this code in for loop
while (a[i]) {
--a[i], ++c; // <- specifically this part
printf("%d.%03d\n", i / 1000, i % 1000);
if (c == 7) return 0;
}
generates 7 smallest variables.
Any help would be much appreciated
Suppose 8.3 is an input, then you are storing the 8003rd index of the array to 1. i.e a[8003]=1. if 8.3 is input twice then a[8003] will be equal to 2.
So in the for loop when i=8003, a[8003] is non zero that that means there was an input 8.3. So it is considered in the top 7 smallest input values and the loop exits when count reaches 7.
As hellow mentioned, This is bad code and if you are a student, stay away from such programming style (Not just student, everyone should stay away).
What this code does is it creates sort of "Look-up" table.
Whenever a number is entered, it increases a count at that array instance.
e.g. If I input 3.2, it increments a[3002] th location. Code for this is:
scanf("%d.%d", &x, &y);
a[x*1000+y]++;
x = 3 and y = 2 so a[3*1000+2]++ --> a[3002] = 1
(Note: Code assumes that array a is initialized with 0 - another bad habit)
Now say I entered 1.9, code will increment a[1009]. If I enter 3.2 again, a[3002] will be incremented again.
This was input part.
Now code parses entire array a starting from 0. At first it will encounter 1009, code will print 1.9 and keep on parsing array.
When it finds 7 non=zero locations, loop exits.
When you enter same number again, like 3.2, while(a[i]) executes twice printing same number again.
As smaller number will be at lower location in array and array parsing starts from 0, it prints smallest 7 numbers. If you reverse the for loop, you can print 7 biggest numbers.
The answer here is how the input data is being stored.
User entered values populate array a. It does not store actual entered numbers, but a COUNT how many times the value was entered (code makes lots of assumptions about data sanity, but lets ignore that)
The data is naturally Sorted from smallest to largest, so to find 7 smallest inputs you just take first 7 values (iterations tracked by index i, c tracks how many values we already did print out) where the COUNT is not zero (a[i], non zero value indicates how many times user entered corresponding value)

Getting 'taking too long to run' error while getting space separated integers

This problem is bothering me for a while. Please forgive me for posting a big question. I have tried implementing simple logic to get space separated integers. This is the problem statement that was given to me.
PROBLEM STATEMENT:
The runs scored by two cricket players is passed as input. The program must print the total runs scored by the better player. The better player is the player with a higher average. It is not necessary that both the players have played/scored in the same number of matches. If both the players have the same average, then print the runs scored by the player who has the highest total runs.
Boundary Conditions:
The number of matches played for any player will not exceed 20.
If a negative value is passed as runs scored, then the program output must be INVALIDINPUT.
Input Format:
The first line will contain the runs scored by player one. The scores are separated by one or more spaces. The second line will contain the runs scored by player two. The scores are separated by one or more spaces.
Output Format:
The first line will contain the total runs scored by the player having the higher average.
Sample Input/Output:
Example 1:
Input:
20 30 40
50 10
Output:
90
Explanation: Both the players have same average 30. Hence the output is the highest total runs which is by player 1. (20+30+40 = 90)
Example 2:
Input:
42 -10
22 45
Output:
INVALIDINPUT
Explanation: As -10 is passed as runs scored in the input, the program must print INVALIDINPUT
Now I have asked a question regarding this before(link:How to get space separated integers as input?). Now this was my code as a result:
#include<stdio.h>
#include <stdlib.h>
int main()
{
int a[100],b[100],sum1=0,sum2=0,av1,av2,f=1;
char ch,ch1;
int i=0,j=0,n,m;
//Two do-while loops to get the input
do{
scanf("%d%c",&a[i++],&ch);
}while(ch!='\n');n = i;
do{
scanf("%d%c",&b[j++],&ch1);
}while(ch1!='\n');m = j;
//sum1 and sum2 are the total scores of the 2 players
for(i=0;i<n;i++) sum1 += a[i];
for(j=0;j<m;j++) sum2 += b[j];
//av1 av2 are average of the two players
av1 = sum1/n; av2 = sum2/m;
//This part of the code for calculation and printing the output
//To check wether the given element is negative
for(i=0;i<n;i++) {if(a[i]<0) {f = 0;break;}}
for(j=0;j<m;j++) {if(b[j]<0) {f = 0;break;}}
if(f==1){
if(av1>av2) printf("%d",sum1);
else if(av2>av1) printf("%d",sum2);
else {
if(sum2>sum1) printf("%d",sum2);
else printf("%d",sum1);
}
}
else printf("INVALIDINPUT");
return 0;
}
Now the problem is I am getting output when I execute the above code in an online compiler but the same code fails in the compiler where I submit the assignment. I get the following message:
Your program has exceeded the time limit allocated. Please check for infinite loops or other similar scenario in your code:
I want to know how can I correct this. The two do while loops are fine for getting the input as specified in the problem statement. Is there any alternative approach — a way that I can get the two lines of integers as two strings and convert them to integer by parsing through them character by character?

Using codeblocks writing a c program that repeatedly prompts for input

Key points, I'm using Codeblocks to write this program, and it needs to be written with the intent of writing C only and nothing more. I want it to be as basic as possible. So this is the mess that I have so far.
I need this program to continue to ask the user for a value until between 1-29 until it reaches 176. Once it exceeds 176 all I need to do is print the sum of the numbers, the largest number entered and the smallest number entered.
From there the program needs to loop and ask if another set of numbers will be entered. Terminating the program with the appropriate user input. I need to output the following info:
Sum of all numbers
Largest number entered
smallest number entered
If anyone has any advice that would help a lot.
/* Matthew Gambrell CSC 120 12/4/14*/
#include <stdio.h>
main ()
{
int total, num, large, small, again;
again=1;
while (again==1);
{
total = 0;
large = 0;
small = 50;
}
while(total<=176);
{
num=inputNum();
total=tot(num, total);
large=CheckLarge(num, total);
small=CheckSmall(num, small);}
printresult(total, large, small);
printf("play again");
printf("1=yes 0=no");
scanf("%d", &again);
}
float inputNum();
{
float badnum, num;
badnum=1;
while (badnum==1);
printf("please enter a number between 1 and 29");
scanf("%f", &num);
if(num>0 and num<30)
badnum = 0;
else
printf("error renter");
getch("press enter to continue");
return(num)
}
tot(num, total)
total += num
return (total)
}
return(num)
Like your classmate said, you can do this using a loop within a loop. The structure of your code makes it seem like this was your goal.
Firstly, as mentioned in the comments, remove your semicolons from the end of your while(..); statements. This will allow control to enter the blocks you're defining below them.
Secondly, you probably want to place the closing bracket for your first while loop after the end of your second while loop. This is your 'loop within a loop' structure.
Thirdly, you don't have any real way of displaying your results at present. Usually, your int main(){ ... } function returns a number relating to how your program went. Whilst you can have it return your total variable, it's more likely you want it to return 0;, and output your variables to screen during program execution.
For example, as you did in your input parsing in inputNum(..), you can write
printf('The total is %i\n', total);
printf('The largest number entered was %i\n', large);
printf('The smallest number entered was %i\n', small);
These numbers (large and small) will need to be within your (first) while loop - they should be reset each time your loop restarts, but not each time you enter a number.

Resources