Moving columns in a bidemensional array in C - c

Hello I have a bidimensional array initiated the following way:
#include <stdio.h>
#include <stdlib.h>
int main(){
char matriz[6][5]={
{'F','H','V','D','U'},
{'E','L','Q','U','E'},
{'P','E','R','S','E'},
{'V','E','R','A','A'},
{'L','C','A','N','Z'},
{'A','Z','Z','Z','Z'}};
system("pause");
}
And I need to move the columns, ordering alphabetically the first line,
I mean, the line that contains {'F','H','V','D','U'}.
I need the following output:
char matriz[6][5]={
{'D','F','H','U','V'},
{'U','E','L','E','Q'},
{'S','P','E','E','R'},
{'A','V','E','A','R'},
{'N','L','C','Z','A'},
{'Z','A','Z','Z','Z'}};
I know I need to use the selective ordering method and a cycle of fors, but I am not sure how.

Declare a struct:
typedef struct{
colChar:char;
colIndex:int;
} COL_HEADER;
Make an array of them, same length as row length:
COL_HEADER myColHeaders[5];
Load up each in a loop, colChar as the column header char, colIndex as the column index, 0-4.
Now you can qsort the array with a comparison function that just compares the colChar. The colIndex keeps track of the initial columns. You now know which col needs to go where in the output.
You can then use a couple of loops to copy the source columns to a 'dest' [6][5], using the myColHeaders[5].colIndex to identify the destination column for each source column.

First you have to compare the first elements of each column to all other top elements,if a column's 1st element is greater than the next column's top element then swap both columns.You can also use qsort function in the algorithm header for sorting.
Below is the implementation:
#include <stdio.h>
int main(){
int i,k,j;
char matriz[6][5]={
{'F','H','V','D','U'},
{'E','L','Q','U','E'},
{'P','E','R','S','E'},
{'V','E','R','A','A'},
{'L','C','A','N','Z'},
{'A','Z','Z','Z','Z'}};
for(i=0;i<4;i++)
{
for(k=i+1;k<5;k++)
{
//comparing top elements of columns
if(matriz[0][i]>matriz[0][k])
{
//swapping columns
for(j=0;j<6;j++)
{
int t=matriz[j][i];
matriz[j][i]=matriz[j][k];
matriz[j][k]=t;
}
}
}
}
//display
for(i=0;i<6;i++)
{
for(k=0;k<5;k++)
printf("%c ",matriz[i][k]);
printf("\n");
}
}

Related

I m trying to build a 2*2 array but my program asks for 5 inputs. Why?

I couldn't zero down where i have missed in the input statement. I have build it to acquire four values as input but it goes one more.
manipulating the array entries to check if the fifth value is stored. Basic things
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
scanf("%d\t",&a[i][j]);
}
printf("\n%d\t%d\n%d\t%d", a[1][1],a[1][2],a[2][1],a[2][2]);
}
You have declared this
int a[2][2];
which has four items, a[0][0], a[0][1], a[1][0] and a[1][1].
However, you are starting your indexing at 1 and going up to 2, so are stepping out of bounds which is undefined behaviour.
Anything can then happen.
Change your loops i.e.:
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
// as you were
to index from 0.
You also need to consider your printf statement, since that oversteps too.
#include <stdio.h>
int main()
{
int i,j,a[2][2];
for(i=0;i<2;i++) /*go through rows - arrays in c go [0- (n-1)]*/
{
for(j=0;j<2;j++)/*go through col */
scanf("%d",&a[i][j]); /*remove \t- now will scan 4 values only */
}
printf("\n%d\t%d\n%d\t%d", a[0][0],a[0][1],a[1][0],a[1][1]);
return 0;
}

Program to run function

I have a question for my assignment:
Write a function called second which takes, as parameters, an array of
positive integers and also an integer representing the size of the
array. The function returns the value of the second largest integer in
the array. If the largest integer in the array repeats, then the
second largest integer is also the largest. For example, if we have
{1, 2, 3, 4, 5, 5 }, the second largest integer is
5. The function should not change the contents of the array in any way. You can assume that the size of the array is at least two.
What I've done:
int second(const int arr[], int size)
{
int num1,num2;
int i;
if(arr[0]>arr[1])
{
num1=arr[0];num2=arr[1];
}
else
{
num1=arr[1];num2=arr[0];
}
for (i=2; i<size; i++)
{
if (arr[i]>num1)
{
num2=num1;
num1=arr[i];
}
else if (arr[i] > num2)
{
num2=arr[i];
}
}
return num2;
}
I have no idea how to type a program that can run the above function and display the integer '5'
The function should not change the contents of the array in any way.
Use a temporary array to perform all the operations. Simply copy the elements from the old array to the new temp array.
Write a function called second which takes, as parameters, an array of
positive integers and also an integer representing the size of the
array
Case 1: if the array is unsorted
You could just sort the elements(ascending order) and return the second last element.
Case 2: If the array is sorted
Just return the second last element.
There are lots of sorting algorithms like quicksort and mergesort which give you a better runtime but you could use bubble sort as well if there is no constraint on time complexity.
Additional Hint:
int second(const int arr[], int size)
{
int temp[size]; //<-----use a temporary array as you're not allowed to modify the original array
int i;
for(i=0;i<size;i++)
{
//copy the elements
}
//sort the temp array in ascending order
return temp[size-2]; //<----return the second last elements
}
I am not looking at your function second. I will leave that to you as an exercise.
To run this function, you will need to make a main program which will create this array and call this function.
#include <stdio.h>
int second(const int arr[], int size);
int main(void)
{
int arr[] = {1,2,3,4,6,7};
int N = sizeof(arr)/sizeof(arr[0]);
printf ("%d ", second(arr, N));
}
You can add your code below the code here and compile.

Counting sort in C apparently works but binarysearch doesn't

I am looking for help regarding the implementation of a counting sort function in the CS50 Course in week 3.
An int Array has to be sorted.
I tested various unsorted arrays and my counting sort function seems to sort the array just correctly, yet my search functions won't work on the sorted array after.
Could someone give me a hint?
void countsort( int array[], int size) {
int count=0;
int zahl=0;
int max=65536;
int countarr [max];
int finalarr [size];
memset (countarr, 0, sizeof(countarr));
for(int i=0;i<size;i++) {
zahl=array[i];
countarr[zahl]++;
}
for(int i=0;i<max;i++) {
while(countarr[i]>0) {
finalarr[count]=i;
countarr[i]--;
count++;
}
}
array=finalarr;
for(int i=0;i<size;i++){
printf(" %i ",array[i]);
}
}
This is my search algorithm used after the array is sorted, it works with sort algorithms from other people.
bool binarysearch(int value, int values[], int n){
int start=0,
end=n,
mid=0,
midpos=0;
while(end>0) {
midpos=(start+end)/2;
mid=values[midpos];
if(mid==value) return true;
if(mid<value) start=++midpos;
if(mid>value) end=--midpos;
}
return false;
}
In binarysearch, the loop condition while(end>0) is wrong.
If we search for a value which is greater than at least one of the elements of the array, end will never be zero.
Try changing it to while(end>=start), which literally means that the considered interval is non-empty.
In countsort, the line array=finalarr; does not copy the whole array.
Instead, the local variable array becomes a pointer to finalarr.
The contents of the original array remain unchanged, and the sorted array is gone when you exit the function.
This explains why your binary search works (better) with other sort functions.
Try changing finalarr[count]=i; to array[count]=i; and get rid of finalarr completely, putting the values into array right away.
Alternatively, you can use memmove instead of that line.

C programming error.2Darrays

I have the code below.The problem is that I am taking a two dimensional array with a rows and 2 col.The 1st col is for storing values and 2nd as a flag.The problem arises when I initialize my flag the values are also getting affected.
#include<stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
int arr[a][1];
int i,j,k,sum=0;
for(i=0;i<a;i++)
{
scanf("%d",&arr[i][0]);
}
for(i=0;i<a;i++)
{
printf("%d\n",arr[i][0]);
}
for(j=0;j<a;j++)
{
arr[j][1]=0;
}
for(i=0;i<a;i++)
{
printf("%d\n",arr[i][0]);//Different Values
}
}
int arr[a][1]; There is only one column and not two.You should use
int arr[a][2];
Here you write out of bounds
arr[j][1]=0;
This is because you write to the second element of an array with only one element.
The size of arr[x] (for any valid x) is just one.
Writing out of bounds leads to undefined behavior.
Your arrays should be something like this :
arr[row][col] where row denotes the number of rows and col the no of coloumns.
Therefore arr[a][1] is a array of a rows and 1 coloumn and therefore your code works wrong.
Your array should be a[a][2]. It means arr is a array with a rows and 2 coloumn.Similarly you have to change the other arr[][] 's throughout the code.

Ascending order arrangement of numbers of a file

How to read a file which contains two columns and sort the first column numbers in ascending order and to print them with their corresponnding 2nd column values using C ?
fopen opens a file.
fscanf reads from a file and splits what is read into bits according to a format specification (e.g. "%d %s" means an integer followed by whitespace followed by a string of non-whitespace characters).
qsort is a standard library function that will sort an array. It sorts the array by comparing one item to another item. You give it the name of a function (which you write) that does this comparison.
I encourage you to read the manual pages for these functions if you are not familiar with them.
The program below uses all this to:
Open a file test.txt
Read lines from the file into an array arr
Sort the array using qsort, using the rowcmp function (rowcmp looks at the numerical value in the first column to determine whether one element is greater than, equal to, or less than another element)
Print out the elements of the array.
The code...
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100
#define MAXITEMS 100
// A row has two columns, the first is a number and
// the second is any string of up to MAXLEN chars
struct row {
int col1;
char col2[MAXLEN];
};
// Function to do comparison of rows
// Sorts numerically on the value in the first column
int rowcmp(struct row * r1, struct row * r2) {
if (r1->col1 < r2->col1) return -1;
if (r1->col1 == r2->col1) return 0;
return 1;
}
int main(int argc, char ** argv) {
struct row arr[MAXITEMS]; // up to MAXITEMS rows
int rows = 0, i;
FILE * stream = fopen("test.txt", "r");
// Read in rows and put first and second columns into struct,
// building up an array
while (fscanf(stream, "%d %s", &(arr[rows].col1), arr[rows].col2) !=EOF) {
rows++;
}
// Sort the array using the rowcmp function to compare items
qsort(&arr[0], rows, sizeof(struct row), (__compar_fn_t)rowcmp);
fclose(stream);
// Print the sorted array
for (i=0; i<rows; i++) {
printf("%d\t%s\n", arr[i].col1, arr[i].col2);
}
}
With input file:
1 apple
3 cucumbers
21 dates
7 figs
4 grapes
output is
1 apple
3 cucumbers
4 grapes
7 figs
21 dates

Resources