How in the world do you format this for things to line up, ive tried everything, nothing changes?!
printf("N Count\n");
printf("---- ------ \n");
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
count = getOccur(arr, MAX_ELEMENTS, arr[i]);
printf("%1d %1d\n", arr[i], count);
}
I've tried tabbing, spacing, those % signs with the numbers for the last one, it wont change from this
N Count
----- ---
1 1
2 1
3 1
Driving me crazy! I dont get it! lol
EDIT WHOLE PROGRAM NEW QUESTION!
#include <stdio.h>
#define MAX_ELEMENTS 10
int getOccur(int a[], int num_elements, int value);
void printArr(int a[], int num_elements);
int main()
{
int arr[MAX_ELEMENTS];
int trim[MAX_ELEMENTS];
int count, target, i;
int j, k, temp;
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
printf("Enter a variable for the array: ");
scanf("%d", &arr[i]);
}
for (j = 1 ; j <= MAX_ELEMENTS-1 ; j++)
{
for(k = 0 ; k <= MAX_ELEMENTS-2 ; k++)
{
if(arr[k] > arr[k+1])
{
temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
}
printf("%4s %6s\n", " N ", "Count");
printf("%4s %6s\n", "----", "------");
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
count = getOccur(arr, MAX_ELEMENTS, arr[i]);
printf("%3d %4d\n", arr[i], count);
}
}
int getOccur(int a[], int tally, int value)
{
int i;
tally = 0;
for( i = 0 ; i < MAX_ELEMENTS ; i++)
{
if (a[i] == value)
{
++tally;
}
}
return(tally);
}
void printArr(int a[], int amount)
{
int i;
for(i = 0 ; i < amount ; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
printf("%4s %6s\n", " N ", "Count");
printf("%4s %6s\n", "----", "------");
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
count = getOccur(arr, MAX_ELEMENTS, arr[i]);
printf("%4d %6d\n", arr[i], count);
}
That should line everything up.
EDIT
In response to the question in the comments, my approach would be to first find all the unique values in arr and save them to a different array (call it unique). Then you'd walk through the unique array in your loop:
for (i = 0; i < uniqueCount; i++)
{
count = getOccur(arr, MAX_ELEMENTS, unique[i]);
printf("%4d %6d\n", unique[i], count);
}
As for finding unique elements, the brute force method would be something like
size_t uniqueCount = 0;
int unique[MAX_SIZE]; // needs to be same size as original array in case
// all values are unique
for (i = 0; i < MAX_SIZE; i++)
{
size_t j = 0;
for (j = 0; j < uniqueCount; j++)
if (arr[i] == unique[j])
break;
if (j == uniqueCount)
unique[uniqueCount++] = arr[i];
}
For each element in the original array, we scan the (initially empty) unique array. If we don't find the value of a[i] in the unique array, we add it and increment uniqueCount.
Note that this method is pretty inefficient and will perform poorly as MAX_ELEMENTS gets large. Better solutions are available, but you sound like you're still at the bottom of the learning curve, so I'll leave it at that.
This is what you are looking for. The first column you have four - so the minimum width is four, the next column has size - so minimum width is 6 as specified in the format string. see printf manual page
printf("N Count\n");
printf("---- ------ \n");
for(i = 0 ; i < MAX_ELEMENTS ; i++)
{
count = getOccur(arr, MAX_ELEMENTS, arr[i]);
printf("%4d %6d\n", arr[i], count);
}
EDIT
Edited first printf
Related
I want to create a program that can read scores from user and display the scores output in the form of stars. But it seems that my code keep getting an infinity loop. Can anyone tell me what is wrong with my looping.
#include <stdio.h>
int main() {
int i, k, j;
int score[5];
for(i = 1; i < 6; i++) {
printf("\nplease enter the score for %d match : ", i);
scanf("%d", &score[i]);
}
printf("\nstatistics collection points for 5 matches\n\n");
for (k = 1; k < 6; k++) {
printf("%d. ", k);
for (j = 1; j <= score[k]; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Array indices are 0 based in C. So for an array with 5 elements the indices are from 0-4 inclusive. You are using indices 1-5 which results in buffer overflow. Below is the corrected program with the for loops fixed up to use the right indices:
#include <stdio.h>
#define NUM_SCORES 5
int main()
{
int i, k, j;
int score[NUM_SCORES];
for(i = 0; i < NUM_SCORES ; i++)
{
printf("\nplease enter the score for %d match : ", i);
scanf("%d", &score[i]);
}
printf("\nstatistics collection points for 5 matches\n\n");
for (k = 0; k < NUM_SCORES ; k++){
printf("%d. ", k);
for(j = 1; j <= score[k]; j++){
printf("*");
}
printf("\n");
}
return 0;
}
You should also add a check to ensure scanf is able to successfully read each input.
hi this is my code can you help me out not printing output properly how to print output given in description , i am not getting way to sort the given output, output should be sorted from given average.
Implement fragments using array of pointers.
Rows are static and columns are dynamic. Fixed no.of rows and columns will vary for each row.
Example:
Read no.of rows from user and allocate the memory statically for rows.
Read no.of columns for each row and allocate the memory dynamically.
Let us Assume, Row = 3.
Row[0] = 4 columns, Row[1] = 3 columns and Row[2] = 5 columns.
While allocating the memory for columns you have allocate for no.of columns + 1 dynamically.
After that read the values from user and calculate the average for each row separately and store that average in that extra memory block which you added while allocating the memory.
Then sort the array based on the average.
Print the output on the screen.
Example is given below.
ENTER THE NUMBER OF ARRAY YOU WANT TO GIVE AS INPUT: 3
ENTER NO. OF COLUMNS IN ROW[0]: 3
ENTER NO. OF COLUMNS IN ROW[1]: 3
ENTER NO. OF COLUMNS IN ROW[2]: 3
ENTER 3 VALUES OF ROW[0]: 2 3 5
ENTER 3 VALUES OF ROW[1]: 2 4 7
ENTER 3 VALUES OF ROW[2]: 2 1 0
BEFORE SORTING OUTPUT IS:
2 3 5 3.33333
2 4 7 4.33333
2 1 0 1
AFTER SORTING OUTPUT IS:
2 1 0 1
2 3 5 3.33333
2 4 7 4.33333
My code so far:
#include <stdio.h>
#include <stdlib.h>
int fragments(int rows, int *array)
{
int i, j;
int pos[rows];
float *arr[rows], avg, sum;
char *temp[rows];
for (i = 0; i < rows; i++)
{
arr[i] = malloc(sizeof(float*) * array[i]+1);
pos[i] = i;
printf("Enter %d values for row[%d]: ", array[i], i);
for (j = 0; j< array[i]; j++)
{
scanf(" %f", &arr[i][j]);
}
}
printf("Before Sorting output is:\n");
for (i = 0; i < rows; i++)
{
sum = 0;
for (j = 0; j < array[i]; j++)
{
printf("%f ", arr[i][j]);
sum = sum + arr[i][j];
}
printf("%f\n", arr[i][j] = (sum / j));
}
for (i = 0; i < rows - 1; i++)
{
for (j = 0; j < rows - i - 1; j++)
{
if (arr[j][array[j]] > arr[j+1][array[j+1]])
{
temp[j][j] = arr[j][array[j]];
arr[j][array[j]] = arr[j+1][array[j+1]];
arr[j+1][array[j+1]] = temp[j][j];
}
}
}
for (i = 0; i < rows; i++)
{
for (j = 0; j < array[i] + 1; j++)
{
printf("%f ", arr[i][array[j]]);
}
printf("\n");
}
}
int main()
{
int rows, i, j;
printf("Enter no of rows: ");
scanf("%d", &rows);
int array[rows];
int pos[rows];
for (i = 0; i < rows; i++)
{
printf("Enter no of columns in row[%d]:", i);
scanf("%d", &array[i] );
}
fragments(rows, array); //`enter code here`
}
There are multiple problems in your code:
The allocation size is incorrect: arr[i] = malloc(sizeof(float*) * array[i]+1); should read:
arr[i] = malloc(sizeof(float) * (array[i] + 1));
the swapping code should swap the array pointers and the array sizes. The current code does not make sense. Use this instead:
float *temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
int temp1 = array[j];
array[j] = array[j+1];
array[j+1] = temp1;
the final print loop is incorrect: instead of printf("%f ", arr[i][array[j]]); you should write:
printf("%f ", arr[i][j]);
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int fragments(int rows, int *array) {
float *arr[rows];
for (int i = 0; i < rows; i++) {
arr[i] = malloc(sizeof(float) * (array[i] + 1));
printf("Enter %d values for row[%d]: ", array[i], i);
for (int j = 0; j < array[i]; j++) {
if (scanf("%f", &arr[i][j]) != 1)
return;
}
}
printf("Before Sorting output is:\n");
for (int i = 0; i < rows; i++) {
float sum = 0;
for (j = 0; j < array[i]; j++) {
printf("%f ", arr[i][j]);
sum += arr[i][j];
}
printf("%f\n", arr[i][j] = sum / j);
}
for (int i = 0; i < rows - 1; i++) {
for (int j = 0; j < rows - i - 1; j++) {
if (arr[j][array[j]] > arr[j+1][array[j+1]]) {
float *temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
int temp1 = array[j];
array[j] = array[j+1];
array[j+1] = temp1;
}
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < array[i] + 1; j++) {
printf("%f ", arr[i][j]);
}
printf("\n");
}
for (int i = 0; i < rows; i++) {
free(arr[i]);
}
}
int main() {
int rows;
printf("Enter no of rows: ");
if (scanf("%d", &rows) != 1)
return 1;
int array[rows];
for (int i = 0; i < rows; i++) {
printf("Enter no of columns in row[%d]:", i);
if (scanf("%d", &array[i]) != 1)
return 1;
}
fragments(rows, array);
return 0;
}
So as the question says i am just trying to sort an array with duplicate values.
The array is sorted properly but problem arises when a duplicate value is given to the array
O/P:without duplicate
Enter the size of the array : 5
Enter the 5 elements
7 3 4 8 1
After sorting: 1 3 4 7 8
Original array value 7 3 4 8 1
O/P: with duplicates
5 3 1 1 4
After sorting: 1 3 4 1 3
Original array value 5 3 1 1 4
#include <stdio.h>
void print_sort(int *arr, int size) //function definition
{
int i, j, k, temp, largest = arr[0], smallest = arr[0];
for( i = 1 ; i < size ; i++ )
{
if(arr[i] > largest)
{
largest = arr[i];
}
if(arr[i] < smallest)
{
smallest = arr[i];
}
}
printf("After sorting: ");
for(i = 0; i < size; i++)
{
temp = largest;
printf("%d ", smallest);
for(k = i + 1; k < size; k++)
{
if(arr[i] == arr[k])
{
smallest = arr[i];
break;
}
for(j = 0; j < size; j++)
{
if(arr[j] > smallest && arr[j] < temp)
{
temp = arr[j];
}
}
smallest = temp;
}
}
printf("\n");
printf("Original array value ");
for( i = 0 ; i < size ; i++ )
{
printf("%d ", arr[i]);
}
}
int main()
{
int size, i;
printf("Enter the size of the array : ");
scanf("%d", &size);
int arr[size];
printf("Enter the %d elements\n",size);
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
print_sort(arr, size);
}
I understand that it is a specific exercise (homework ?), with no possibility to modify the array not to use an additional array.
This implies that classical sorting algorithms cannot work.
Iteratively searching for the minimum is a possible solution, even if not efficient O(n^2).
To cope with duplicates, it it necessary not only to memorize the current minimum, but also its position.
This is a possible implementation.
#include <stdio.h>
#include <stdlib.h>
void print_sort(int *arr, int size) //function definition
{
int i, j, k, largest = arr[0], smallest = arr[0];
int i_smallest = 0;
for (i = 1; i < size; i++ ) {
if (arr[i] > largest) {
largest = arr[i];
}
if(arr[i] < smallest) {
smallest = arr[i];
i_smallest = i;
}
}
printf("After sorting: ");
for (i = 0; i < size; i++) {
int temp = largest + 1;
int i_temp = -1;
printf("%d ", smallest);
if (i == size-1) break;
for (k = 0; k < size; k++) {
if (arr[k] < smallest) continue;
if (arr[k] == smallest) {
if (k <= i_smallest) continue;
i_temp = k;
temp = smallest;
break;
}
if (arr[k] < temp) {
temp = arr[k];
i_temp = k;
}
}
smallest = temp;
i_smallest = i_temp;
}
printf("\n");
printf("Original array value ");
for( i = 0 ; i < size ; i++ )
{
printf("%d ",arr[i]);
}
}
int main(void) {
int size, i;
printf("Enter the size of the array : ");
if (scanf("%d", &size) != 1) exit(1);
int arr[size];
printf("Enter the %d elements\n",size);
for (i = 0; i < size; i++) {
if (scanf("%d", &arr[i]) != 1) exit(1);
}
print_sort(arr, size);
return 0;
}
Maybe it is easier to insert each read value directly into the sorted Array. So you don't have to sort the array afterwards.
If you want to do it this way, geeksforgeeks.org has nice examples also for C which I already used (https://www.geeksforgeeks.org/search-insert-and-delete-in-a-sorted-array/).
// C program to implement insert operation in
// an sorted array.
#include <stdio.h>
// Inserts a key in arr[] of given capacity. n is current
// size of arr[]. This function returns n+1 if insertion
// is successful, else n.
int insertSorted(int arr[], int n, int key, int capacity)
{
// Cannot insert more elements if n is already
// more than or equal to capacity
if (n >= capacity)
return n;
int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];
arr[i + 1] = key;
return (n + 1);
}
/* Driver program to test above function */
int main()
{
int arr[20] = { 12, 16, 20, 40, 50, 70 };
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 26;
printf("\nBefore Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
// Inserting key
n = insertSorted(arr, n, key, capacity);
printf("\nAfter Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
I've been trying to sort columns in a matrix (the dimensions are m,n <= 10) via the lexicographical order (if the columns share the same element, then we compare the elements in the row beneath etc.) with some additional conditions. I need to use functions to print the matrix, input random integers up to 5 as its elements and finally arrange the matrix. I think I got the printing and random inputs correctly but I can't figure out the sorting. Plus I can't use global variables which I have no idea how to do, since I haven't been shown. An example matrix would be :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m, n;
int mat[10][10];
void print_matrix()
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void random_int()
{
int i, j;
srand((unsigned)time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = rand() % 5;
}
}
}
void arrange()
{
int i, j, k, a;
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
for (k = i + 1; k < m; ++k)
{
if (mat[i][j] < mat[k][j])
{
a = mat[i][j];
mat[i][j] = mat[k][j];
mat[k][j] = a;
}
}
}
}
}
printf("Input the number of rows : ");
scanf("%d", &m);
printf("Input the number of columns: ");
scanf("%d", &n);
random_int(mat[m][n]);
print_matrix(mat[m][n]);
arrange(mat[m][n]);
print_matrix(mat[m][n]);
return 0;
}
Try this solution(will work for input 0-8 only), also used global variables:
There have multiple solutions. but is the easiest one.
I have converted each of the columns as an integer value. then bubble sorted the integers. After sorting. I have then converted the integer value to digits. (You have to know how to convert individual digits to multiple digit integer and multiple digit integers to single-digit.
Note I have added one(1) with each digit. Because the input can be zero(0). if you convert 0 0 2 1 to an integer will be only 21. the first two digits lost. So I have added 1. so 0 0 2 1 will be converted to 1132. I have done (added 1) for each input(deducted 1 after sorting). so it will not affect other inputs. Be careful input have to be from(0 to 8)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int m, n;
int mat[10][10];
int generatedNumber[10];
void print_matrix()
{
printf("The matrix is:\n");
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
void random_int()
{
int i, j;
srand((unsigned)time(NULL));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
mat[i][j] = rand() % 5;
}
}
}
void arrange()
{
int i, j, k, a;
for (j = 0; j < n; ++j)
{
int number = 0;
for (i = 0; i < m; ++i)
{
number = number * 10 + mat[i][j] + 1;///Adding one for avoiding zero(0)
}
generatedNumber[j] = number;
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if( generatedNumber[j] > generatedNumber[j+1])
{
// swap the elements
int temp = generatedNumber[j];
generatedNumber[j] = generatedNumber[j+1];
generatedNumber[j+1] = temp;
}
}
}
for(i = 0; i < n; i++)///columwise
{
int generatedColumnvalue = generatedNumber[i];
for(j = m -1; j>= 0; j--)///row wise and fro last vaue to first
{
mat[j][i] = (generatedColumnvalue%10)-1;///removing extra added 1
generatedColumnvalue/=10;
}
}
}
int main()
{
printf("Input the number of rows : ");
scanf("%d", &m);
printf("Input the number of columns: ");
scanf("%d", &n);
random_int();
print_matrix();
arrange();
print_matrix();
return 0;
}
I'm learning C, and trying to print a boolean matrix (5 x 5) from couples of numbers (edges of a graph) in input. If the position of the elements in the matrix has corresponding edges it is "1", otherwise "0". For example:
I put as input: 1 2, 1 4, 2 4, 2 3, 3 5
I want that in the position (1,2) and (2,1); (1,4) and (4,1); (2,4) and (4,2); (2,3) and (3,2), (3,5) and (5,3) it prints 1, but 0 in all the others.
This is what I was able to write, but doesn't really work:
(I have studied multidimensional arrays, but I can't see if they might be useful for this case.)
int i, j;
int array1[5], array2[5];
for (i = 0; i < 5; ++i)
{
printf("Insert the edges %d of the graph\n", i);
scanf("%d %d", &array1[i], &array2[i]);
}
printf("{");
for (i = 0; i < 5; ++i)
printf("(%d,%d)", array1[i], array2[i]);
printf("}\n");
for (i = 0; i < 5; ++i) {
for (j = 0; j < 5; ++j)
if (((array1[i] == i+1) && (array2[i] == j+1)) || ((array1[i] == j+1) && (array2[i] == i+1))) printf("%d ", 1);
else printf("%d ", 0);
printf("\n"); }
What I should see (with those sample inputs):
http://imageshack.com/a/img537/9986/jx5roa.png
What I get:
http://imageshack.com/a/img537/6341/kroVQK.png
Thank you for your time!
You should create the 2-dimensional array. Initially fill it with all zeroes, then when the user enters the edges you change those elements to one.
#define SIZE 5
int array[SIZE][SIZE];
int i, j;
// Initialize array to 0
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
array[i][j] = 0;
}
}
// Get edges from user
for (i = 0; i < SIZE; i++) {
int e1, e2;
printf("Insert the edges %d of the graph\n", i);
scanf("%d %d", &e1, &e2);
// Set them to 1
array[e1-1][e2-1] = 1;
array[e2-1][e1-1] = 1;
}
// Display the array
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}