I'm working on a program for class. We are using pointers. We had to generate an array with the number of elements being determined by the user (using malloc). I got that part all working. Second we had to sort the array in descending order. I have no clue why I cant get this to work. This code flips the whole array, so that 3 4 5 12 5 becomes 5 12 5 4 3, but that is not what I want. I'm sure it's something small, but for the life of me I cant figure out what I'm doing wrong.
void main()
{
int *p, *sizearray, *q;
int i, siz;
printf("How large do you want the array? Enter a number between 0 and 50\n");
scanf("%d", &siz);
if (siz <= 50)
{
p = genarr(siz);
for (i = 0; i <siz; i++)
printf("%i\n", *(p + i));
arrsort(p,siz);
for (i = 0; i <siz; i++)
printf("%i\n", *(p + i));
}
else
printf("That number was not in the given range");
while(1);
}
#include "stdafx.h"
#include <time.h> // required for the time_t structure
#include <stdlib.h> // Reqwuired for the srand() and rand() functions
#include "ArrEdit.h"
int* genarr(int size)
{
time_t t;
int i, m;
int *sizearr;
sizearr = (int*)malloc(sizeof(int)*size);
srand((unsigned)time(&t));
for (i = 0; i<size; i++)
*(sizearr + i) = rand() % 50;
return sizearr;
free(sizearr);
}
int *arrsort(int*prt, int si)
{
int k, j;
int temp; // holding variable
for (k = 0; k< (si - 1); k++) // element to be compared
for (j = (k + 1); j < si; j++) // rest of the elements
{
swap(&prt[k], &prt[j]);
}
return prt;
}
void swap(int *s, int *r)
{
int pSwap = *r;
*r = *s;
*s = pSwap;
}
for (j = (k + 1); j < si; j++) // rest of the elements
{
swap(&prt[k], &prt[j]);
}
This should only swap if k > j, so you need an if statement:
for (j = (k + 1); j < si; j++) // rest of the elements
{
if (prt[k] > prt[j])
swap(&prt[k], &prt[j]);
}
Related
Im trying to learn C and I'm doing this program to sort an array but It doesn't work and I'm not sure why, I tested each function and works well, someone knows if its a problem of variables or something?
#include <stdio.h>
#include <stdlib.h>
#define N 5
int V[5] = { -383, 386, 277, 415, 293 };
void displayArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
}
int maxim(int v[], int n)
{
int i, m;
m = v[0];
/*
Find maxim element
*/
for (i = 1; i < n; i++)
if (v[i] > m)
m = v[i];
/*
Search element position
*/
for (i = 0; i < N; i++)
if (v[i] == m)
return i;
}
void sort(int v[], int n)
{
int i, pos, t;
for (i = 0; i < n; i++)
pos = maxim(v, n - i);
/*
Swap elements
*/
t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
}
int main()
{
displayArray(V, N);
sort(V, N);
printf("\n");
displayArray(V, N);
return 0;
}
The output is
-383 386 277 415 293 - Original Array
21900 386 277 415 293 - 'Sorted' Array
First fix your maxim function. Its purpose is to find the maximum index of a sequence v of magnitude n. Therefore, remembering the maximum value in m is irrelevant; you want to remember where it resides :
int maxim(int v[], int n)
{
int m=0;
for (int i=1; i<n; ++i)
{
if (v[m] < v[i])
m = i; // save new max location
}
return m;
}
After that, the sort, which is completely wrong. This:
int i, pos, t;
for (i = 0; i < n; i++)
pos = maxim(v, n - i);
is pointless. It calculates, and overwrites, pos repeatedly until the last iteration, which is the only one that is processed with:
t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
E..g, you sort one element, and then exit your sort. You need to sort them all, starting with the full segment, then reducing the size of the segment by one with each iteration after you swap the most-maximum element into position for that segment.
void sort(int v[], int n)
{
for (int i=0; i<(n-1); ++i)
{
int m = maxim(v, (n-i)); // max of this segment
int tmp = v[m];
v[m] = v[n-i-1];
v[n-i-1] = tmp;
}
}
Your program is inefficient, but almost correct. The only place where you must focus is:
void sort(int v[], int n)
{
int i, pos, t;
for (i = 0; i < n; i++)
pos = maxim(v, n - i);
/*
Swap elements
*/
t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
}
Well, C is not Python, so if, after getting pos you want to swap the elements of your array, then you need to group all of the for loop in braces, as in:
void sort(int v[], int n)
{
int i, pos, t;
for (i = 0; i < n; i++) {
pos = maxim(v, n - i);
/*
Swap elements
*/
t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
}
}
pos = maxim(v, n - i);
should be
pos = maxim(v, n);
#include <stdio.h>
#include <string.h>
int ai, aj; // ai and aj to store the value of i and j respectively
int maxx(int a, int b) { // to return max of the two numbers
return (a <= b) ? b : a;
}
void LongestPal(char a[], int n) { // to find longest palindrome
int i, j, max = 0;
int p[1000][1000] = { 0 };
for (j = 0; j < n; j++)
for (i = 0; i <= j; i++) {
if (i == j) { // for one string having only one character
p[i][j] = 1;
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
}
if (j == (i + 1)) { // for string having two characters
if (a[i] == a[j]) { // if the string is like "aa","bb" etc.
p[i][j] = 2;
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
} else { // if string like "ab","ba" etc.
p[i][j] = 1;
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
}
} else { // for all other type of strings
if (a[i] == a[j]) { // if a longer palindrome found
p[i][j] = p[i-1][j-1] + 2;
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
} else { // if no longer palindrome is present
p[i][j] = maxx(p[i+1][j], p[i][j-1]);
if (max < p[i][j]) {
max = p[i][j];
ai = i;
aj = j;
}
}
}
}
}
int main() {
int i, j, n;
char a[1000];
printf("Just enter the string hoss!\n");
scanf("%s", &a);
n = strlen(a);
LongestPal(a, n);
for (i = ai; i <= aj; i++)
printf("%c", a[i]);
return 0;
}
In this program I wanna find longest palindrome Subsequence, but unable to run program
I have written comments for each case
This program for printing longest palindrome subsequence isn't working, When I run it, the Windows console stops working after taking input.
Your program fails because it allocates too much data with automatic storage (aka on the stack). int p[1000][1000] uses 4MB, probably too much for your system default stack size. You can try and use less space by allocating this array as:
int p[n][n];
This is allowed in C99, but your compiler might not support C99.
Your algorithm is a little complicated. Why not enumerate all positions for i and j and just verify with an auxiliary function if you have a palindrome there and keep track of the longest one:
#include <stdio.h>
#include <string.h>
int isPalindrome(const char *a, int i, int j) {
for (; i < j; i++, j--) {
if (a[i] != a[j])
return 0;
}
return 1;
}
void getLongestPalindrome(const char *a, int n, int *ai, int *aj) {
int i, j, maxi, maxj;
for (maxi = maxj = i = 0; i < n; i++) {
for (j = n - 1; j > i + maxj - maxi; j--) {
if (isPalindrome(a, i, j)) {
maxi = i;
maxj = j;
break;
}
}
}
*ai = maxi;
*aj = maxj;
}
int main(void) {
char a[1000];
int i, j;
printf("Enter the string: ");
if (scanf("%999s", a) == 1) {
getLongestPalindrome(a, strlen(a), &i, &j);
printf("longest palindrome at %d..%d: %.*s\n", i, j, j - i + 1, a + i);
}
return 0;
}
I'm currently trying to learn C, and the exercise I found online has me creating a function that returns the index of the smallest value in an array. This is my function:
int return_index_of_minimum(int A[10], int i, int j){
int minimum_value = A[i];
int index_to_return = 0;
for (int index = i; index < j; index++){
if (A[index] < minimum_value){
minimum_value = A[index];
index_to_return = index;
}
}
return index_to_return;
}
i and j are the lower and upper bound numbers the function should look in. For example, if i is 4 and j is 8, that means the function will return the index of the smallest value between indices 4 and 8.
Here is my main function:
#include <stdio.h>
int main(){
int numbers[10];
int user_input = 0;
for (int i = 0; i < 10; i++){
printf("Please enter a number: ");
scanf_s("%d", &user_input);
numbers[i] = user_input;
}
for (int i = 0; i < 10; i++){
int index_of_min_value = return_index_of_minimum(numbers, i, 10);
int old_num = numbers[index_of_min_value];
int new_num = numbers[i];
numbers[index_of_min_value] = new_num;
new_array[i] = old_num;
}
for (int i = 0; i < 10; i++){
printf("%d\n", new_array[i]);
}
}
The user would first enter a bunch of numbers and that would populate the array with the user's values. The idea is to use return_index_of_minimum to return the index of the smallest item in an array, and then set that equal to numbers[0] with a for loop, and then numbers[1], and then so on. old_num is the lowest number in the array, at its previous index. Here, I'm trying to swap that minimum value with whatever is at numbers[i] However, when I'm done sorting through the entire array, and am printing it out, I see that 10 (when the user enters 1-10 randomly for values) is at index 0, and then the rest of the numbers are in order. Does anybody see what is wrong here?
Here is a fix:
int return_index_of_minimum(int A[10], int i, int j){
int minimum_value = A[i];
int index_to_return = i;
...
}
Unfortunately this code doesn't have protection of invalid arguments, but otherwise this is an answer you've been looking for.
The reason is in call index_of_minimum(a, 9, 10): the loop performs only one iteration for index = 9, and because the minimum value is already initialized to value a[9], the index_to_return is not updated due to condition check.
This is a different approach that doesn't have same issue:
int return_index_of_minimum(int A[10], int i, int j){
/* assuming i < j */
int minimum_value = A[i];
int index_to_return = i; /* First element is a candidate */
for (int index = i + 1; index < j; index++){
/* Iterate from second element */
if (A[index] < minimum_value){
minimum_value = A[index];
index_to_return = index;
}
}
return index_to_return;
}
I believe there is an error in your return_index_of_minimum function.
int index_to_return = 0;
The problem lies I think here as the value of index_to_return will stay 0 if you call return_index_of_minimum(numbers, 5, 10); and that numbers[5] if the actual minimum.
However why not use a simple bubble-sort like the one implemented here
/*
* C program to sort N numbers in ascending order using Bubble sort
* and print both the given and the sorted array
*/
#include <stdio.h>
#define MAXSIZE 10
int main(void)
{
int array[MAXSIZE];
int i, j, num, temp;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
}
I have got some more problems with the code. This program ask the user to specify the nr of throws then it throws 3 dices and add these 3 dices to sum.
Then another function sorts the sum form the smallest to the largest with a bubble sorting algorithm.
the first two functions seems to work but the program does not print out the result of the 3rd sorting function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100
//This function ask the user for the amout of throws
int numberofthrows() {
int throws
printf("Type in the number of throws");
scanf("%d", &throws);
return throws;
}
//This function makes the random throws of 3 dices with regard to the number of throws
int filler(int thrownr, int dice1[MAX], int dice2[MAX], int dice3[MAX], int sum[MAX]) {
int i, nr;
srand(time(NULL));
for(i = 0; i <= thrownr; i++) {
nr = rand()%6;
dice1[i] = nr + 1;
nr = rand()%6;
dice2[i] = nr + 1;
nr = rand()%6;
dice3[i] = nr + 1;
sum[i] = dice1[i] + dice2[i] + dice3[i];
}
int j;
for(j = 0; j <= thrownr; j++) {
printf("%d ", dice1[j]);
printf("%d ", dice2[j]);
printf("%d ", dice3[j]);
printf("%d\n", sum[j]);
}
}
//This function sorts the result in form the sum array
int sorter(int thrownr, int sum[MAX], int sortsum[MAX]) {
int tmp, i, j, k, m;
for(i = 0; i <= thrownr; i++) {
sortsum[i] = sum[i];
}
for(m = 0; m <= 10; m++) {
for(j = 0; j <= thrownr; i++) {
if (sortsum[j] > sortsum[j+1]) {
tmp = sortsum[j];
sortsum[j] = sortsum[j+1];
sortsum[j+1] = tmp;
}
}
}
for(k = 0; k <= thrownr; k++) {
printf("%d\n", sortsum[k]);
printf("%d\n", sum[k]);
}
}
int main(void) {
srand(time(NULL));
int dice1[MAX];
int dice2[MAX];
int dice3[MAX];
int sum[MAX];
int sortsum[MAX];
int numberofthrows2;
numberofthrows2 = numberofthrows();
filler(numberofthrows2, dice1, dice2, dice3, sum);
sorter(numberofthrows2, sum, sortsum);
return 0;
}
The code for sorting is a bit wrong. Change
for(m = 0; m <= 10; m++)
To
for(m = 0; m <= thrownr-1; m++)
And
for(j = 0; j <= thrownr; i++)
To
for(j = 0; j < thrownr-m-1; i++)
To fix it. Also, call srand once at the start of main. Don't call it more than once in a program or you might get the same "random" numbers everytime you run your program.
I want to Quicksort a randomly generated array (homework). I'm given a function "randomArray" which generates the random array. However, I don't get correct results. Can anyone point out what's wrong with my code?
There might be a problem with pointers in my code. I don't understand very well why the (given) "randomArray" function takes a pointer variable.
#ifndef UTIL_H
#define UTIL_H
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#define MIN 0
#define MAX 100000
void quicksort(double *a[], int n)
{
if (n <= 1) return;
double *p = a[n/2];
double *b[n], *c[n];
int i, j = 0, k = 0;
for (i=0; i < n; i++) {
if (i == n/2) continue;
if ( a[i] <= p) b[j++] = a[i];
else c[k++] = a[i];
}
quicksort(b,j);
quicksort(c,k);
for (i=0; i<j; i++) a[i] =b[i];
a[j] = p;
for (i= 0; i<k; i++) a[j+1+i] =c[i];
}
void
randomArray (double *array, int length)
{
int i ;
for (i = 0; i < length; i++)
{
array[i] =
(double) (rand () /
(((double) RAND_MAX + 1) / (double) (MAX - MIN + 1))) + MIN;
}
}
int main(void) {
int i;
/* das Array zum Sortieren */
double test_array[9];
randomArray(test_array, 9);
quicksort(test_array, 9);
for(i = 0; i < 9; i++)
printf("%f ", test_array[i]);
printf("\n");
return 0;
}
You allocate an array in the main function:
double test_array[9];
When passing an array to a function
randomArray(test_array, 9);
It decays to a pointer, that's why you also need to pass its length:
randomArray (double *array, int length)