find the smallest number of n integers - c

C Programming Beginner.
I don't understand why this code doesn't work. The numbers I get as answers for min and max are 2686672 and 4525824. Can anyone explain please? Thank you.
#include <stdio.h>
int main(void) {
int array[20], i, x, y;
int max, min;
printf("Please enter number of integers to be checked\n");
scanf("%d", &x);
for (y = 0; y <= x; y++) {
printf("Please enter your numbers\n");
scanf("%d", &i);
}
min = array[0];
max = array[0];
for (y = 0; y <= x; y++) {
if (array[i] < min) {
min = array[i];
} else if (array[i] > max) {
max = array[i];
}
}
printf("%d is the min and %d is the max", min, max);
}

Your section at
for (y=0;y<=x;y++){
printf ("Please enter your numbers\n");
scanf ("%d",&i);
}
Has several issues. First, you're storing the value in i each time; that will get overwritten the next time through the loop. Second, you want < instead of <= as you will otherwise ask for too many numbers. (You should also check that the user asked for <= 20 numbers).
I think you want:
for (y=0;y< x;y++){
printf ("Please enter your numbers\n");
scanf ("%d",&array[y]);
}

You aren't storing the values that you read into i in your array when you have the loop asking for the numbers to be entered.
Later, your are indexing array with i, but the loop counter is y - so i is never changing (nor is it necessarily a valid index, since it holds the last value that was read via scanf).
Check your code again to make sure you actually store the values you read into an array, and then check what you are using for array indices when computing the max and min.

you are never storing the numbers into the array. You overwrite the number the user enters on each pass. You therefore end up with garbage data at the end, whatever happened to be initialized into max and min.
for (y=0;y<=x;y++){
printf ("Please enter your numbers\n");
scanf ("%d",&i);
array[y] = i;
}
at least this way there will be something in the array locations to compare with in your Max/Min Logic later on.
cheers.

write a loop to dump out the array after its entered - just so you can be sure you get the right stuff
for(i = 0 ; i < x; i++)
{
printf("%d\n", array[i];
}
Also (as others have said) your loop boundaries need to be < not <=. A 10 element array has elements numbered 0 - 9

Related

C program displays garbage value while taking user input using scanf

I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");

Finding the average of 5 numbers and N numbers using only While and do while loop in C

i am really stuck with this been trying to solve it for quite a time now.
i have to write a program where i should input 5 numbers between 1 to 10 and then calculate the average, USING ONLY WHILE LOOP, but it does not have to exit when the number does not meet the requirement. then, i have to write a variation of the same code but this time you can enter all the numbers you want, and when 0 is entered it has to calculate the average and exit
this is where i have gotten so far
#include <stdio.h>
int main(void)
{
int n, i = 1;
float add;
float avg;
do
{
printf("enter the number %d:\n", i++);
scanf("%d", &n);
add = add + n;
} while(n > 0 && n < 11);
avg= (add / 5);
printf("%.1f", avg);
return 0;
}
it will keep asking for numbers after 5 have been entered. and the average is not right anyways
First, you're using nas your while condition variable, but also as the variable to scan the input. If I start your program by scanning 20, for example, your while loop will exit on the first interaction. Use your i variable instead and also increment it every time your loop executes.
do{
...
}while(i <= 5);
Second, if you want only numbers between 1 and 10, then you should write a condition for it. For example:
printf("enter the number %d:\n", i); //do not increment it here!
scanf("%d",&n); //assuming "n" as your variable to scan
if(n > 0 && n < 11){
add += n;
i++; //increment it here instead!
}
Third, initialize your variables in order to not get thrash values
float add = 0;
float avg = 0;
int i = 1;
Finally, assign your result (not mandatory, but since you're using it I'll keep it):
avg = add/5.0f
and display:
printf("%.1f", avg);

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

Scan and sum using array in C

I'm trying to write a simple program that'll prompt the user to enter N numbers, store them in an array, then just sum them all up
I understand I can just do this with a recursion but I'm trying to learn how array works
Example:
1 (hit enter)
2 (hit enter)
...
10 (hit enter)
Expected output: 55
#include <stdio.h>
int main (void){
int n;
int a[n];
int counter;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
printf("OK! now enter your number: \n");
for (int i = 0; i <= n; i++){
scanf("%d", &a[i]);
counter =+ a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
Right now there's no error message, no output, just the standard windows error message
"scanner.exe has stopped working..."
I'm using Win8 and GCC compiler
First of all, you can't create an static array without first knowing its size. You first need to ask the user for the "n" variable and then declare your array.
You also need to explicitly initialize your counter variable to be zero before you start counting. In C, variables don't default to 0 when you declare them.
The operator "=+" doesn't exist AKAIK, change it to "+=".
Last but not least, the limit in your loops is a little off, you're asking for 11 values ;)
(I edited this post, I was wrong about only asking for 9 values. I tend to confuse that sort of stuff)
#include <stdio.h>
int main (void){
int n;
int counter = 0;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
int a[n];
printf("OK! now enter your number: \n");
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
counter += a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
You are using variable length arrays. At run time the value of n must be known. Place the declaration
int a[n];
after taking input for n, i.e, after scanf("%d", &n); and initialize counter to zero before using it otherwise you will get garbage value (because of undefined behavior).
Also change the for loop condition from i <= n to i < n.
After this line:
int n;
What do you think the value of n is?
Now go to the next line:
int a[n];
How big is this array?
Can you access it properly?

Need function to find largest value in an array, return it to main( ) and print out

To me, my program looks like it should do what I want it to do: prompt a user to enter 10 values for an array, then find the largest of those values in the array using a function, then return the largest number to the main () function and print it out.
But, when I enter values, I never get numbers back that look anything like the ones I'm entering.
For example, let's say I enter just "10, 11" I get back "1606416648 = largest value".
Does anyone know what I'm doing wrong?
Here's the code:
#include <stdio.h>
#define LIMIT 10
int largest(int pointer[]);
int main(void)
{
int str[LIMIT];
int max;
int i = 0;
printf("Please enter 10 integer values:\n");
while (i < LIMIT)
{
scanf("%d", &str[i]);
i++;
}
// Thanks for your help, I've been able to make the program work with the above edit!
max = largest(str);
printf("%d = largest value\n", max);
return 0;
}
int largest(int pointer[])
{
int i;
int max = pointer[0];
for (i = 1; i < LIMIT; i++)
{
if (max < pointer[i])
max = pointer[i];
}
return max;
}
scanf("%d", &str[LIMIT]); reads in one number and puts it in the memory location one past the end of your array.
After changes:
You don't need scanf() in your while condition; it should go in the while body instead.
Your scanf() still isn't quite right. You need to tell it where in the array you want to store the input.
str[i]; doesn't do anything.
printf("Please enter 10 integer values:\n");
scanf("%d", &str[LIMIT]);
This doesn't do what you think. First, it only reads one number in. Second, you are reading it into the last position + 1 of the array.

Resources