I want to find three largest number(area) from 10 numbers(scanf), I wrote this code, but only the largest number is correct when I run it, second and third largest number is wrong. So, I need help. any suggestions? Merry Christmas!
#include <stdio.h>
#define N 3
int main()
{
int i,j;
int area;
int maxArea[N];
int empty = N;
for(j=0;j<10;j=j+1)
{
printf("Input:");
scanf("%d",&area);
printf("\n");
if(empty > 0)
{
maxArea[N-empty]=area;
empty=empty-1;
}
else
{
for(i=0; i < N; i=i+1)
{
if(area>maxArea[i])
{
maxArea[i]=area;
break;
}
}
}
}
printf("Area1=%d\n",maxArea[0]);
printf("Area2=%d\n",maxArea[1]);
printf("Area3=%d\n",maxArea[2]);
}
#include <stdio.h>
#include <limits.h>
#include <string.h>
#define N 3
int main(){
int i,j;
int area;
int maxArea[N];
for(i=0;i<N;++i)
maxArea[i]=INT_MIN;
for(j=0;j<10;++j){
printf("Input:");
scanf("%d",&area);
printf("\n");
for(i = 0;i<N && i <= j;++i){
if(area > maxArea[i]){
memmove(&maxArea[i+1], &maxArea[i], (N-i-1)*sizeof(*maxArea));
maxArea[i] = area;
break;
}
}
}
printf("Area1=%d\n", maxArea[0]);
printf("Area2=%d\n", maxArea[1]);
printf("Area3=%d\n", maxArea[2]);
return 0;
}
Firstly you should initialize all the array elements to zero.
Also, your code does not work correctly since you only check for the first element in the array that is lesser than the new element.
If the array has 6, 3, 2 and the new element is 7, then 7 shall pop out 6 from the array and the array shall become 7, 3, 2. Instead it should have been 7, 6, 3.
You should pop out the lowest number in the array.
In the general case a minheap would be the best resort. (for k largest elements)
I just want to show you a different approach, you have to decide for yourself what is easier;
First I initialize maxArea with the smallest possible integer. This way I don't need special handling if it does not contain 3 numbers yet. Any number will simply be larger then MIN_INT, so it will be replaced automatically.
for(i=0; i < N; i++)
{
maxArea[i]=MIN_INT;
}
In the loop, I swap area with the old maximum value, and I keep running the loop, so the old value will be reused for the other max values.
for(j=0;j<10;j=j+1)
{
printf("Input:");
scanf("%d",&area);
printf("\n");
for(i=0; i < N; i++)
{
if(area>maxArea[i])
{
// swap both
int temp=maxArea[i];
maxArea[i]=area;
area=temp;
}
}
}
Note that this is not very optimized, but it might be better to read what is happening. maxArea[0] will always be the largers, maxArea[1] the next and so on.
for example if the array is [6, 3, 2], and the new area is 5;
nothing will happen in the first loop, because 5 is smaller than 6.
In the second loop (i=1), the array will become [6, 5, 2] and area will be 3.
In the third loop, the array will become [6, 5, 3], and area will be 2, (but that 2 will not be used any more).
Related
#include <stdio.h>
int highcard (int array[])
{
int i, j;
int largest = array[0];
for (i=0; i<5; i++)
{
if (largest < array[i])
{
largest = array[i];
}
}
printf("largest element is %d", largest);
return largest;
}
int main()
{
int hand1[5]={8, 10, 6 , 4, 2};
int hand2[5]={13, 5, 3, 9, 12};
int largest;
highcard(hand1[5]);
int largest1 = largest;
return largest1;
highcard(hand2[5]);
int largest2 = largest;
return largest2;
if (largest1 < largest2)
{
printf("winner: hand2");
}
else
{
printf("winner: hand1");
}
return 0;
}
I am trying to develop a program that tiebreaks two highcard hands in poker. For this I "translate" the card values to numbers (2=2 ... A=14), and for this specific case the maximum array size will always be 5 (5 cards). My problem is how do I compare the return values of the same function when applied to two different arrays?
What I mean is:
I have hand(array)1
I have hand2
I determine the largest number of hand1 and return it
I do the same thing for hand2
In main(), I want to compare the return (largest number) of highcard applied to hand1 and then hand2
But how do I specify in main() the specific return value of function highcard when applied to hand1 and then hand2 and keeping both returns separated?
This is what I have tried so far.
P.S.: This is for a university/college project, I have only started programming this semester, so any detailed explanation of my mistakes/errors and how to correct them would be very much appreciated :)
You have several misundertstandings.
highcard(hand1[5]);
Here, you want to call the function highcard and pass in the 5-element array hand1. To do that, do not specify the dimension in brackets. That works only when you declare the array. What happens instead is that you pass the sixth element of hand1 -- the first element has index 0 -- to the function. That element does not exist. You should also get a warning, because an integer is not an array; the argument types don't match.
return largest1;
Here, you probably want to store something in largest1, but what you actually do is to return from the function with the given value. That means you leave the current function. Leaving main means that you stop the program. You don't need a return here, just store the value.
int largest1 = largest;
Here, you try to access the variable largest from highcard, but thzat variable is local highcard and therefore is not visible to your main function. Rhe largest you look at is just an unrelated, uninitialized variable.
You can access the value that is returned from a function by assigning the result of a function call like so. Your main function should look like this:
int main(void)
{
int hand1[5] = {8, 10, 6 , 4, 2};
int hand2[5] = {13, 5, 3, 9, 12};
int largest1 = highcard(hand1);
int largest2 = highcard(hand2);
if (largest1 < largest2) {
printf("winner: hand2");
} else {
printf("winner: hand1");
}
return 0;
}
I am trying to find the duplicate values in an array. When a number is duplicated once like (25,25) program correctly prints 25 once but when a number duplicated twice like (12,12,12) program prints 12 three times while it should print it once.
#include<stdio.h>
int main()
{
int numbers[15]={1,1,2,2,2,3,4,5,6,6,7,7,7,8,9},i,j;
for(i=0;i<15;i++)
{
for(j=i;j<14;j++)
{
if(numbers[i]==numbers[j+1])
{
printf("Number %d has duplicate values\n",numbers[i]);
}
}
}
return 0;
}
Output:
Number 1 has duplicate values
Number 2 has duplicate values
Number 2 has duplicate values
Number 2 has duplicate values
Number 6 has duplicate values
Number 7 has duplicate values
Number 7 has duplicate values
Number 7 has duplicate values
The arrays cannot be assumed to be ordered so the program should work even with {1,2,1,2,3,4,2,5,6,6,7,7,7,8,9}.
The problem at hand is essentially simple. There is no need for any complicated code fragments. All it takes is just a little modification to the limits of the for loops and how you check for duplicates.
The solution:
Just introduce another array which is going to store the elements which are repeated in the array. Start filling this array from the 0th index as and when you find a NEWLY REPEATED element. This can easily be done iterating through this new array and checking if the currently encountered repeated element is already present or not. If it is not present there, then insert into the new array, which in the code I have given below is arr2[].
Hence whatever elements will be held by this new array are the unique repeated elements. I have attached the code and corresponding output below.
CODE:
#include<stdio.h>
int main()
{
int numbers[15] = {1,1,2,2,2,3,4,5,6,6,7,7,7,8,9}, i, j;
int arr2[15], k = 0, k1 = 0;
int flag = 0;
for(i = 0; i < 15; i++)
{
for(j = 0; j < 15; j++)
{
flag = 0;
if(i != j && numbers[i] == numbers[j])
{
for(k1 = 0; k1 < k; k1++)
if(arr2[k1] == numbers[j])
flag = 1;
if(flag != 1)
arr2[k++] = numbers[j];
}
}
}
for(i = 0; i < k; i++)
printf("Number %d has duplicate values\n",arr2[i]);
return 0;
}
OUTPUT:
Number 1 has duplicate values
Number 2 has duplicate values
Number 6 has duplicate values
Number 7 has duplicate values
Hope this helps.
A solution which doesn't introduce additional memory requirements and finds unique duplicates in a worst case of O(N²):
#include <stddef.h>
#include <stdbool.h>
#include <stdio.h>
// macro that evaluates to the number of elements in an array:
#define SIZEOF_ARRAY(arr) sizeof(arr) / sizeof(*arr)
// contains() returns true if [values, values + size) contains value
bool contains(int *values, size_t size, int value)
{
for (size_t i = 0; i < size; ++i)
if (values[i] == value)
return true;
return false;
}
int main(void)
{
int numbers[] = { 1, 1, 2, 2, 2, 3, 4, 5, 6, 6, 7, 7, 7, 8, 9 };
for (size_t i = 0; i < SIZEOF_ARRAY(numbers) - 1; ++i)
{
if (contains(numbers, i, numbers[i])) // if we already encountered numbers[i]
continue; // it was already identified as dup.
if(contains(numbers + i + 1, SIZEOF_ARRAY(numbers) - i , numbers[i]))
printf("Number %d has duplicate values\n", numbers[i]);
}
}
Output:
Number 1 has duplicate values
Number 2 has duplicate values
Number 6 has duplicate values
Number 7 has duplicate values
If you deal with low numbers, you can always go via index table
#include <stdio.h>
int main() {
int index[256] = {0};
int table[15] = {1, 2, 3, 5, 5, 6, 1, 2, 9, 10, 11, 2, 3, 4, 5 };
for(int i=0; i<15; i++) {
index[table[i]] ++;
}
for(int i=0; i<256; i++) {
index[i] > 1 ? printf("%d\n",i) : 0;
}
}
In your example consider the indexes of the 7: they are 10, 11, 12.
The first print happens when i=10 and j=10 because your are indexing numbers[10] and numbers[11].
At the next iteration of the inner loop you have i=10 and j=11 and the condition is verified again by the elements numbers[10] and numbers[12].
Finally the third condition happens when i=11 and j=11 because you are referring to numbers[11] and numbers[12].
All this becomes clear if you print your indexes when the condition happens. For example you can substitute your printf with this:
printf("Number %d has duplicate values with indexes i=%d, j=%d\n",numbers[i], i,j);
which prints:
Number 1 has duplicate values with indexes i=0, j=0
Number 2 has duplicate values with indexes i=2, j=2
Number 2 has duplicate values with indexes i=2, j=3
Number 2 has duplicate values with indexes i=3, j=3
Number 6 has duplicate values with indexes i=8, j=8
Number 7 has duplicate values with indexes i=10, j=10
Number 7 has duplicate values with indexes i=10, j=11
Number 7 has duplicate values with indexes i=11, j=11
If your values are ordered you can do something like this:
#include<stdio.h>
int main()
{
int numbers[15]={1,1,2,2,2,3,4,5,6,6,7,7,7,8,9},i,j;
int last_dup = -1;
for(i=0;i<15;i++)
{
for(j=i+1;j<14;j++)
{
if(numbers[i]==numbers[j] && numbers[i]!=last_dup)
{
printf("Number %d has duplicate values with indexes i=%d, j=%d\n",numbers[i], i,j);
last_dup = numbers[i];
break;
}
}
}
return 0;
}
I initialized to -1 assuming your numbers are all positive. If not you can save the index of the last duplicate and reference using in the check numbers[last_dup_idx] (be careful to initialize the value properly and not go out the length of the array). I also added a break: since you already found a duplicate there is no need to continue the second loop.
If your array is not ordered, you can create an additional array saving the duplicates elements every time you find one and then iterate through this array to check.
FOR NOT ORDERED ARRAYS
#include<stdio.h>
int main()
{
int numbers[15]={1,1,2,2,2,3,4,5,6,6,7,7,7,8,9},i,j;
int dups [7];//at most 15/2 duplicates
char dup_idx=0;
char found_new_duplicate; //initialized later
for(i=0;i<15;i++)
{
for(j=i+1;j<14;j++)
{
if(numbers[i]==numbers[j])
{
found_new_duplicate = 1;
//check in the duplicates array
for (int kk=0; kk<=dup_idx; kk++)
{
if (dups[kk]==numbers[i] && !(i==0 && j==1))
{
found_new_duplicate = 0;
break;
}
}
if (found_new_duplicate)
{
dups[dup_idx] = numbers[i]; //insert the new duplicate in the duplicates array
printf("Number %d has duplicate values with indexes i=%d, j=%d\n",numbers[i], i,j);
printf("New duplicate %d\n", dups[dup_idx]);
dup_idx++;//increase the index
break;
}
}
}
}
for (int kk=0; kk< dup_idx; kk++)
printf("%d\n", dups[kk]);
return 0;
}
I'm a bit stuck on one of my problems not because I don't know, but because I can't use more complex operations.(functions and multiple arrays)
So I need to make a program in C that ask for an input of an array(max 100 elements) and then program needs to sort that matrix by numbers with same digits.
So I made everything that I know, I tested my program with sorting algorithm from minimum to maximum values and it works, only thing that I can't understand is how should I test if the number have same digits inside the loop? (I can't use functions.)
So I know the method of finding if the number have the same digits but I don't know how to compare them. Here is an example of what I need.
This is what I have for now this sorts numbers from min to max.
#include <stdio.h>
int main() {
int matrix[100];
int i,j;
int temp,min;
int elements_number=0;
printf("Enter the values of matrix-max 100 elements-type -1 to end: ");
for(i=0;i<100;i++){
scanf("%d",&matrix[i]);
elements_number++;
if(matrix[i]==-1){
elements_number--;
break;
}
}
for (i=0; i<elements_number; i++) {
min=i;
for (j=i+1; j<elements_number; j++) {
if (matrix[j] < matrix[min])
min = j;
}
temp = matrix[i];
matrix[i] = matrix[min];
matrix[min] = temp;
}
for(i=0;i<elements_number;i++){
if(i!=elements_number-1){
printf("%d,",matrix[i]); }
else printf("%d.",matrix[i]);
}
return 0;
}
I need this output for these numbers:
INPUT :
1 22 43 444 51 16 7 8888 90 11 -1
OUTPUT:
1,22,444,7,8888,11,43,51,16,90.
Integers with 1 digit count as "numbers with same number of digits" like 7 and 1 in this example.
Hope that you can help.
After processing the array, the single-digit numbers should all be in the left part of the array, the other numbers in the right part. Within each part, the original order of the elements should be preserved. This is called a stable partition. It is different from sorting, because the elements are only classified into two groups. Sorting means that there is a clear relationship between any two elements in the array.
This can be done by "filtering" the array for single-digit numbers and storing the other numbers that were filtered out in a temporary second array. Then append the contents of that second array to the (now shorter) first array.
Here's how that could work:
#include <stdlib.h>
#include <stdio.h>
void print(const int *arr, int n)
{
for (int i = 0; i < 10; i++) {
if (i) printf(", ");
printf("%d", arr[i]);
}
puts(".");
}
int is_rep_digit(int n)
{
int q = n % 10;
n /= 10;
while (n) {
if (n % 10 != q) return 0;
n /= 10;
}
return 1;
}
int main()
{
int arr[10] = {1, 22, 43, 444, 51, 16, 7, 8888, 90, 11};
int aux[10]; // auxliary array for numbers with several digits
int i, j, k;
print(arr, 10);
j = 0; // number of single-digit numbers
k = 0; // number of other numbers
for (i = 0; i < 10; i++) {
if (is_rep_digit(arr[i])) {
arr[j++] = arr[i]; // pick single-digit number
} else {
aux[k++] = arr[i]; // copy other numbers to aux
}
}
k = 0;
while (j < 10) { // copy aux to end of array
arr[j++] = aux[k++];
}
print(arr, 10);
return 0;
}
Edit: I've just seen your requirement that you can't use functions. You could use Barmar's suggestion to test divisibility by 1, 11, 111 and so on. The tricky part is to find the correct divisor, however.
Anyway, the point I wanted to make here is that you don't need a full sorting algorithm here.
In C programming, suppose we have an array as: A[8] = {3, 5, 6, 8, 2, 9, 10, 1}, how to modify those items by index range? For instance, to "remove" elements from index 3 to 6, since we have static array, after handling, we expect: A[8] = {3, 5, 6, 1, 0, 0, 0, 0}.
concerning dealing with one element at specified index:
for(i= index; i< size - 1; i++)
{
A[i] = A[i+ 1];
}
size = size - 1
What's the best solution to this problem, suppose the array size can be very large.
With an array, copy is all you can do. You can copy element by element. Or you can use memmove which permits overlapping memory space (memcpy is not safe for overlapping copies). memmove is more efficient than a loop (though optimizing compilers may solve that). You can use either method to copy to a temporary space, or to copy/move in place. In all cases, you must makes sure your vacated cell is cleared.
// an example that assumes you have valid index and size
memmove(&A[index], &A[index+1], size-(index+1));
A[--size] = 0;
The Big(O) is still N (linear with respect to size). With very large arrays, the cost to delete goes up. If unacceptable, you would need a different data structure.
So, consider all your requirements which include cost of inserting, cost of finding/changing, and cost of deleting elements. Choose your data structure to match your requirements. When the data set is small or there are relatively few transactions, the performance differences may not matter to your requirements.
One way to remove elements from array will be to create another array.
And then copy elements from (start, left) and (right, end) in second array.
Here (left,right) are indices of subarray which you want to remove.
Another way will be to override elements instead of creating another array.
If you need to maintain order then care needs to be taken while overriding.
else simple copy (right-left) elements from end of array (you need to set these elements to zero) and put it from left..right.
You should use memcpy and memset for readability, but also because they are get optimized well by the compiler.
Example:
#include <stdio.h>
#include <string.h>
void array_print (const int* arr, size_t size)
{
for(size_t i=0; i<size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void array_remove (int* arr, size_t size, size_t index, size_t rem_size)
{
int* begin = arr+index; // beginning of segment to remove
int* end = arr+index+rem_size; // end of segment to remove
size_t trail_size = size-index-rem_size; // size of the trailing items after segment
memcpy(begin, // move data to beginning
end, // from end of segment
trail_size*sizeof(int));
memset(begin+trail_size, // from the new end of the array
0, // set everything to zero
rem_size*sizeof(int));
}
int main (void)
{
int array [8] = {3, 5, 6, 8, 2, 9, 10, 1};
const int size = sizeof(array) / sizeof(*array);
array_print(array, size);
array_remove(array, size, 3, 4); // from index 3, remove 4 items
array_print(array, size);
return 0;
}
Though memset, memcpy, memmove are options to you, if you want to implememnt something of your own, it could be something like this.
#include <stdio.h>
#define MAX_ARRAY_INDEX 10
static int array[10] = {1,5,1,4,8,9,6,3,7,2};
int Pull(int *arr, int from, int to, int count)
{
int iter = 0;
if((from<0) || (to<0))
return 0;
if((from>MAX_ARRAY_INDEX) || (to>MAX_ARRAY_INDEX))
return 0;
for(iter = 0; iter < count ; iter++,from++,to++)
{
arr[to] = arr[from];
arr[from] = 0;
}
return 1;
}
int main()
{
int i = 0;
for(i = 0; i < 10; i++)
{
printf(" %d,", array[i]);
}
printf("\n\n");
if(Pull(array, 6, 2, 3));
printf("\nIndexes pulled!");
else
//Error handling, the next part of the code can be vomited?
for(i = 0; i < 10; i++)
{
printf(" %d,", array[i]);
}
printf("\n\n");
Pull(array, 9, 7, 2);
for(i = 0; i < 10; i++)
{
printf(" %d,", array[i]);
}
printf("\n\n");
return 0;
}
Though with this code you need to take care of pulling the indexes completely. May be instead of using a count check in for() loop, you could do it till the MAX_ARRAY_INDEX ?
You cant remove from an array unless it is dynamically initialized.
Google Linked Lists.
Best case scenario would be to substitute to get the answer. such as
int indexStart = 3;
int indexEnd= 6;
for(int i=indexStart; i<A.length;i++){
if(indexEnd<A.length)
A[i]=A[indexEnd+1];
else
A[i]=0;
indexEnd++;
}
We were tasked to make a program that accepts ONLY ten inputs from the user and then sort it into an Even or Odd Array.
Accepts 10 inputs.
Segregates to an Even or Odd Array.
Print how many are in the Even/Odd Array.
Print the numbers in each Array.
This is the program I made:
#include<stdio.h>
int main(){
int even[10];
int odd[10];
int number;
int numOdd = 0;
int numEven = 0;
int sizeOdd = 0;
int sizeEven = 0;
int count;
printf("Input numbers:\n");
for(count = 0; count < 10; count++){
scanf("%d", &number);
if (number %2 == 0){
while (numEven < 10){
even[numEven++] = number;
sizeEven++;
}
}
else {
while (numOdd < 10){
odd[numOdd++] = number;
sizeOdd++;
}
}
}
printf("\n\nEven numbers(%d): ", sizeEven);
for(number = 0; number < numEven; number++){
printf("%d, ", even[number]);
}
printf("\n\nOdd numbers(%d): ", sizeOdd);
for(number = 0; number < numOdd; number++){
printf("%d, ", odd[number]);
}
system("pause");
return 0;
}
But my program just outputs the first numbers in the array and repeats it. Like, if I input 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, I get:
Even numbers (10): 2, 2, 2, 2, 2
Odd numbers (10): 1, 1, 1, 1, 1
Am I wrong with everything/my logic in the program? Am I on the right track and I just have to tweak it a bit? Hope for help!
This may help you:
Why do you add that while loop inside the if and else condition:
if (number %2 == 0){
even[numEven++] = number;
Also even[numEven++] itself increses the value of numEven variable no need to increment again in the next line.
You've used while twice, where you should have used if. As a result, your even array will be filled with the first even number entered, and your odd array will be filled with the first odd number.
Change each while to an if and you may be OK, though I haven't checked for other errors. For example...
if (number %2 == 0){
if (numEven < 10){
even[numEven++] = number;
sizeEven++;
}
}
The while keyword defines a complete loop of it's own - it's not a limit on some other kind of repetition such as (in this case) your addition of elements to each array.
BTW - you don't really need the if checks either. You only input 10 items, so at most you can add 10 items to the even array, or 10 items to the odd array. As the arrays are both large enough to take 10 items, you don't need bounds checks in this code.
The while keyword defines a complete loop of it's own - it's not a limit on some other kind of repetition such as (in this case) your addition of elements to each array.
BTW - you don't really need the if checks either. You only input 10 items, so at most you can add