Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
#include <stdio.h>
int main () {
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
So I have this code so far, it writes every single element on the screen, but I would also like to write the highest number and its index. I'm only a beginner, so I'd like to ask your opinion.
It is nice to get effort (and code) with a question. Good job. All you need to do is compare each array value and save the largest as max. Note, whenever searching for a maximum value, it is good practice to initialize your max value as the minimum for that storage type ('int') in this case. So initializing to INT_MIN insures that any value (even a large negative one if all your values are negative) will be larger than the initial value. To capture the indexes where the maximum value occurs, simply save the index values for i, j each time you save a max value and you will have captured the indexes where the maximum value occurrs:
#include <stdio.h>
#include <limits.h>
int main () {
int a[][2] = {{0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int maxrow = -1, maxcol = -1;
int nrows = sizeof a/sizeof *a;
int i, j, max = INT_MIN;
for (i = 0; i < nrows; i++) {
for (j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
/* find largess value */
if (a[i][j] > max) {
max = a[i][j];
maxrow = i;
maxcol = j;
}
}
}
printf ("\n maximum value at 'a[%d][%d]' : %d\n\n",
maxrow, maxcol, max);
return 0;
}
Compile
gcc -Wall -Wextra -O3 -o bin/array_max array_max.c
Output
$ ./bin/array_max
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8
maximum value at 'a[4][1]' : 8
In C function main without parameters shall be declared like
int main ( void )
As for the searching of the maximum element then the approach is simple. At first it is supposed that the maximum element is the first element of the array. Then all other elements of the array are compared with this maximum and if some element is greater than the maximum then it becomes the maximum.
For example
#include <stdio.h>
#define M 5
#define N 2
int main ( void )
{
int a[M][N] =
{
{ 0, 0 }, { 1, 2 }, { 2, 4 }, { 3, 6 }, { 4, 8 }
};
int i, j;
int max_i, max_j;
for ( i = 0; i < M; i++ )
{
for ( j = 0; j < N; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
max_i = 0;
max_j = 0;
for ( i = 0; i < M; i++ )
{
for ( j = 0; j < N; j++ )
{
if ( a[max_i][max_j] < a[i][j] )
{
max_i = i;
max_j = j;
}
}
}
printf( "The maximum value is %d at row %d and column %d\n",
a[max_i][max_j], max_i, max_j );
return 0;
}
you can use the following code:
int max,pi,pj;
max = –2147483648;
for(i=0; i<5; i++) {
for(j=0; j<2; j++) {
if(a[i][j] > max) {
max = a[i][j];
pi = i;
pj = j;
}
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
#include <stdio.h>
int main () {
int []={1,2,3,7,8}; // add element after 3 --> 4,5,6 (condition that i don't know position of 3 in array)
for(int i=0,i<10;i++)
{
printf("%d\n",n[i]);
}
return 0;
}
i want output 1,2,3,4,5,6,7,8
but remember in case i don't know the position of 3 or 7 in array
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
// n = len of tab
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
int main()
{
int len = 10;
int top_number_count = 3;
int data[10] = {1, 11, 3, 4, 5, 20, 7, 8, 9, 10};
int temp[10];
// copy the tab for dont change any value
for (int i = 0; i < len; i++) {
temp[i] = data[i];
}
// sort the new tab
bubbleSort(temp, len);
// print the top number
// top_number_count is the count of max number you want
for (int i = len - top_number_count; i < len; i++)
printf(">%d\n", temp[i]);
return 0;
}
As the number of large values to be displayed may vary, sorting the array is the best choice. There are different techniques of sorting. For this program I shall use the "bubble sort"(if you wish to learn other sorting techniques, check this).
Once the array is sorted in descending order(largest to smallest), we can specify the number of large values we need. The program below displays the first 3 largest numbers.
#include <stdio.h>
int main()
{
int data[10] = {0, 12, 90, 8, 1, 2, 7, 9, 11, 10} ;
int MaxElements = 10 ;
int endBoundary = MaxElements - 1 ;
for(int index = 0 ; index <= MaxElements-1 ; index++)
{
for(int counter = 0 ; counter < endBoundary ; counter++)
{
if(data[counter] < data[counter+1]) // then swap the values
{
int temp = data[counter] ;
data[counter] = data[counter+1] ;
data[counter+1] = temp ;
}
}
endBoundary-- ;
}
// displaying the first 3 largest numbers
int numOfValuesSought = 3 ;
for(int count = 0 ; count < numOfValuesSought ; count++)
{
printf("%d\n", data[count]) ;
}
return 0 ;
}
I have this weird problem, When I run following code snippet, it gives me wrong answer. I am trying to find smallest positive number from 2D array.
I tried combining two if conditions in one if, placing brackets, interchanging if conditions. But while I debug I see, control never goes inside if greater than 0 condition.
float smallest(float b[3][4]);
int main()
{
float a[3][4],result;
int i, j;
printf("\nEnter 12 numbers into the array:\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
scanf("%f", &a[i][j]);
}
printf("\n");
}
result=smallest(a);
printf("\nSamllest positive number is %.1f", result);
system("pause");
return 0;
}
float smallest(float b[3][4])
{
int i, j;
float min = b[0][0];
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (b[i][j]<min)
if (b[i][j]>0)
min = b[i][j];
}
}
return min;
}
Enter 12 numbers into the array:
-5
4
9
7
6
2
3
1
-7
5
4
7
Samllest positive number is -5.0
It is becuse you set min to b[0][0] which is -5 in your example, so the only number where if (b[i][j]<min) is true is -7. But your second if only true if the number is greater than 0. Which is false for -7, therefore min = b[i][j]; this code never executes.
Initialize min to FLT_MAX and it should be fine. (Although this could be problematic if the array only contains negative numbers.)
assign first positive value of array to your min and then use your code.
int check = 0;
int i, j;
float min=-2;//this is for case when all elements are negative
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (b[i][j] > 0)
{
min = b[i][j];
check = 1;
break;
}
}
if (check == 1)
break;
}
so your smallest function:
float smallest(float b[3][4])
{
int check = 0;
int i, j;
float min=-1;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (b[i][j] > 0)
{
min = b[i][j];
check = 1;
break;
}
}
if (check == 1)
break;
}
if(min<0)
printf("no positive number");
else
{
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (b[i][j]<min)
if (b[i][j]>0)
min = b[i][j];
}
}
}
return min;
}
you also should check if returned min is navigate or positive in main.
if it was negative no positive value were found.
The function initially is defined incorrectly.
For starters the function shall have a second parameter that specifies the number of "rows" in the array. This function declaration
float smallest(float b[3][4]);
is equivalent to the following function declaration
float smallest(float b[][4]);
and the both declarations declare the same one function the declaration of which is adjusted by the compiler to the fol;lowing
float smallest(float ( *b )[4]);
Secondly the array can have no positive element. SO in this case the function will return an incorrect value.
Th function should return either an index or a pointer to the minimum positive elements. And if the index or the pointer is outside the array then it means that the array does not have a positive element.
Here is a demonstrative program that shows how the function can be defined and how in the caller there can be determine whether the array has a minimum positive element.
#include <stdio.h>
#define N 4
size_t smallest( float a[][N], size_t size )
{
size_t i = 0;
float *p = ( float * )a;
while ( i < size * N && !( 0 < p[i]) ) ++i;
size_t min = i;
for ( ++i; i < size * N; i++ )
{
if ( 0 < p[i] && p[i] < p[min] ) min = i;
}
return min;
}
int main(void)
{
float a[][N] =
{
{ -5, 4, 9, 7 },
{ 6, 2, 3, 1 },
{ -7, 5, 4, 7 }
};
const size_t M = sizeof( a ) / sizeof( *a );
size_t min = smallest( a, M );
if ( min < M * N )
{
printf( "The smallest positive element is %.1f\n", a[min / N][min % N] );
}
else
{
puts( "There ia no minimal positive element in the array" );
}
return 0;
}
The program output is
The smallest positive element is 1.0
#include <stdio.h>
void main()
{
int maj, count, n = 6;
int arr[] = {1, 2, 2, 2, 2, 3, 4};
for (int i = 0; i < n; i++) {
maj = arr[i];
count = 0;
for (int j = 9; j < n; j++) {
if (arr[j] == maj) count++;
}
if (count > n / 2) {
break; /* I think some problem is here ,if majority element not found then it takes last element as the majority element */
}
}
printf("%d", maj);
}
It is giving correct output if majority ellement is there but incorrect output if no majority element is there for example if array is {1,2,3,4} it is giving output as 4. please help!!
#include <stdio.h>
int main() {
int maj, count, n = 7; //n is size of arr
int arr[] = {1, 2, 2, 2, 2, 3, 4};
int isFound = 0; //0 -> false, 1 -> true
for (int i = 0; i < n; i++) {
maj = arr[i];
count = 1; //first elements is itself
isFound = 0; //by default we assume that no major elements is found
for (int j = i+1; j < n; j++) { //iterate from next elements onwards to right in array
if (arr[j] == maj) count++;
}
if (count > n / 2) {
isFound = 1;
break; //major elements found; no need to iterator further; just break the loop now
}
}
if(isFound) printf("%d ", maj);
else printf("no major element");
return 0;
}
For starters according to the C Standard function main without parameters shall be declared like
int main( void )
Try not to use magic numbers. Usually as in your program they are a reason for program bugs. For example you declared the array arr as having 7 elements however the variable n that should keep the number of elements in the array is initialized with the value 6. Another magic number 9 is used in the loop
for (int j = 9; j < n; j++) {
^^^
There is no need to write the outer loop that travers the whole array. Also the program does not report the case when the majority number does not exist in the array.
Using your approach with two loops the program can look the following way
#include <stdio.h>
int main( void )
{
int a[] = { 1, 2, 2, 2, 2, 3, 4 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t i = 0;
for ( ; i < ( N + 1 ) / 2; i++ )
{
size_t count = 1;
for ( size_t j = i + 1; count < N / 2 + 1 && j < N; j++ )
{
if ( a[i] == a[j] ) ++count;
}
if ( !( count < N / 2 + 1) ) break;
}
if ( i != ( N + 1 ) / 2 )
{
printf( "The majority is %d\n", a[i] );
}
else
{
puts( "There is no majority element" );
}
return 0;
}
Its output is
The majority is 2
I should make new array out of existing one (ex. 1 0 4 5 4 3 1) so that the new one contains digits already in existing array and the number of their appearances.
So, the new one would look like this: 1 2 0 1 4 2 5 1 3 1 (1 appears 2 times, 0 appears 1 time.... 3 appears 1 time; the order in which they appear in first array should be kept in new one also); I know how to count no. of times a value appears in an array, but how do I insert the no.of appearances? (C language)
#include <stdio.h>
#define max 100
int main() {
int b, n, s, i, a[max], j, k;
printf("Enter the number of array elements:\n");
scanf("%d", &n);
if ((n > max) || (n <= 0)) exit();
printf("Enter the array:\n");
for (i = 0; i < n; i++)
scanf("%d", a[i]);
for (i = 0; i < n; i++) {
for (j = i + 1; j < n;) {
if (a[j] == a[i]) {
for (k = j; k < n; k++) {
a[k] = a[k + 1];
}}}}
//in the last 5 rows i've tried to compare elements, and if they are same, to increment the counter, and I've stopped here since I realised I don't know how to do that for every digit/integer that appears in array//
If you know that the existing array consists of digits between 0 and 9, then you can use the index of the array to indicate the value that you are incrementing.
int in[12] = {1,5,2,5,6,5,3,2,1,5,6,3};
int out[10] = {0,0,0,0,0,0,0,0,0,0};
for (int i = 0; i < 12; ++i)
{
++out[ in[i] ];
}
If you provide any code snippet, its easy for the community to help you.
Try this, even you optimize the no.of loops :)
#include <stdio.h>
void func(int in[], int in_length, int *out[], int *out_length) {
int temp[10] = {0}, i = 0, j = 0, value;
//scan the input
for(i=0; i< in_length; ++i) {
value = in[i];
if(value >= 0 && value <= 9) { //hope all the values are single digits
temp[value]++;
}
}
// Find no.of unique digits
int unique_digits = 0;
for(i = 0; i < 10; ++i) {
if(temp[i] > 0)
unique_digits++;
}
// Allocate memory for output
*out_length = 2 * unique_digits ;
printf("digits: %d out_length: %d \n",unique_digits, *out_length );
*out = malloc(2 * unique_digits * sizeof(int));
//Fill the output
for(i = 0, j = 0; i<in_length && j < *out_length; ++i) {
//printf("\n i:%d, j:%d val:%d cout:%d ", i, j, in[i], temp[in[i]] );
if(temp[in[i]] > 0 ) {
(*out)[j] = in[i];
(*out)[j+1] = temp[in[i]];
temp[in[i]] = 0; //Reset the occurrences of this digit, as we already pushed this digit into output
j += 2;
}
}
}
int main(void) {
int input[100] = {1, 0, 4, 5, 4, 3, 1};
int *output = NULL, output_length = 0, i = 0;
func(input, 7, &output, &output_length );
for(i=0; i < output_length; i+=2) {
printf("\n %d : %d ", output[i], output[i+1]);
}
return 0;
}
I am trying to write a code to solve the problem of taking two numbers m and n as an input from user and then calculating A(m,n) as follows:
1. A(m,n) = A(m,n-1) + A(m-1,n) , m,n >=0
2. A(m,n) = m-n if m<0 or n<0
I have written the following code in C, but the problem is that the answer coming is not correct, because the initialization of the variable value to zero, erases the value while recursion is going on and the answer I get is incorrect. Anybody knows how to solve this issue?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num1=0;
int num2=0;
int rows=0;
int columns=0;
int i,j,**array;
printf("Enter two non-negative integer numbers \n");
scanf("%d %d",&num1,&num2);
//create 2d-Array
rows=num1+1;
columns=num2+1;
array=malloc(rows * sizeof(int *));
for(i=0;i<rows;i++)
{
array[i]=malloc(columns*sizeof(int));
}
for (i = 0; i < rows; i++ )
{
for(j= 0; j < columns; j++ )
{
array[i][j]=0;
}
}
//Fill data in array
computeArray(array,rows,columns);
// Display contents of array
for (i = 0; i < rows; i++ )
{
for(j= 0; j < columns; j++ )
{
printf("array[%d][%d] = %d\n", i,j, array[i][j] );
}
}
getch();
return 0;
}
int computeArray (int **array, int rows, int columns)
{
int i,j;
for(i=0; i<rows;i++)
{
for(j=0;j<columns;j++)
{
array[i][j]=computeFunction(array,i,j);
}
}
return **array;
}
int computeFunction(int **array, int i, int j)
{
printf("Value reset by zero\n");
int value=0;
if((i<0)||(j <0))
{
value = i-j;
printf("Value contains i-j value\n");
return value;
}
else
{
value = (computeFunction(array,i,j-1)+ computeFunction(array,i-1,j));
printf("Value updated after else\n");
return value;
}
}
The answer for 0,0 should be -2, but I am getting 0 due to the initialization issue. Please let me know if you know how to overcome this issue?
It's being computed correctly - it should be 0.
A(m,n) = A(m,n-1) + A(m-1,n) , m,n >=0
A(m,n) = m-n if m<0 or n<0
So A(0,0) = A(0,-1) + A(-1,0) = (0 - (-1)) + (-1 - 0) = 1 + (-1) = 0