My sort function won't print the sorted array?
I'm trying to write a program that gathers array elements, sorts the array, then prints the factorial of each element. I don't want to get ahead of myself and write the recursive function if the array isn't being sorted correctly. The sort seems fine to me; people have criticized me using while loop but I don't know another way yet. Any input is appreciated.
#include <stdio.h>
int sorter(int numbList[]);
int getData(int numList[]);
//int recursive(int numList[]);
int main(void) {
int x;
int numberList[x];
getData(&numberList[x]);
sorter(&numberList[x]);
//recursive(&numberList[x]);
return 0;
}
//gets user input-data
int getData(int numbList[]) {
int i;
int x;
printf("Enter number of Elements:\n");
scanf("%d", &x);
printf("Enter the values for each element starting from first
element:\n");
for (i = 0; i < x; i++) {
scanf("%d", &numbList[i]);
}
printf("\nYou have filled the array list with\n");
for (i = 0; i < x; i++) {
printf("%d\n", numbList[i]);
}
return numbList[x];
}
//sorter function
int sorter(int numbList[]) {
int x;
int temp;
int swapped;
while (1) {
swapped = 0;
for (int i = 0; i < x; i++) {
if (i > numbList[i + 1]) {
temp = numbList[x];
numbList[x] = numbList[x + 1];
numbList[x + 1] = numbList[x];
swapped = 1;
}
if (swapped == 0) {
break;
}
}
printf("Array as sorted:\n");
for (int i = 0; i < x; i++) {
printf("%d\t", numbList[x]);
}
return(numbList[x]);
}
}
//recursive factorial function
/* int recursive(int numbList[]) {
int b = 0;
numbList[b] *= numbList[b - 1];
return 0;
} */
Some hints as comments in your code:
It still won't do the job, but get you in better shape...
int main(void)
{
//uninitialized x!
int x;
//Even if you get a value for x, VLAs are depreciated
int numberList[x];
//Both calls get the adress of last value + 1 in numberList.
//So you a) go out of the array bounds, and b) why would you want
//the last element's address??
//Just use it like getData(numberList);
getData(&numberList[x]);
sorter(&numberList[x]);
return 0;
}
//gets user input-data
//What is the return value for?
int getData(int numbList[])
{
int i;
int x;
printf("Enter number of Elements:\n");
scanf("%d",&x);
printf("Enter the values for each element starting from first element:\n");
for(i=0;i<x;i++){
scanf("%d",&numbList[i]);
}
printf("\nYou have filled the array list with\n");
for(i=0;i<x;i++){
printf("%d\n",numbList[i]);
}
//see above
return numbList[x];
}
//sorter function
//Again, what and why return?
int sorter(int numbList[])
{
//uninitialized x!
int x;
int temp;
int swapped;
while(1)
{
swapped=0;
for(int i=0;i<x;i++)
{
//What do you compare here? Think.
if(i>numbList[i+1])
{
temp=numbList[x];
numbList[x]=numbList[x+1];
//What do you have temp for??
numbList[x+1]=numbList[x];
swapped=1;
}
//Pretty sure you want an else clause here
if(swapped==0)
{
break;
}
}
printf("Array as sorted:\n");
for(int i=0;i<x;i++)
{
printf("%d\t",numbList[x]);
}
return(numbList[x]);
}
}
There are multiple problems in your code:
the number of elements x is uninitialized when you define the array numbList[x]. This has undefined behavior. You should pass a pointer to the count to getData and this function should update this value, allocate the array, read the values and return a pointer to the array.
You should not break strings on multiple lines without a \
The swap code is broken: the test if (i > numbList[i + 1]) is incorrect, it should be
if (numbList[i] > numbList[i + 1])
the swap code should use i instead of x as an index and the last assignment in the swap code should store temp into numbList[i + 1].
the inner loop should stop at x - 1 to avoid reading past the end of the array.
you should let the inner loop run to the end and break from the outer loop if swapped == 0.
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int *getData(int *count);
void sorter(int numList[], int count);
int main(void) {
int x;
int *numberList;
numberList = getData(&x);
if (numberList != NULL) {
printf("Elements entered:");
for (int i = 0; i < x; i++) {
printf(" %d", numberList[i]);
}
printf("\n");
sorter(numberList, x);
printf("Sorted array:");
for (int i = 0; i < x; i++) {
printf(" %d", numberList[i]);
}
printf("\n");
free(numberList);
}
return 0;
}
//gets user input-data
int *getData(int *countp) {
int i, x;
int *numbList;
printf("Enter the number of elements: ");
if (scanf("%d", &x) != 1 || x <= 0) {
printf("Invalid size:");
return NULL;
}
numbList = calloc(sizeof *numbList, x);
if (numbList == NULL) {
printf("Memory allocation error:");
return NULL;
}
printf("Enter the element values: ");
for (i = 0; i < x; i++) {
if (scanf("%d", &numbList[i]) != 1) {
free(numbList);
return NULL;
}
}
*countp = x;
return numbList;
}
//sorter function
void sorter(int numbList[], int x) {
for (;;) {
int swapped = 0;
for (int i = 0; i < x - 1; i++) {
if (numbList[i] > numbList[i + 1]) {
int temp = numbList[i];
numbList[i] = numbList[i + 1];
numbList[i + 1] = temp;
swapped = 1;
}
}
if (swapped == 0) {
break;
}
}
}
You can use bubble sort algorithm technique which is fast sorting algorithm and it uses for loop instead of while loop
int bubbleSorter(int numbList[])
{
int temp;
int i, x;
bool swapped = false;
for (i = 0; i < x - 1; i++)
{
swapped = false;
for (j = 0; j < x - 1 - i; j++)
{
if (list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
else {
swapped = false;
}
}
// if no number was swapped that means
// array is sorted now, break the loop.
if (!swapped) {
break;
}
printf("Array as sorted:\n");
for (int i = 0; i<x; i++)
{
printf("%d\t", numbList[x]);
}
return(numbList[x]);
}
}
Related
This is my last try. I tried to find the most popular element in a string, for do this i've taken the string and converted single character in number and after this i sorted them in int array.
the problem is: when i use the 2d array for keep the frequency of each number: x[1][y]. and which number: x[0][y]. for some reason they are trash number
can someone help me?
(my english is rusty, sry).
#include<stdio.h>
#include<time.h>
#include<math.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
#include<malloc.h>
void bubble(int a[],int x);
void frequenza(int A[], int n);
int main(){
size_t counter;
char a[] = "asrfujefwaa";
int b[20];
int x;
x = strlen(a);
for(counter = 0; counter != strlen(a); counter ++)
{
b[counter] = a[counter];
}
bubble(b,x);
for(counter = 0; counter != x; counter ++)
{
printf("%d ",b[counter]);
}
puts("\n");
system("pause");
puts("\n");
frequenza(b,x);
return 0;
}
void bubble(int a[],int x)
{
size_t i;
int ord;
int scambio;
scambio = 0;
if(ord == 1)
{
return;
}
else
{
ord = 1;
for(i = 0; i < x - 1; i++)
{
if(a[i] > a[i + 1])
{
scambio = a[i];
a[i] = a[i + 1];
a[i + 1] = scambio;
ord = 0;
}
}
bubble(a,x);
}
}
void frequenza(int A[], int n)
{
int x[2][n];
int z = 0;
int y = 0;
size_t q;
x[0][0] = A[0];
x[1][0] = 1;
for(z = 0; z != n; z++)
{
if(x[0][y] == A[z + 1])
{
x[1][y] += 1;
}
if(x[0][y] != A[z + 1])
{
y++;
x[0][y] = A[z + 1];
}
}
for(z = 0; z != 2; z++)
{
puts("\n");
for(q = 0; q != y;q++)
{
printf("%d ",x[z][q]);
}
}
}
If you want to find the most common character in a string, you don't need to sort it or anything fancy. Just iterate through the characters, recording how many times each one has been seen, and get the maximum such count. You can do it all with a single pass through the string if you keep track of the maximum to date as you go:
#include <limits.h>
#include <stdio.h>
int main(void)
{
char a[] = "asrfujefwaa";
int freqs[UCHAR_MAX + 1] = { 0 }; // Initialize frequency table to all 0's
int most_common = 0;
for (unsigned char *c = (unsigned char *)a; *c; c++) {
if (++freqs[*c] > freqs[most_common]) {
most_common = *c;
}
}
printf("Most common character is %c, with %d occurrences.\n",
most_common, freqs[most_common]);
return 0;
}
This program for selection sort gives unfavorable output, I tried a lot but unable to find my mistake, The output, I'm getting through this is not sorted, one or more elements are at wrong position(or they are not sorted)...Please help me to find my mistake.
#include <stdio.h>
void swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int *get_least(int *p, int i, int count)
{
int temp = *(p + i), key = 0;
int *index;
for (i; i < count; i++)
{
if (temp > *(p + i))
{
temp = *(p + i);
index = (p + i);
key++;
}
}
if (key == 0)
{
return (p + 1);
}
return (index);
}
void sel_sort(int *p, int count)
{
for (int i = 0; i < count - 1; i++)
{
swap((p + i), get_least(p, i, count));
}
}
int main()
{
int num[10], count;
printf("ENTER INPUT LIMIT:\n");
scanf("%d", &count);
printf("ENTER YOUR NUMBERS:\n");
for (int i = 0; i < count; i++)
{
scanf("%d", &num[i]);
}
sel_sort(num, count);
printf("OUTPUT AFTER SORTING:\n");
for (int i = 0; i < count; i++)
{
printf("%d ", num[i]);
}
return (0);
}
I'm getting this output:
As you mentioned in comments, You want to return address. now, When you return (p+i) as an address, Your i value get changed and holds the last incremented value from for loop, so the returned address is diffrent from what You supposed to return.
I'm creating a program that reads input from an array and orders it in an ascending order. However, I also wanted to count the number of times each element appears in the array, but I'm struggling to to this. This is the code I have so far:
#include <stdlib.h>
#include <locale.h>
typedef enum _ordem {
Crescente=1
} ordem;
void troca(int *x, int *y){
int wk;
wk=*x;*x=*y;*y=wk;
}
int trocar(int x, int y, ordem dir){
if(dir == Crescente)
return x > y;
return 0;
}
void bubbleSort(int *array, int top, int fim, ordem dir){
int i, j, trocado;
for(i = top; i < fim; ++i){
trocado = 0;
for(j = top + 1; j <= fim - i; ++j)
if(trocar(array[j-1], array[j], dir)){
troca(&array[j-1], &array[j]);
trocado = 1;
}
if(trocado == 0)break;
}
}
int main(){
int vetor[100], index, ordem=1;
index=0;
setlocale(LC_ALL,"Portuguese");
printf("Introduza os nĂºmeros. Escreva -00 para parar. \n");
do{
scanf("%d", &vetor[index++]);
}while(vetor[index-1] != -00 && index < 100);
--index;
bubbleSort(vetor, 0, index-1, ordem);
{
int i;
for(i=0;i<index;++i)
printf("%d ", vetor[i]);
printf("\n");
}
return 0;
}
After the numbers have been sorted, equal numbers will be next to each other in the array. This makes it easy to count the number of times each number occurs using a single loop that iterates through the sorted array, with an extra variable that is incremented when the next element has the same number as the current element, or is reset when the next element has a different number.
The following block of code will do that:
{
int i, c;
c = 1;
for (i = 0; i < index; ++i) {
if (i < index - 1 && vetor[i] == vetor[i + 1]) {
c++;
} else {
printf("%d(x%d) ", vetor[i], c);
c = 1;
}
}
printf("\n");
}
You could create another array to store a table of the unique values with their frequency of occurrance:
struct freq {
int val;
int freq;
};
struct freq freq[100];
int nfreq = 0;
Fill the table using a loop similar to the earlier code:
{
int i, c;
c = 1;
for (i = 0; i < index; ++i) {
if (i < index - 1 && vetor[i] == vetor[i + 1]) {
c++;
} else {
freq[nfreq].val = vetor[i];
freq[nfreq].freq = c;
nfreq++;
c = 1;
}
}
}
Print the out the table with another simple loop:
{
int i;
for (i = 0; i < nfreq; i++) {
printf("%d(x%d) ", freq[i].val, freq[i].freq);
}
printf("\n");
}
So I'm creating a sudoku solver in C. Here's my full code as of now, I've mostly been using python and just got into C, I basically converted a lot of python functions to C to get this but I think it'll work:
#include <stdio.h>
#include <stdlib.h>
int is_empty();
int possible_v();
int solver();
int main(){
int s_array[9][9];
FILE * fpointer;
int i;
int j;
fpointer = fopen("sudoku001.txt", "r");
for (i=0; i<9; i++){
for(j = 0; j<9; j++){
fscanf(fpointer, "%d", &s_array[i][j]);
}
}
for (i=0; i<9; i++) {
if (i % 3 == 0) {
printf("------------------------------\n");
}
for (j = 0; j < 9; j++) {
printf(" %d ", s_array[i][j]);
if ((j + 1) % 3 == 0) {
printf("|");
}
}
printf("\n");
}
solver(s_array);
for (i=0; i<9; i++) {
if (i % 3 == 0) {
printf("------------------------------\n");
}
for (j = 0; j < 9; j++) {
printf(" %d ", s_array[i][j]);
if ((j + 1) % 3 == 0) {
printf("|");
}
}
printf("\n");
}
return 0;
}
int is_empty(int board[9][9]){
int i;
int j;
int is_empty= 0;
for (i=0; i<9; i++){
for(j = 0; j<9; j++){
if (board[i][j] == 0) {
is_empty = 1;
break;
}
}
if (is_empty == 1){
break;
}
}
return is_empty;
}
int possible_v(int board[9][9], int i, int j) {
int p_array[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
int x;
int y;
int temp;
for (x = 0; x < 9; x++) {
if (board[x][j] != 0) {
temp = board[x][j];
p_array[temp - 1] = temp;
}
}
for (y = 0; y < 9; y++) {
if (board[i][y] != 0) {
temp = board[i][y];
p_array[temp - 1] = temp;
}
}
int m;
int n;
int temp1;
int temp2;
if (i>= 0 && i <= 2) {
m = 0;
}
else if (i>= 3 && i<=5) {
m = 3;
}
else{
m = 6;
}
if (j>= 0 && j <= 2) {
n = 0;
}
else if (j>= 3 && j<=5) {
n = 3;
}
else{
n = 6;
}
temp1 = m;
temp2 = n;
for (temp1; temp1<temp1+3; temp1++){
for (temp2; temp2<temp2+3; temp2++){
if (board[temp1][temp2] != 0){
p_array[board[temp1][temp2]] = 1;
}
}
}
temp1 = 1;
for (temp1; temp1<10){
if (p_array[temp1] == 0){
p_array[temp1] = temp1;
}
else{
p_array[temp1] = 0;
}
}
return p_array;
}
int solver(int board[9][9]){
int i;
int j;
int x;
int y;
int empty_check;
int p_values;
int temp;
if (is_empty(board) == 0){
printf("Board Completed");
empty_check = 0;
return empty_check;
}
else{
for (x = 0; x < 9; x++){
for (y = 0; y< 9; y++){
if (board[x][y] == 0){
i = x;
j = y;
break;
}
}
}
p_values = possible_v(board, i, j);
for (temp = 1; temp <10; temp++){
if (p_values[temp] != 0){
board[i][j] = p_values[temp];
solver(board);
}
}
board[i][j] = 0;
}
}
My main issue when compiling is getting the last two functions work with each other.
Function 'solver' calls and binds function 'possible_v'. Possible_V returns an array which I need to solve the puzzle. How can I make this work? .
You have the array locally declared, hence it cannot be passed back since it is destroyed once the function is exited. The workaround to this is to dynamically declare the array using malloc int *parray = (int*)malloc(9*sizeof(int)); and using the return type int* instead of int. But do not forget to free the allocated memory, else you will just keep allocating new memory from heap for every call you make.
As a side note, your implementation of Sudoku solver is a bit complex, and there is no need to return an array. You need to pass only the board. Here is an implementation of Sudoku Solver. This works both for 9x9 and 6X6 boards.
Edit : As advised by David Rankin, I have converted the C++ code to C.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int n;
int issafe(int **board,int i,int j,int num){
for(int k=0;k<n;k++)
if(board[i][k] == num || board[k][j] == num)
return 0;
int cellx,celly;
if(n==6){
cellx = (i/2)*2;
celly = (j/3)*3;
for(int l=cellx;l<cellx+2;l++)
for(int m=celly;m<celly+3;m++)
if(board[l][m] == num){
return 0;
}
return 1;
}
int root = sqrt(n);
cellx = (i/(root))*root;
celly = (j/(root))*root;
for(int l=cellx;l<cellx+root;l++)
for(int m=celly;m<celly+root;m++)
if(board[l][m] == num)
return 0;
return 1;
}
int solve(int **board,int i,int j){
if(i == n)
return 1;
if(j == n){
return solve(board,i+1,0);
}
if(board[i][j] != 0)
return solve(board,i,j+1);
for(int k=1;k<n+1;k++)
if(issafe(board,i,j,k)){
board[i][j] = k;
if(solve(board,i,j+1))
return 1;
//backtrack
board[i][j] = 0;
}
return 0;
}
int main(){
do{
printf("Enter size of board(9 or 6): ");
scanf("%d",&n);
}while(n != 9 && n != 6);
int **board;
board = malloc(sizeof *board * n);
for(int i=0;i<n;i++)
board[i] = malloc(sizeof *board * n);
// input
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%d",&board[i][j]);
if(solve(board,0,0))
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
printf("%d ",board[i][j]);
printf("\n");
}
return 0;
}
What command could one use to check if the sum of any two numbers within an array add up to a certain value of x.
The following solution should help you:
int TestArray (int array[], int count, int targetSum)
{
int i,j;
for (i=0; i<count-1; i++)
{
for (j=i+1; j<count; j++)
{
if (array[i] + array[j] == targetSum)
{
return 1;
}
}
}
return 0;
}
This function takes as arguments the array, the number of array elements (3 in your example), and the target sum to check for (5 in your case).
Usage is like this (sample main):
int main(int argc, char *argv[])
{
int numbers1[] = {1,2,3,4};
int numbers2[] = {1,1,3,3};
int result;
result = TestArray(numbers1, 4, 5);
if (result == 1)
{
printf("True");
}
else
{
printf("False");
}
result = TestArray(numbers2, 4, 5);
if (result == 1)
{
printf("True\n");
}
else
{
printf("False");
}
return 0;
}
The output is:
True
False
according to your example
Beginners practice..
int arr[3] = {1,2,3}; //array has 3 numbers
int i,j,x,k;
int res = 0;
scanf("%d",&x);
for(i=0; i< size; i++){
j = i+1;
if(j >= size){
j = 0;
}
k = arr[i] + arr[j];
if(k == x){
res = 1;
break;
}
}
if(res == 1)
printf("True\n");
else
printf("false\n");
How about this:
int i;
int j;
int x;
int [size] TheArray;
printf("Enter value of x: ");
scanf("%d", &x);
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
if(TheArray[j]+TheArray[i] == x)
{
printf("true");
break;
}
else printf("false");
}
}
You need to include the array in your code, he is the main actor in your problem.