How to select multiple elements in an array with C? - c

Is there a way to select multiple elements in array using one line of code in C? For instance, say I had the following code (assuming I already asked the user for twenty numbers, the first ten I asked to be positive and the last ten I asked to be negative):
if (myArray[0 through 9] > 0)
{
printf("Thank you for providing positive numbers!");
}
else
{
printf("Sorry, please try again!");
}
if (myArray[10 through 19] < 0)
{
printf("Thank you for providing negative numbers!");
}
else
{
printf("Sorry, please try again!");
}
What code could I substitute for "through"? I am fairly new to this language, and have never heard of a way of doing so. I know that with this particular code I could make two arrays, one for the positive numbers and one for the negative numbers, but I am curious to know for other programming projects.
Thank you for reading and answering!

There's nothing built-in that does it, you need to write a loop. Don't forget that array indexes start at 0.
int all_positive = 1;
int i;
for (i = 0; i < 10; i++) {
if (myArray[i] <= 0) {
all_positive = 0;
break;
}
}
if (all_positive) {
printf("Thank you for providing positive numbers!\n");
}

int a[20];
// entering values for the array
_Bool first_positive = 1;
for ( size_t i = 0; i < 10 && first_positive; i++ )
{
first_positive = 0 < a[i];
}
if ( first_positive ) puts( "Hura, first 10 elements are positive" );
_Bool last_negative = 1;
for ( size_t i = 10; i < 20 && last_negative; i++ )
{
last_negative = a[i] < 0;
}
if ( last_negative ) puts( "Hura, last 10 elements are negative" );
Instead of type name _Bool you can use type int if your compiler does not support _Bool

The program requests number of rows (1D array).
Then asks for 2 integers, whole numbers.
Then asks user to select 2 rows.
The sum of the 2 selected rows is then added.
#include <stdio.h>
int main ()
//1D_Array. Load Element and Add Sumline .
//KHO2016.no5. mingw (TDM-GCC-32) . c-ansi .
{
//declare
int a,b,c,d,e,sum1=0;
int array[50];
int i,j,elm1,elm2;
//valuate
printf ("Plot a number of elements [1 - 20]: ");
scanf ("%d",&a);
printf ("Plot a value : ");
scanf ("%d",&b);
printf ("Plot an increment value : ");
scanf ("%d",&c);
//calculate
{for (i<0;i<=a;i++)
{array[i] =(b+(++c)); // set value for variable [i], inside the array subscript. the vairable [i] must have an INT, and an increment to function !
sum1 = (sum1 + array[i]);
printf ("Row [%.2d] : %.2d + %.2d = %d\n",i,b,c,array[i]);}
printf ("\nSum total = %d\n",sum1);}
printf ("\nRow [%.2d] = %d\n",b,array[b]);
printf ("Row [%.2d] = %d\n",a,array[a]);
printf ("Select 2 Rows :\n");
scanf ("%d%d",&elm1,&elm2);
d=elm1;
e=elm2;
printf ("You selected Row [%.2d] = %d\n",d,array[d]);
printf ("You selected Row [%.2d] = %d\n",e,array[e]);
printf ("The sum of two selected Rows [%d]+[%d] : %d + %d = %d\n",d,e,array[d],array[e],array[d]+array[e]);
//terminate
return 0;
}

Related

Sorting array elements to find the largest and smallest number in C

I'm solving this problem where I need to give some inputs, find the largest and smallest among them. Here is the problem statement
Ivan Vasilyevich came to the market and decided to buy two watermelons: one for himself and another for the wife's mother. It is clear to choose for himself the heaviest watermelon, and for mother-in-law the lightest. But there is one problem: there are many watermelons and he does not know how to choose the lightest and the heaviest one. Help him!
Input
The first line contains the number of watermelons n (n ≤ 30000). The second line contains n numbers, each number is a mass of corresponding watermelon. All weights of watermelons are positive integers and do not exceed 30000.
Output
Print two numbers: the weight of watermelon that Ivan Vasilyevich will buy for his mother-in-law and the weight of watermelon that he will buy himself, or print the message "Ooops!" (without quotes), if someone left without watermelon
Here's my code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, w[30000], gw, lw;
scanf("%d", &n);
n = abs(n);
for (i = 0; i < n; i++)
{
scanf("%d", &w[i]);
}
if (n >= 2)
{
for (i = 0; i < n; i++)
{
if (w[0] < w[i])
w[0] = w[i];
gw = w[0];
}
for (i = 0; i < n; i++)
{
if (w[0] > w[i])
w[0] = w[i];
lw = w[0];
}
printf("%d %d", lw, gw);
return 0;
}
else
{
printf("Ooops!");
return 0;
}
}
I'm getting wrong answer(96/100). What am I getting wrong?
You do not need to allocate space for an array of 30k integers to find the min and max weights entered.
First, initialize min and max weights to the first integer entered and then update min and max accordingly as you read more weights. Use the variable cur (an integer) to store the last integer (i.e. weight) read.
That way, you do it all in one pass, rather than in multiple loops.
If you use scanf, it is good practice to check it's return value. For reference (from the C99 standard):
The scanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
In our case, when our scanf call is of the form scanf("%d", &a) where a is some int, we expect the call scanf("%d", &a) to return 1.
While it is good practice to check the return value, it is not absolutely necessary. If this is a program for one of your classes and you have never worked with the return value of scanf, you could remove all the checks for the return value below and the program should function the same. That said, it would show great initiative if you do check for the return value and reference the C standard in your justification for checking it (as the return value provides very useful information).
#include <stdio.h>
#include <stdlib.h>
#define MAX_WAT 30000 /* maximum number of watermelons */
int main(void) {
int n, i, min, max, cur;
/* prompt user for number of watermelons */
printf("Enter number of watermelons: ");
/* read integer, checking return value of scanf as expected */
if (scanf("%d", &n) != 1) {
printf("error in scanf\n");
exit(EXIT_FAILURE);
}
if (n > MAX_WAT) {
printf("Please enter less than %d watermelons.\n", MAX_WAT);
return 0;
}
/* if zero or one watermelons, at least one person leaves without */
if (n <= 1) {
printf("Ooops!\n");
return 0;
}
/* initialize min, max to first integer and update
min, max accordingly as new weights are read */
printf("Enter weights of %d watermelons: ", n);
scanf("%d", &cur);
min = max = cur;
for (i = 1; i < n; i++) {
if (scanf("%d", &cur) != 1) {
printf("error in scanf\n");
exit(EXIT_FAILURE);
}
if (cur < min)
min = cur;
if (cur > max)
max = cur;
}
printf("Ivan Vasilyevich: %d\nMother: %d\n", max, min);
return 0;
}
Example Session 1:
Enter number of watermelons: 5
Enter weights of 5 watermelons: 2 5 1 9 10
Ivan Vasilyevich: 10
Mother: 1
Example Session 2:
Enter number of watermelons: 1
Ooops!
Example Session 3:
Enter number of watermelons: 30001
Please enter less than 30000 watermelons.
do not modify your original array
initialize your gw and lw
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, w[30000], gw, lw;
scanf("%d", &n);
n = abs(n);
for (i = 0; i < n; i++)
{
scanf("%d", &w[i]);
}
if (n >= 2)
{
gw = w[0];
for (i = 0; i < n; i++)
{
if (gw < w[i]) gw = w[i];
}
lw = w[0];
for (i = 0; i < n; i++)
{
if (lw > w[i]) lw = w[i];
}
printf("%d %d", lw, gw);
return 0;
}
else
{
printf("Ooops!");
return 0;
}
}

Some problems in coding a "guessing random number in C" under some conditions such as using input(), output()

I tried going beyond just guessing random numbers. The conditions were these:
use input() numbers used from 1 to100 and if inserted numbers that are out of this range, to show a line to re-enter a number
use output() to show the output(but show the last line```You got it right on your Nth try!" on the main())
make the inserted number keep showing on the next line.
Basically, the program should be made to show like this :
insert a number : 70
bigger than 0 smaller than 70.
insert a number : 35
bigger than 35 smaller than 70.
insert a number : 55
bigger than 55 smaller than 70.
insert a number : 60
bigger than 55 smaller than 60.
insert a number : 57
You got it right on your 5th try!
I've been working on this already for 6 hours now...(since I'm a beginner)... and thankfully I've been able to manage to get the basic structure so that the program would at least be able to show whether the number is bigger than the inserted number of smaller than the inserted number.
The problem is, I am unable to get the numbers to be keep showing on the line. For example, I can't the inserted number 70 keep showing on smaller than 70.
Also, I am unable to find out how to get the number of how many tries have been made. I first tried to put it in the input() as count = 0 ... count++; but failed in the output. Then I tried to put in in the output(), but the output wouldn't return the count so I failed again.
I hope to get advice on this problem.
The following is the code that I wrote that has no errors, but problems in that it doesn't match the conditions of the final outcome.
(By the way, I'm currently using Visual Studio 2017 which is why there is a line of #pragma warning (disable : 4996), and myflush instead of fflush.)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input();
int random(int);
void myflush();
void output(int, int);
int main()
{
int num;
int i;
int ran;
srand((unsigned int)time(NULL));
i = 0;
while (i < 1) {
ran = 1 + random(101);
++i;
}
num = input();
output(ran, num);
printf("You got it right on your th try!");a
return 0;
}
int input()
{
int num;
printf("insert a number : ");
scanf("%d", &num);
while (num < 1 || num > 100 || getchar() != '\n') {
myflush();
printf("insert a number : ");
scanf("%d", &num);
}
return num;
}
int random(int n)
{
int res;
res = rand() % n;
return res;
}
void myflush()
{
while (getchar() != '\n') {
;
}
return;
}
void output(int ran, int num) {
while (1) {
if (num != ran){
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
break;
}
}
return;
}
There are many problem and possible simplifications in this code.
use fgets to read a line then scanf the line content. This avoids the need of myflush which doesn’t work properly.
the function random is not needed since picking a random number is a simple expression.
if the range of the random number is [1,100], you should use 1+rand()%100.
there is no real need for the function output since it’s the core of the main program. The input function is however good to keep to encapsulate input.
you should test the return value of scanf because the input may not always contain a number.
Here is a simplified code that provides the desired output.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input() {
char line[100];
int num, nVal;
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
while (nVal != 1 || num < 1 || num > 100) {
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
}
return num;
}
int main()
{
int cnt = 0, lowerLimit = 0, upperLimit = 101;
srand((unsigned int)time(NULL));
// pick a random number in the range [1,100]
int ran = 1 + rand()%100;
while(1) {
cnt++;
int num = input();
if (num == ran)
break;
if (num > lowerLimit && num < upperLimit) {
if (num < ran)
lowerLimit = num;
else
upperLimit = num;
}
printf("bigger than %d and smaller than %d\n", lowerLimit, upperLimit);
}
printf("You got it right on your %dth try!\n", cnt);
return 0;
}
I am unable to find out how to get the number of how many tries have been made.
Change the output function from void to int so it can return a value for count, and note comments for other changes:
int output(int ran, int num) {//changed from void to int
int count = 0;//create a variable to track tries
while (1) {
if (num != ran){
count++;//increment tries here and...
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
count++;//... here
break;
}
}
return count;//return value for accumulated tries
}
Then in main:
//declare count
int count = 0;
...
count = output(ran, num);
printf("You got it right on your %dth try!", count);
With these modifications, your code ran as you described above.
(However, th doesn't work so well though for the 1st, 2nd or 3rd tries)
If you want the program to always display the highest entered number that is lower than the random number ("bigger than") and the lowest entered number that is higher then the random number ("smaller than"), then your program must remember these two numbers so it can update and print them as necessary.
In the function main, you could declare the following two ints:
int bigger_than, smaller_than;
These variables must go into the function main, because these numbers must be remembered for the entire duration of the program. The function main is the only function which runs for the entire program, all other functions only run for a short time. An alternative would be to declare these two variables as global. However, that is considered bad programming style.
These variables will of course have to be updated when the user enters a new number.
These two ints would have to be passed to the function output every time it is called, increasing the number of parameters of this function from 2 to 4.
If you want a counter to count the number of numbers entered, you will also have to remember this value in the function main (or as a global variable) and pass it to the function output. This will increase the number of parameters for the function to 5.
If you don't want to pass so many parameters to output, you could merge the contents of the functions output and input into the function main.
However, either way, you will have to move most of the "smaller than" and "bigger than" logic from the function output into the function main, because that logic is required for changing the new "bigger_than" and "smaller_than" int variables which belong to the function main. The function output should only contain the actual printing logic.
Although it is technically possible to change these two variables that belong to the function main from inside the function output, I don't recommend it, because that would get messy. It would require you to pass several pointers to the function output, which would allow that function to change the variables that belong to the function main.
I have now written my own solution and I found that it is much easier to write by merging the function output into main. I also merged all the other functions into main, but that wasn't as important as merging the function output.
Here is my code:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int main()
{
const char *ordinals[4] = { "st", "nd", "rd", "th" };
int num_tries = 0;
int bigger_than = 0, smaller_than = 101;
int input_num;
int random_num;
srand( (unsigned int)time( NULL ) );
random_num = 1 + rand() % 101;
for (;;) //infinite loop, equivalent to while(1)
{
printf( "Bigger than: %d, Smaller than: %d\n", bigger_than, smaller_than );
printf( "enter a number: " );
scanf( "%d", &input_num );
printf( "You entered: %d\n", input_num );
num_tries++;
if ( input_num == random_num ) break;
if ( input_num < random_num )
{
if ( bigger_than < input_num )
{
bigger_than = input_num;
}
}
else
{
if ( smaller_than > input_num )
{
smaller_than = input_num;
}
}
}
printf( "You got it right on your %d%s try!", num_tries, ordinals[num_tries<3?num_tries:3] );
return 0;
}
Also, I made sure that the program would print "1st", "2nd" and "3rd", whereas all the other solutions simply print "1th", "2th", "3th". I used the c++ conditional operator for this.

For loop "<" vs "<=" print format issues in program

I am learning C on my own with a book and I cannot for the life of me figure out how to solve this exercise. I'm obviously looking at it in the wrong way or something. Here is an explanation below.
Listed below are some functions and the main function at the bottom. This program is compiled to generate a certain number of random numbers and determine the min and the max of the random numbers. If you copy and paste this code, you will see how it works. Anyways, an exercise asks me to go to the function "prn_random_numbers()" and change the for loop from "for (i = 1; i < k; ++i)" to for (i = 2; i <= k; ++i). This causes the first line format to print incorrectly. The exercise is to further modify the program in the body of the for loop to get the output to be formatted correctly.
To sum it up, the "prn_random_numbers()" function is written to print out 5 random numbers before moving to the next line. Hence the" i % 5" if statement. Now, for some reason, when you make the slight adjustment to the for loop, as the exercise asks above, it causes the first line to only print 4 numbers before moving to the next line. I have tried a number of things, including trying to force it to print the 5th number, but it only duplicated one of the random numbers. I even tried "i % 4" to see if it would print 4 numbers for each row, but it only prints 3 numbers for the first row instead of 4! So it always prints one less number on the first line than it is supposed to. I have n clue why it is doing that and the book does not give an exercise. Do you have any idea?
Bear with me if you think this is a stupid question. I am just learning on my own and I want to make sure I have a good foundation and understand everything as I learn it, before moving forward. I appreciate any help or advice!
prn_random_numbers(k) /* print k random numbers */
int k;
{
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 1; i < k; ++i)
{
if (i % 5 == 0)
printf("\n");
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main()
{
int n;
printf("Some random numbers are to be printed.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
while (n < 1)
{
printf("ERROR! Please enter a positive integer.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
}
prn_random_numbers(n);
return (EXIT_SUCCESS);
}
the following proposed code:
properly initializes the random number generator
cleanly compiles
properly checks for and handles errors
performs the desired functionality
avoids having to list instructions twice
follows the axiom: Only one statement per line and (at most) one variable declaration per statement.
does not use undefined functions like: max() and min()
and now the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void prn_random_numbers(int k)
{
int count = 1;
int r;
int smallest;
int biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for ( int i = 2; i <= k; i++, count++)
{
if (count % 5 == 0)
{
count = 0;
printf("\n");
}
r = rand();
smallest = (r < smallest)? r : smallest;
biggest = (r > biggest)? r : biggest;
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main( void )
{
int n;
srand( (unsigned)time( NULL ) );
do
{
printf("Please enter a positive integer, greater than 0.\n");
printf("How many would you like to see? ");
if( scanf("%d", &n) != 1 )
{
fprintf( stderr, "scanf for number of random numbers failed\n" );
exit( EXIT_FAILURE );
}
} while( n < 1 );
prn_random_numbers(n);
// in modern C, if the returned value from `main()` is 0 then no `return 0;` statement needed
}
a typical run, no input problems is:
Please enter a positive integer, greater than 0.
How many would you like to see? 20
98697066 2110217332 1247184349 421403769 1643589269
1440322693 985220171 1915371488 1920726601 1637143133
2070012356 541419813 1708523311 1237437366 1058236022
926434075 1422865093 2113527574 626328197 1618571881
20 random numbers printed.
Minimum: 98697066
Maximum: 2113527574
Try to use a debugger to solve your problem, it's easy to use and really helpfull :)
SOLUTION:
Your i variable don't count the number of numbers because it is initialize at 1 (in the for statement), so you need to declare a new variable to count properly.
If you have still a problem:
void prn_random_numbers(int k)
{
int count = 1;
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 2; i <= k; i++, count++) {
if (count % 5 == 0) {
count = 0;
printf("\n");
}
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}

Returning to the start of a for loop in C

Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8

Printf: pops out after the break statement

Being at the very beginning of learning programming,
C in particular, I am struggling with how to restrict
printf only to the valid outputs, i.e. to make sure
that printf does not appear after the "break" statement.
I understand that my test for scanf is within the for
loop, and when i reaches 3 the for loop stops and printf
appears. I hope to find the correct way to both test
scanf, and make sure printf doesn't appear after
the break statement (in case user types in integers).
// a program that calculates the average of an array
of 3 floating-point values and check if correct inputs
are types in scans (only floating values)
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
float values[3];
float element, average;
float sum = 0;
int i, n;
bool is_float;
printf ("Please, enter 3 floating values: \n");
for ( i = 0; i < 3; i++)
{
scanf ("%f", &element);
is_float = 1;
n = (int) element;
if (n - element == 0 || element == 0 )
{
is_float = 0;
printf ("Sorry, invalid input\n");
break;
}
else
{
values[i] = element;
sum += values[i];
}
}
printf ("The average of 3 values is %.2f\n", sum / 3);
return 0;
}
Thank you!
If you want the program to exit directly after this line:
printf ("Sorry, invalid input\n");
then you must replace the break statement directly below that printf line with something like this:
return 1;
On another note, when you want to print error messages, you should use fprintf() instead of printf(). The entire for loop would look like this:
for (i = 0; i < 3; i++)
{
scanf ("%f", &element);
is_float = 1;
n = (int) element;
if (n - element == 0 || element == 0 )
{
is_float = 0;
fprintf (stderr, "Sorry, invalid input\n");
return 1;
} else {
values[i] = element;
sum += values[i];
}
}

Resources