How can I program for mode if there are multiple modes? - c

I am able to write a program to find the mode provided there is only one mode. However, I'm not sure how to alter my code so it can function properly when there is more than one mode.
Here is what I have! Any advice on how to fix my code would be appreciated.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main ()
{
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i<=100)
{
c[i]=0;
i=i+1;
}
scanf("%d", &x);
while ((x>=0) && (x<=100))
{
c[x]=c[x]+1;
if (c[x]>=mode)
{mode=x;}
scanf("%d", &x);
}
printf("the mode is %d\n", mode);
}

You'd want to:
a) Have something that keeps track of how often each value occurred. You're already using an array of "occurrence counts" for this.
b) Find the highest "occurrence count"
c) Find all values that share the highest "occurrence count"
For your code, this can mostly be done by replacing:
if (c[x]>=mode)
{mode=x;}
..with something more like:
if (c[x] > highest)
{highest = c[x];}
..and then doing something like this at the end:
printf("the mode/s are:");
for(i = 0; i <= 100; i++) {
if(c[i] == highest) {
printf(" %d", i);
}
}
printf("\n");

Related

What's the problem with my code? In the third last line in score[i], the program said that i is undeclared

I just started learning C language. So, I am running into a lot of problems. I thought declaring i under for loop is enough, and I can use the value of i for outside too. But I think, that was not the case. Can someone explain the situation, please.
# include <stdio.h>
int main(void)
{
int x;
printf("Enter how many numbers in arrays you want to input : ");
scanf("%i", &x);
int score[x];
for(int i= 0; i <= x; i++)
{
printf("Enter the score : ");
scanf("%i", &score[i]);
}
// in the below line the output said "i" is undeclared.
float average = score[i] / x;
printf("The average score is : %f", average);
}
The answer is fairly simple
because of where you decalred i it is only visable to the for loop.
To make i visable to the whole function all you need to do is:
int i = 0;
for (; i <=x; i++){
printf("Enter the score : ");
scanf("%i", &score[i]);
}
this makes i avaliable throughout the function
i is declared in the initialization section of a for statement. That means the scope and lifetime of that variable is the expressions in the for statement itself as well as the block statement it contains. Once the loop is done, the variable no longer exists.
You need to declare i outside of the loop if you want to use it outside of the loop.
int i;
for(i= 0; i <= x; i++)
That being said, you don't actually need to use i outside of the loop.
There are security issues associated with using scanf so don't use it for anything serious. That said, I tried to re-write your program properly, and it still has pretty rubbish input validation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUTTEXTLEN 20
#define MAXINPUTINT 1000
int inputint() {
char inputtext[INPUTTEXTLEN + 1] = {0};
long inputval;
while (1) {
fgets(inputtext, INPUTTEXTLEN, stdin);
if (strlen(inputtext) > 0) {
inputval = atoi(inputtext);
if ((inputval < MAXINPUTINT) && (inputval >= 0)) break;
}
}
return (int)inputval;
}
int main(void)
{
int x = 0;
printf("Enter how many numbers in arrays you want to input : ");
//scanf("%i", &x);
while (x <= 0) {
x = inputint();
}
int score[x];
float average = 0;
for(int i= 0; i < x; i++)
{
printf("Enter the score : ");
//scanf("%i", &score[i]);
score[i] = inputint();
average += score[i];
}
average /= x;
printf("The average score is : %f\n", average);
}

Learning C basics and need some help:

Basically, I'm trying to create a program where you can read up to 100 inputs from the keyboard.
The inputs must be numbers between [1,100] and when "0" is entered, the program exits the loop and displays an array of all the numbers entered except the number zero.
I'm trying to work with "while,for,if" statements but it's a bit difficult to understand the logic.
Could you guys help me and give me some tips and feedback? Sorry for my ignorance but I'm programming for the first time.
#include <stdio.h>
int main(){
int long ship;
int array[100];
for(ship = 0; ship < 100; ship++){
printf("Repaired ship: ");
scanf("%li", &ship[array]);
while(ship[array] == 0){
printf("\n\t");
for(ship = 0; ship < 100; ship++)
printf("%li ", ship[array]);
printf("\n\nRepaired ships: %li", ship);
}
}
if(ship == 100){
printf("\n\t");
for(ship = 0; ship < 100; ship)
printf("%li ", ship[array]);
printf("\n\nRepaired ships: %li", ship);
}
return 0;
}
I have edited your code with some minor corrections.
In the comments below the code, I help clarify the changes.
Code:
#include <stdio.h>
int main(){
int ship;
int long array[100];
for(ship = 0; ship < 100; ship++)
{
printf("Repaired ship: ");
scanf("%ld", &array[ship]);
if(array[ship]==0)
break;
}
ship=0;
while(array[ship] != 0)
{
printf("\n\t");
printf("%ld ", array[ship]);
ship++;
}
printf("\n\nRepaired ships: %d", ship);
return 0;
}
The long int is not needed for ship as 100 is not that big of a value.
If required, the long int will be used for array.
The format specifier %ld is required for long int.
The for loop handles the input.
We don't need a for loop inside the while as it already deals with the output.
The use array[ship] type notation instead of ship[array] as the former is more common.
This if statement is not needed:
if(ship == 100){
printf("\n\t");
for(ship = 0; ship < 100; ship)
printf("%li ", ship[array]);
printf("\n\nRepaired ships: %li", ship);
}

Write a program that multiplies user entered number till product of these numbers reach 1000

I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}

making a staircase of x's using loops in C, but I keep getting squares

So I need to make a staircase but I clearly have something wrong with my logic. Any advice on how to approach this? I only end up getting squares.
#include <stdio.h>
int main()
{
int a,b,z,y,p;
char x;
scanf("%i ", &a);
printf("Number of stairs is: %i\n", a);
printf("up: \n");
for(b=0; b<a; b++) {
for(z=1; a>=z; z++) {
x='x';
p=1;
if ((p=z)) {
printf("%c", x);
}
else {
printf(" ");
}
p++;
}
printf("\n");
}
}
Your code has many flaws and lack of clarity is one of them. Nevertheless, the reason you have a square is because p=z is always true (setting the value of p to z returns the value of z and this, in your code is always 1 or higher - a true value for C standards).
Here is a code that works, loosely based on your example:
#include <stdio.h>
int main() {
int numberSteps,currentStep,currentColumn;
scanf("%i", &numberSteps);
printf("Number of stairs is: %i\n", numberSteps);
printf("up: \n");
for(currentStep=0; currentStep<numberSteps; currentStep++) {
for(currentColumn=0; currentStep>=currentColumn; currentColumn++) {
printf("x");
}
printf("\n");
}
}
Please notice that I changed the variable names so that they became meaningful and also got rid of the unnecessary variables and the unnecessary test if ((p=z)) that was cluttering your code.

Program will stop once five even numbers are placed in array

This is a program that gets numbers input. From the numbers given or inputted, store in an array those numbers only that are even. Input will stop/terminates once 5 even numbers are already stored in the array. So here's my code:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int x, counter, even[5], numEven=0;
for(counter=0; counter<5; counter++){ //loop for getting the numbers from the user
printf("Enter number: ");
scanf("%d", &num[counter]);
if(num[counter]%2==0){ //storing the even numbers
even[numEven] = num[counter];
numEven++;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(counter=0; counter<numEven; counter++){
printf("%d, ", even[counter]);
}
getch();
return 0;
}
I have confusion in the part where will I stop the inputting when there's already 5 even numbers stored. Is there something missing? Or am I doing the wrong way? I hope I can get help and suggestions with the code. Thank you very much.
#include <stdio.h>
#include <conio.h>
int main()
{
int x, even[5], numEven = 0;
while (numEven < 5)
{
scanf("%d", &x);
if (x % 2 == 0)
{
even[numEven++] = x;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(x=0; x<numEven; x++)
{
printf("%d, ", even[x]);
}
getch();
return 0;
}
You keep readin inputs till numEven reaches 5. If the read input is an even number store it in the array and increment numEven.
Use a while loop if the number of times the program will ask the user for input is not fixed and dependent on the user's input.
while (numEven < 5) {
printf("Enter number: ");
scanf("%d", &num[counter]);
if (num[counter] % 2 == 0) {
even[numEven] = num[counter];
numEven++;
}
}

Resources