How to create loops for ordering vectors - c

I have a homework problem that asks for my code to read a 10-length vector, order it in ascendant order and then print it. I'm trying to do this using a variable int k as a countable index, where the code verifies whether a particular position in the vector is greater than the other positions, and adds 1 to k for each smaller variable. Then, I create a second vector, and atrribute for its kth position this value of the first vector.
The compilation isn't pointing out any mistakes. The code runs, I inform the 10 values of the vector, then it returns a big number and crashes.
Could anyone help me? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main ()
{
setlocale(LC_ALL, "Portuguese");
//creates two double vectors
double v[10], w[10];
//creates a int variable to be a countable index
int k = 0;
//asks for the user to inform the values of the vector
for (int i=0; i<=9; i++)
{
printf("Digite um número:\n");
scanf("%lf", &v[i]);
}
//Here, I create this loop to verify whether each position of the vector v is greater than the other positions.
for (int j=9; j>=0; j--)
{
//For the case j=9, I verify if it is greater than all the predecessor values, and add 1 to k for each case
if (j==9)
{
for (int t=j-1; t>=0; t--)
{
if (v[j]>v[t])
{
k+=1;
}
}
//I attribute this value of v to the kth position of the new vector, and restart the countable index
w[k]=v[j];
k=0;
continue;
}
//I do the same for the case in which j=0, verifying whether it is greater than the subsequent values
else if (j==0)
{
for (int s=j+1; s<=9; s++)
{
if (v[j]>v[s])
{
k+=1;
}
}
w[k]=v[j];
k=0;
continue;
}
//For all the other values of the vector, I test both whether they are greater than the
//predecessors and the subsequent values, and add 1 to k for each case
else
{
for (int t=j-1; t>=0; t--)
{
if (v[j]>v[t])
{
k+=1;
}
}
for (int s=j+1; s<=9; s--)
{
if (v[j]>v[s])
{
k+=1;
}
}
//I attribute this value to the kth position of the new vector and restart the countable index
w[k]=v[j];
k=0;
}
//Here my loop ends
}
//I print the new vector
for (int p=0; p<=9; p++)
{
printf(" %lf ",w[p]);
}
system("pause");
return 0;
}

for (int s=j+1; s<=9; s--) should have s++. I don't see anything else wrong but I'll check with gdb if that doesn't fix it.

Related

create a matrix with specific conditions

I would like to create a matrix with these specifics
text of exercise
write a program that reads a number k > 0 and a permutation of the first K numbers (from 0 to k-1) that does not fix any element and produce (printing on consecutive lines) permutations p0, . . . , ph such that (1) p0 is permutation given in input; (2) fro every i > 0, pi is the smallest permutation of K cthat does not fix any element and does not collide with any other permutation from p0 and pi−1. We say that 2 permutations p1, p2 ok
K collides if exists and index i from 1 to k such that p1(i) = p2(i).
my ideas i wanted to create a k*k matrix amd the first row will be the imput of a vector i will declare. I tought to fill the matrix in these way : let's take a specific element v[i][j]
v[i][j]is in the matrix if 1)v[k][j] from k =0,...,i-1 is different from v[i][j],1)v[i][k] from k =0,...,i-1 is different from v[i][j],v[i][j] is different from i , and from the remaining possibilities for v[i][j] it is the minimum from the remainin number 0,...k-1
code implementations
#include <stdio.h>
#include <stdlib.h>
#define N 50
typedef int matrix[N][N];
int min(int vector[],int n)
{
int i;
int p=0;
int min=vector[0];
for(i=0; i<n;i++)
{
if (vector[i]<=min)
{
min=vector[i];
p=i;
}
}
return min;
}
int main()
{
int k;
printf("\n insert a number ");
scanf("%d",&k);
int v[k][k];//creation of matrix I wanted
int input[k];//first row
int arrayindex[k]={0};// array from 0 to k
for(int u=0; u<k;u++)
{
arrayindex[u]=u;
}
printf("insert component of vector:");
for(int l=0;l<k;l++)
{
printf("input[%d]= ",l);
scanf("%d",&input[l]);
}
//print vector
for(int l=0;l<k;l++)
{
printf("%d",input[l]);
}
printf("\n\n");
// copy first row
for(int j=0;j<k;j++)
{
v[0][j]=input[j];
}
//printf of first row
for(int j=0;j<k;j++)
{
printf("\nv[0][%d]=%d ",j,v[0][j]);
}
//try to fill matrix
for(int i=1; i<k;i++)
{
for(int j=0;j<k;j++)
{
if (j=0){
v[i][j]!=v[i-1][j];
v[i][j]!=j;
v[i][j]=min(arrayindex,k);}
if(j!=0)
v[i][j]!=v[i-1][j];
v[i][j]!=v[i][j-1];
v[i][j]!=j;
v[i][j]=min(arrayindex,k);
}
}
//print of matrix
printf("\n the matrix is:\n ");
for(int i=0; i<k;i++)
{ printf("\n");
for(int j=0;j<k;j++)
{
printf("%d",v[i][j]);
}
}
return 0;
}
the problem in this code is in the section called try to fill matrix . When I compile nothing appear on the screen .Where is the problem ? is at least idea correct?

Transfering a 2-dimensional array into a single dimension array

I'm trying to make a program in C that transfers a 2-dimensions-array(a matrix to be particular) into a single-dimension-array. For example, if we have a matrix with L lines and C columns, it should turn into a a single line newL=L*C. Therefore, if the matrix has 3 lines and 4 columns, the new array will have 3*4=12 as its size.
The matrix should turn to this:
1 2
--> 1 2 3 4
3 4
The problem I'm facing right now, is how to assign the matrix to the array without having random values or repeated values.
The piece of code I'm concerned with, goes like this:
for(k=1;k<=t;k++)
{
for(i=1;i<=l;i++)
{
for(j=1;j<=c;j++)
{
v[k]=m[i][j];
}
}
}
k,i and j are counters of the matrix(2-dimensions-array) and the the array. two of which; i and j, are counters for the matrix and k is the array's counter. Notice that each one of them starts from 1 and goes to its size and in this size I will use 2 lines and 2 columns for the matrix therefore the array will have a size of 4(2*2).
l is the number of lines in the array.
c is the number of colunms in the array.
t is the size of the array. t=l*c
Executing the code gives me this as a return:
1 2
--> 4 4 4 4
3 4
Simply said, the piece of code will ALWAYS give the last value of the matrix to the array. So if I replace 4 with 5 in the matrix, the array will have 5 5 5 5.
EDIT:
Here is the full code to understand what I'm trying to do:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c,i,j,l,k,t;
printf("Donner le nombres des lignes: ");
scanf("%d",&l);
printf("Donner le nombres des colonnes: ");
scanf("%d",&c);
int m[l][c];
t=l*c;
int v[t];
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
printf("Donner m[%d][%d]: ",i+1,j+1);
scanf("%d",&m[i][j]);
}
}
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",m[i][j]);
}
printf("\n");
}
printf("\n\n\n\n");
for(k=1;k<=t;k++)
{
for(i=1;i<=l;i++)
{
for(j=1;j<=c;j++)
{
v[k]=m[i][j];
}
}
}
for(k=0;k<t;k++)
{
printf("%d\t",v[k]);
}
system("pause");
}
Thank you guys for the help, I found the correct way to do it.
You need not the outer loop
Array indices are zero-based in C
Thus, we have:
for(k = 0, i = 0; i < o; i++)
{
for(j = 0; j < p; j++)
{
v[k++] = m[i][j];
}
}
where o and p - dimensions of the matrix m
If we have a multidimensional array like this:
int nums[3][3];
And we have:
int all[9];
And we've got:
int a, b;
We'll reference each of the nums like this:
nums[a][b];
Now think of what the values of a and b will actually be:
for (a = 0; a < 3; a++) {
for (b = 0; b < 3; b++)
all[((a * 3) + b)] = nums[a][b];
}
This will work so long as you multiply a with the number of elements it will iterate:
int nums[5][5];
int all[25];
int a, b;
for (a = 0; a < 5; a++) {
for (b = 0; b < 5; b++)
all[((a * 5) + b)] = nums[a][b];
}
You mention your question is "how to I fix the code?" I think plenty of people have given you the correct answer. This is your code along with the corrected code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c,i,j,l,k,t;
printf("Donner le nombres des lignes: ");
scanf("%d",&l);
printf("Donner le nombres des colonnes: ");
scanf("%d",&c);
int m[l][c];
t=l*c;
int v[t];
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
printf("Donner m[%d][%d]: ",i+1,j+1);
scanf("%d",&m[i][j]);
}
}
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",m[i][j]);
}
printf("\n");
}
printf("\n\n\n\n");
/* corrected code below */
k = 0;
for(i=0;i<l;i++)
{
for(j=0;j<c;j++)
{
v[k]=m[i][j];
k++;
}
}
/* corrected code above */
for(k=0;k<t;k++)
{
printf("%d\t",v[k]);
}
system("pause");
}
As long as the new array is the correct size, something like the following should work:
k=0;
for(i=0;i<l;i++){
for(j=0;j<c;j++){
v[k]=m[i][j];
k++;
}
}
Essentially, you are traversing over the matrix (your lines and columns--as you put it) and at the same time increasing the position (k) in the new array where you want that value to be put.
This:
for(k=1;k<=t;k++)
for(i=1;i<=l;i++)
for(j=1;j<=c;j++)
v[k]=m[i][j];
does not do what you think. Think about when you first loop through the j part, you will be setting all the 0th element of v the entire time, finally the last value you set will stick (ie, the one in position 1, 1 which happens to be 4). Then you will increment k to 1 and repeat it again, resulting in all 4's. You want this:
for(i = 0; i < l; i++)
for(j = 0; j < c; j++)
v[i*l+j] = m[i][j]; // i*l + j gives you the equivelent position in a 1D vector.
Make sure your v vector is the right size ie. int v[l*c];. Also remember that in c zero indexing is used.If you really do need 1 based indexing (which you dont ...) then do this:
int k = 1;
for(i = 1; i <= l; i++)
for(j = 1; j <= c; j++)
v[k++]=m[i][j];
But remember that this will make any further operations on this vector Gross. So dont do this ....
If you just want to access the matrix elements as a single dimension array, you could declare an int pointer v:
int m[3][4];
int *v = (int*)m;
// then access for example m[1][1] as v[5]
Or, to actually copy the array, use a double for (as in the other answers), a single for like below
int vv[12];
for(i = 0; i < 12; i++)
vv[i] = m[i/4][i%4];
or just use memcpy:
memcpy(vv, m, 12*sizeof(int));

Counting occurrences of the largest number

I have been attempting to code for a program that stores input into an array and then allows me to print it out. It also lets me know which number is the largest. What I am trying to figure out is how can I get my program to tell me the amount of times (occurrences) the largest number in array is input. Here is my code so far. As of now, this code outputs the numbers I enter to the array, the largest element in the array, and the occurrence of every number I input( The occurrences of the numbers are incorrect). In all the the amount of occurrences for every number turns out to be 0. Which is obviously incorrect. Again, I need my program to display the largest number (which it does) and the occurrences of ONLY the largest number. All advice, tips, or thoughts are welcome. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int main()
{
int arrayNum[15];
int a;
int max=0;
int location;
for( a=0; a < 15; a++)
{
printf("Enter element %d:", a);
scanf("%d",&arrayNum[a]);
}
for(a=0; a < 15; a++)
{
printf("%d\n", arrayNum[a]);
}
for (a = 1; a < 15; a++)
{
if (arrayNum[a] > max)
{
max = arrayNum[a];
location = a+1;
}
}
printf("Max element in the array in the location %d and its value %d\n", location, max);
for(a=0; a<15; a++)
{
if(arrayNum[a+1] == arrayNum[a])
continue;
else
printf("Number %d: %d occurences\n", arrayNum[a]);
}
return 0;
}
I spot some problems in your code. First, the third for loop starts at 1, but it does not update the max as the value of arrayNum[0].
Then, for the problem at hand, I would have two variables:
int max; // The maximum value
int max_count; // The count of the maximum value
Then, the logic to find the greatest, and the count, is the following:
For each element, compare it with the maximum seen. If it is equal, increment max_count. If it is bigger, update max with the value, and set the max_count to 1. If it is smaller, ignore it. Something like:
max = arrayNum[0];
max_count = 1;
for (int a = 1; a < 15; ++a)
{
if (arrayNum[a] == max)
max_count++;
else if (arrayNum[a] > max)
{
max_count = 1;
max = arrayNum[a];
}
}
All you need to do is introduce a new variable to keep track of the number of occurrences of max. When a new value of max is found, set that count to zero. When a subsequent value is found equal to the max, increment the counter.
Incidentally, your code doesn't properly find the maximum in its current form. Try one test case where your array elements are all negative. Try another test case in which all the values are positive, and the first value entered (arrayNum[0]) is the maximum. You will find, in both cases, that your function will not actually find the maximum.
Just before you begin the below loop max is still 0 make
max = a[0];
for (a = 1; a < 15; a++)
{
if (arrayNum[a] > max)
{
max = arrayNum[a];
location = a+1;
}
}
Later
int n=0;
for(i=0;i<15;i++)
{
if(max == a[i])
n++;
}
printf("Number of times max appears in the array is %d\n",n);
Replace last for loop with below code
NoOfOccurances = 0;
for(a=0; a<15; a++)
{
if(max == arrayNum[a])
{
NoOfOccurances++;
}
}
printf("Number %d: %d occurences\n", max,NoOfOccurances);
For your third for-loop, the one where you find out the largest number in your array, I would suggest to set max to arrayNum[0], that way it will work even with negative numbers.
Then, to know how many occurrence of the highest number there is, you need a count variable that you increment (count++) each time a number of the array is equal to max. To do that you need another for-loop.
Good luck.
You can do what you want in just one loop iteration:
int count = 1;
int position = 0;
int max = arrayNum[0];
int N = 15;
int p;
for (p = 1; p < N; ++p)
{
if (arrayNum[p] > max) // Find a bigger number
{
max = arrayNum[p];
pos = p;
count = 1;
}
else if ( arrayNum[p] == max) // Another occurrences of the same number
count++;
}
A simple solution with time complexity of O(n)
int maxoccurence(int a[],int ar_size)
{
int max=a[0],count=0,i;
for(i=0;i<ar_size;i++)
{
if(a[i]==max)//counting the occurrence of maximum element
count++;
if(a[i]>max)//finding maximum number
{
max=a[i];
count=1;
}
}
printf("Maximum element in the array is %d\n",max);
return count;
}

sort a 2d array and find the index and store in a array

I have a 2d array which has same numbers in a row.
I have to find the index of the elements in increasing order and put it in another array.
For example, assume that the input array has the following numbers:
int test[5][2]= { {12,12},{3,3},{14,14},{5,5},{8,8} }.
I have to output in result array with:
result[5] = {1,3,4,0,2}.
Just the index of the elements in increasing order...
I wrote this program, but the result array is always 1.
int main()
{
int N=5;
int result[5];
int test[5][2] = { {12,12},{3,3},{14,14},{5,5},{8,8} };
int i,j;
int smallindex = 0;
for (j=0; j<5; j++)
{
for (i=1; i<5; i++)
{
if (test[i][0] < test[i-1][0])
{
smallindex=i;
}
}
result[j]=smallindex;
}
for (j=0; j<5; j++)
{
printf("%d \t ", result[j]);
}
}
Can anyone tell me what is wrong in this?.
thanks
Make little modification for if statement in your code.
for(i=0;i<5;i++)
{
smallindex=0;
for(j=0;j<5;j++) {
//try to avoid comparing same element by checking i==j
if(test[i][0]<test[j][0])
smallindex++; // check each element with all elements.count how many elements are greater than specific element.increment count and at the end of inner loop assign to result array.
}
result[i]=smallindex;
}

printing randome choices from an array

I am working on a function that picks random numbers from a given array and prints them to stdout. These numbers should not repeat and how many numbers are picked is given to the function along with the array. I have a separate test file for the function and a header file as well. Everything compiles fine but when I run the program I get a hang up in the pickNumbers function, nothing is printed and I don't even know if anything is being chosen to begin with.
#include <stdio.h>
#include <stdlib.h>
#include "head.h"
//program that picks random numbers from the given array
int alreadyPicked(int choices[], int choice);
void pickNumbers(int myArray[],int max)
{
// delcare/initilize variables
int i;
int choices[max];
int length = sizeof(myArray)/sizeof(myArray[0]);
// seed rand
srand(time(NULL));
// pick a random choice until that given number of choices is reached
// to make sure non repeat run against alreadyPicked function
for (i=0; i <= max; i++) {
do{
choices[i] = (rand() % max);
}while (alreadyPicked(choices, choices[i]) == TRUE);
}
for (i=0; i <= max; i++) {
printf("%d", myArray[choices[i]]);
}
printf("\n");
}
int alreadyPicked(int choices[], int choice)
{
int i;
int answer = FALSE;
for (i=0; i <= (sizeof(choices)/sizeof(choices[0])); i++) {
if(choices[i] == choice)
answer = TRUE;
}
return answer;
}
Perhaps
for (i=0; i <= max; i++) {
must be:
for (i=0; i < max; i++) {
and
for (i=0; i <= (sizeof(choices)/sizeof(choices[0])); i++) {
must be:
for (i=0; i < (sizeof(choices)/sizeof(choices[0])); i++) {
In your first "for" loop you have a nested while/do. You increment "i" in your for loop, instead you should increment the variable inside of while/do, otherwise it will hang forever performing such loop because "i" is never incremented.
Replace:
for (i=0; i <= max; i++) {
by:
for (i=0; i < max;) {
And also replace:
choices[i] = (rand() % max);
By:
choices[i++] = (rand() % max);
This way you make sure "i" is being incremented. Also your construction "i<=max" is incorrect since you start from 0, use the way David RF did.
Apart from the aforementioned wrong loop tests, the reason for the endless loop is that in alreadyPicked() you compare the new choice index with every choice index in choices[], including uninitialized ones and the new one itself; thus, alreadyPicked() always returns TRUE. I suggest to change to call of alreadyPicked() to
alreadyPicked(choices, i)
and its implementation to
int alreadyPicked(int choices[], int choice)
{
for (int i = 0; i < choice; i++)
if (choices[i] == choices[choice])
return TRUE;
return FALSE;
}

Resources