I got a problem in generating an array of integers. the program fills hundreds of cells of the array with numbers like -32429173 instead of 3 cells with numbers from 0 to 3 (for example). Maybe the problem is in the wrong way of allocating memory? Here is the wrong part of the code. Thx for the help in advance.
int* generate()
{
int maxnumb;
int i;
scanf_s("%d",&size); //size of an array
scanf_s("%d",&maxnumb); //asks for maxnumb to fill the array with random numbers from 0 to maxnumb
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
array[i] = rand() % maxnumb + 1;
return array;
}
Here is the full code
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
int size;
void swap(int* elem1,int* elem2) //swap elements
{
int temp;
temp=*elem1;
*elem1=*elem2;
*elem2=temp;
}
void bublesort(int* array,int size) //bublesort
{
for (int j=1;j<size-1;++j)
{
for (int i=0;i<size-j;++i)
{
if ((array[i])>(array[i+1]))
swap(&array[i],&array[i+1]);
}
}
}
int* enterHand() //handle entering
{
int i;
scanf_s("%d",&size);
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
{
scanf_s("%d",&array[i]);
}
return array;
}
int* enterFile() //entering from the file
{
int i;
int singlenumb;
FILE* foo;
errno_t err;
err=fopen_s(&foo,"input.txt","r");
if( err == 0 )
{
printf( "The file 'input.txt' was opened\n" );
}
else
{
printf( "The file 'input.txt' was not opened\n" );
}
while (!feof(foo))
{
fscanf_s(foo, "%d", &singlenumb);
size++;
}
size-=1;
int* array=(int*)calloc(size,sizeof(int));
rewind(foo);
i=0;
while (i!=size)
{
fscanf_s(foo, "%d", &array[i]);
i++;
}
fclose(foo);
return array;
}
int* generate()
{
int maxnumb;
int i;
scanf_s("%d",&size); //size of an array
scanf_s("%d",&maxnumb); //asks for maxnumb to fill the array with random numbers from 0 to maxnumb
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
array[i] = rand() % maxnumb + 1;
return array;
}
void putsFile(int* array, int size)
{
int i=0;
int k;
FILE* fooo;
fopen_s(&fooo,"output.txt","w");
while (i!=size)
{
for (k=0; k<10; k++)
{
fprintf(fooo,"%d ", array[i]);
i++;
}
fprintf(fooo,"\n");
}
fclose(fooo);
}
void printArray(int* array, int size)
{
int i=0;
int k;
while (i!=size)
{
for (k=0; k<10; k++)
{
printf("%d ", array[i]);
i++;
}
printf("\n");
}
}
int main()
{
int choice;
int* pntr;
printf("choose a type of filling an array\n1 = handle filling\n2 = filling from the file\n3 = generating\nenter the number...\n");
scanf("%d", &choice);
switch (choice)
{
case 1: {pntr=enterHand();} break;
case 2: {pntr=enterFile();} break;
case 3: {pntr=generate();} break;
default: {pntr=NULL;}
}
bublesort(pntr,size);
printf("choose a type of typing an array\n1 = console\n2 = file\nenter the number...\n");
scanf("%d", choice);
switch (choice)
{
case 1: {printArray(pntr, size);} break;
case 2: {putsFile(pntr, size);} break;
default: {printf("you entered the wrong number");}
}
return 0;
}
I think you should initialize your maxnumb
First, here is a simpler approach for filling an array.
int randomGenerator(int min, int max);
int main(void)
{
int array[100]//or any size
for(i=0;i<sizeof(array)/sizeof(array[0]);i++)
{
array[i]=randomGenerator(1,3);//will issue only 1, 2 or three (as you requested)
} //change min and max for wider range
return 0;
}
int randomGenerator(int min, int max) //set the range of desired numbers in array
{
int random=0, trying=0;
trying = 1;
while(trying)
{
srand(clock());
random = (rand()/32767.0)*(max+1);
(random >= min) ? (trying = 0) : (trying = 1);
}
return random;
}
There are also some things you can do to make this non-repeating, i.e. so you won't get two Ace of Spades. But for now, you have much bigger issues...
Your code, as is has too many issues to build. If you post a small, buildable section, with the specific problem, it can be better addressed.
The printArray() and putsFile() may print outside array size.
int* enterFile() does not set size to 0 before determining number of int in the file, thus using a potentially unexpected non-zero size.
[Edit] Well size is implicitly set to 0 being in the global uninitialized space. Still, recommend explicitly setting to 0 in enterFile().
#if 0
// The value of size is dependent on program history or uninitialized.
while (!feof(foo)) {
fscanf_s(foo, "%d", &singlenumb);
size++;
}
size-=1;
#else
size = 0; // Reset size to 0
while (1 == fscanf_s(foo, "%d", &singlenumb)) {
size++;
}
#endif
Suggest:
void printArray(int* array, int size) {
// Also in void putsFile(int* array, int size)
int i=0;
while (i < size) {
int k;
for (k=0; k<10; k++) {
printf("%d ", array[i]);
i++;
// Add
if (i >= size) break;
}
printf("\n");
}
}
Related
This is a piece of code to add the same number multiple times to an empty array but when I am printing the now non empty array, I am getting some other values:
#include<stdio.h>
#include<stdlib.h>
void sort_0(int arr[100], int i, int n){
int final_array[100], c=0;
// Count the number of '0' in the array
for(i=0;i<n;i++){
if(arr[i] == 0){
c++;
}
}
// Add the c number of '0' to the final_array
for(i=0;i<c;i++){
scanf("%d",final_array[i]);
}
for(i=0;i<c;i++){
printf("%d ", final_array[i]);
}
}
int main(){
int arr[100], i, n;
// Entering the size of the array
scanf("%d", &n);
// Entering n elements into the array
for(i=0;i<n;i++){
scanf("%d", &arr[i]);
}
sort_0(arr,i,n);
return 0;
}
In the above code, the number of times 0 appears in the array is counted. Then the count is taken as the range and 0 is adding to the empty array final_array count times.
If c = 5, the final_array = {0,0,0,0,0}
Expected Output:
arr = {0,1,4,3,0}
Output = 2
I am not getting any output
Since you don't know how much 0 you'll need to add to your array_final I figured out that a better solution could be to create that array after you have the number of 0 of the first array. Also, I see no reason why you were passsing i to the function since you can simply define it in the function itself.
void sort_0(int arr[10], int n, int* c){
int i;
for(i=0;i<n;i++){
if(arr[i] == 0){
(*c)+= 1;
}
}
}
int main (void) {
int size;
printf("Enter array size: ");
scanf("%d", &size);
int arr[size];
for (int i=0;i<size;i++) {
scanf("%d",&arr[i]);
}
int c = 0;
sort_0(arr, size, &c);
printf("C is: %d\n",c);
int* final_array;
if ((final_array=malloc(c * sizeof(int)))==NULL) // should always check malloc errors
{
perror("malloc");
return -1;
}
for (int i=0;i<c;i++) {
final_array[i]= 0;
}
printf("{");
for (int i=0;i<c-1;i++) {
printf("%d,", final_array[i]);
}
printf("%d}\n",final_array[c-1]);
return 0;
}
I have a problem with my code, it doesn't print the result I expect. This code allows the user to enter as many numbers as he wishes and then print the most repeated one
Here it is:
#include <stdio.h>
void reading_numbers(int array[]){
int i = 0;
int Max = 0;
printf("How much long the array will be?\n");
scanf("%d", &Max);
while (i < Max) {
printf("Insert the numbers\n");
scanf("%d", &array[i]);
i++;
}
}
void most_present_number(int array[], int Max){
int i = 0;
reading_numbers(array);
int current_number = array[i];
int current_number_count = 0;
int most_present_one = 0;
int most_present_one_counter = 0;
while (i < Max) {
if (array[i] == current_number) {
current_number_count++;
i++;
} else {
if (current_number_count > most_present_one_counter){
most_present_one = current_number;
most_present_one_counter = current_number_count;
}
current_number_count = 1;
}
}
printf("This is the most present number %d it is repeated %d times\n", most_present_one,
most_present_one_counter);
}
int main() {
int Max = 0;
int array[Max];
most_present_number(array, Max);
return 0;
}
The problem for me is when I call the function, but I don't know how to fix it
I should have written as a premise but I'm a bit new to C so probably there are some things in this code that don't make sense
I make a procedure to find the result ,int main() must have the size of array (mistake logic),because the procedure take the parameters of the main function (int main ())
Here is my code:
#include<stdio.h>
void most_present_number(int Max,int T[Max])
{
int i = 0;
while (i < Max)
{
printf("Insert the numbers :");
scanf("%d", &T[i]);
i++;
}
int k=0,cpt1=0,cpt=0;
for(int i=0;i<Max;i++)
{
cpt=0;
for(int j=i+1;j<Max;j++)
{
if(T[i]==T[j])
{
cpt++;
}
}
if(cpt>=cpt1)
{
cpt1=cpt;
k=T[i];
}
}
printf("This is the most present number %d it is repeated %d times\n",k,cpt1+1);
}
int main()
{
int Max = 0;
do
{
printf("How much long the array will be?\n");
scanf("%d", &Max);
}while(Max<1);
int T[Max];
most_present_number(Max,T);
}
the following proposed code:
cleanly compiles
performs the desired functionality
only includes header files those contents are actually used
and now the proposed code:
#include <stdio.h>
void reading_numbers( int Max, int array[ Max ][2])
{
for( int i = 0; i < Max; i++ )
{
printf("Insert the numbers\n");
scanf("%d", &array[i][0]);
array[i][1] = 0;
}
}
void most_present_number( int Max, int array[ Max ][2] )
{
for( int i=0; i < Max; i++ )
{
for( int j=i; j<Max; j++ )
{
if ( array[i][0] == array[j][0] )
{
array[i][1]++;
}
}
}
int most_present_one = array[0][0];
int most_present_one_counter = array[0][1];
for( int i=1; i<Max; i++ )
{
if( most_present_one_counter < array[i][1] )
{
most_present_one = array[i][0];
most_present_one_counter = array[i][1];
}
}
printf("This is the most present number %d it is repeated %d times\n",
most_present_one,
most_present_one_counter);
}
int main( void )
{
int Max = 0;
printf("How much long the array will be?\n");
scanf("%d", &Max);
int array[Max][2]; // uses variable length array feature of C
reading_numbers( Max, array );
most_present_number( Max, array );
return 0;
}
a typical run of the code:
How much long the array will be?
4
Insert the numbers
1
Insert the numbers
2
Insert the numbers
3
Insert the numbers
2
This is the most present number 2 it is repeated 2 times
Ok I need to write two functions iterative and recursive to count negative elements in an array and then I need to build main. I was only able to write the recursive function but I cannot call it from main, it is an error somewhere. Can someone help me out solve it and help me with the iterative method?
#include <stdio.h>
main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(array, size)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
A working piece of code is this.You really need to take a look at pointers and the way they work.
Here you can see that I have a pointer ->pointing-< at the start of the array , so by passing the starting address of the array , and the length of the array , your functions knows what it is needed to be done.
#include <stdio.h>
int numero(int* array, int size);
int* recursive_count(int* array, int size , int* counter );
int main()
{
int vektor[100];
int* vekt_ptr = &vektor[0];
int i, madhesia;
int counter;
counter=0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
//int ret = numero(vekt_ptr, madhesia);
recursive_count(vekt_ptr, madhesia , &counter );
int ret = counter;
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array, int size)
{
int count = 0;
int j;
for (j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
int* recursive_count(int* array, int size , int* counter )
{
size--;
if(array[size] < 0 )
{
(*counter)++;
}
if(size==0)
{
return NULL;
}
return recursive_count(array++, size , counter );
}
Let's assume that you want to create dynamically an array of X length.
The compiler is going to have some memory for your array , depending on the length.
You initialize your array , lets say [2][45][1][-5][99]
When you call the function you have to pass where this is stored in memory.
int* vekt_ptr = &vektor[0]; -s going to give as something like 0x56c2e0.
This number is the address of your array , which is the address of the starting point of the array.This is equal with the address of first byte.
So when your function starts , it knows where your array starts and how long it is.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
Any function used in a program shall be declared before its usage.
This function declaration of the function definition
int numero(array, size)
{
// ...
}
is invalid because the types of the parameters array and size are undefined.
For the size of an array and for the count of elements it is better to use an unsigned integer type like for example size_t or at least unsigned int.
The program can look the following way
#include <stdio.h>
#define N 100
size_t iterative_numero( const int array[], size_t size );
size_t recursive_numero( const int array[], size_t size );
int main( void )
{
int vektor[N];
size_t madhesia = 0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%zu", &madhesia);
if ( N < madhesia ) madhesia = N;
/* Input array elements */
printf("Elementet: ");
for ( size_t i = 0; i < madhesia; i++ )
{
scanf( "%d", &vektor[i] );
}
size_t ret = iterative_numero(vektor, madhesia );
printf("\nTotal negative elements in array = %zu\n", ret);
ret = recursive_numero(vektor, madhesia );
printf("Total negative elements in array = %zu\n", ret);
return 0;
}
size_t iterative_numero( const int array[], size_t size )
{
size_t count = 0;
for ( size_t i = 0; i < size; i++)
{
if ( array[i] < 0 )
{
count++;
}
}
return count;
}
size_t recursive_numero( const int array[], size_t size )
{
return size == 0 ? 0 : ( array[0] < 0 ) + recursive_numero( array + 1, size - 1 );
}
the program output might look like
Madhesia e vektorit: 10
Elementet: 0 -1 2 -3 4 -5 6 -7 8 -9
Total negative elements in array = 5
Total negative elements in array = 5
First of all what you did is the iterative method, not recursive. Here I have called a recursive function from the main function.
#include <stdio.h>
int main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("\nElementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
printf("\nno of elements:%d",madhesia);
printf("\n");
for (i = 0; i < madhesia; i++)
{
printf("%d", vektor[i]);
}
printf("\n");
i=0;
int ret = numero(vektor,madhesia,0,i);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int array[],int size,int count,int j)
{
if (j<=size-1)
{
if(array[j]<0)
{
count++;
j++;
numero(array,size,count,j);
}
else
{
j++;
numero(array,size,count,j);
}
}
return count;
}
Put function prototype of numero() before main() to be able to call it. Declare function parameters with type:
int numero(int array[], int size);
int main() {
...
#include<stdio.h>
int numero(int *, int); //Function Prototype (1)
int main() //Return Type (2)
{
int vektor[100];
int i, madhesia;
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array,int size) //Parameters Data Type (3)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
Errors:
You have declared the function after "main()" so the program doesn't know that there is a function, so you have to give the function prototype before "main()" so that the program knows there is function ahead.
You missed writing the return type of "main()" which is integer.
In the function declaration you forgot to write the data type of the parameters.
NOTE: The array is always passed by reference so it has to taken in an integer pointer instead of a normal integer.
Some possible implementations:
int iterativeCountNegativeIntegers (int *array, int size)
{
int result = 0;
for (int i = 0; i < size; ++ i)
if (array[i] < 0)
result += 1;
return result;
}
int recursiveCountNegativeIntegers (int *array, int size)
{
if (size == 0)
return 0;
int partial = *array < 0;
return partial + recursiveCountNegativeIntegers(array+1, size-1);
}
The same, condensed:
int iterativeCountNegativeIntegers_1 (int *array, int size)
{
int result = 0;
while (--size >= 0)
result += *array++ < 0;
return result;
}
int recursiveCountNegativeIntegers_1 (int *array, int size)
{
return (size == 0) ? 0
: (*array < 0) + recursiveCountNegativeIntegers_1(array+1, size-1);
}
This is the code i wrote for multiple occurrences in linear search.Can you please help me point out the mistake ? I want the function to store multiple values in the pointer array and then later to print the array
#include <stdio.h>
void linearsearch(int n,int a[n],int x,int count,int *b[count])
{
count=0;
int i;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
b[j]=i;
j++;
}
}
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int x;
scanf("%d",&x);
int count;
int *b[count];
linearsearch(n,a,x,count,b);
for(i=0;i<count;i++)
{
printf("%d",*b[i]);
}
return 0;
}
I think there are several errors.
count must be initialized, like int count = 0;
count variable is not changed after linearsearch function.
b array should allocated dynamically.
suggested patch is:
#include <stdio.h>
void linearsearch(int n,int a[n],int x,int *count,int **b)
{
count=0;
int i;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
*b = realloc(*b, sizeof(int) * (j + 1));
(*b)[j]=i;
j++;
}
}
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int x;
scanf("%d",&x);
int count = 0;
int *b = NULL;
linearsearch(n,a,x,&count,&b);
for(i=0;i<count;i++)
{
printf("%d",b[i]);
}
return 0;
}
Well the ideal way would be to allocate the memory dynamically based of the number of x found. But well let's look at the errors first. Maybe after this discussion you can write the code.
b[j]=i;
In the called function let's dissect the type of this.
i is of type int. And b[j] is of type int*. Then you assigned them (type mismatched). Then %d expects an int but you passed something of type int*. This is undefined behavior.
Now there was another flaw you had - you passed count and somehow you expect the value you changed in search will be there in main(). C is pass by value and you changed to a local variable. That change is lost when the called function ends.
#include <stdio.h>
#include <stdlib.h>
int* linearsearch(int n,int* a,int x,int* count)
{
*count=0;
if( n <= 0){
fprintf(stderr, "%s\n","Error" );
exit(1);
}
int *t = malloc(sizeof(*t)*n);
if( t == NULL){
perror("Malloc failed");
exit(1);
}
for(int i = 0; i < n; i++)
if(a[i] == x)
t[(*count)++] = i;
int *temp = realloc(t,sizeof(*temp)* (*count));
if( temp == NULL){
perror("Realloc failed");
exit(1);
}
t = temp;
return t;
}
int main(void)
{
int n;
if( scanf("%d",&n)!= 1){
fprintf(stderr, "%s\n", "Error in input");
exit(1);
}
if( n <= 0 ){
fprintf(stderr, "%s\n", "Error in input : must be greater than 0");
exit(1);
}
int a[n];
for(int i=0; i < n; i++)
if(scanf("%d",&a[i])!=1){
fprintf(stderr, "%s\n","Error in input." );
exit(1);
}
int elmt_to_find;
if( scanf("%d",&elmt_to_find)!= 1){
fprintf(stderr, "%s\n", "Error in input : Element to find(must be integer)");
}
int count;
int *b = linearsearch(n,a,elmt_to_find,&count);
for(int i = 0; i < count; i++)
printf("%d ",b[i]);
printf("%s","\n");
free(b);
return 0;
}
If you want to stick with using VLA for b, you can alter your linearsearch to return count only if b is NULL. Then, you can create b as VLA, and pass it back to linearsearch again to be populated.
int count = linearsearch(n, a, x, 0, 0);
int b[count];
linearsearch(n, a, x, count, b);
Then, your function could look like:
int linearsearch(int n,int a[n],int x,int count,int *b[count])
{
int i;
if(count==0)
{
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
}
if (b==0)
{
return count;
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
b[j]=i;
j++;
}
}
return count;
}
This prog is to accept an array of chars n compress them....(aaaabbbcc-->a4b3c2)....my prog is showing error at the point where im equating the addr of the 2d array to 1d array. This is my code:
/* size1 defined as 5 and size2 as 10.... (consts)*/
void compress(char data[SIZE1][SIZE2]);
int main()
{
char data[SIZE1][SIZE2];
printf("Enter a 5x10 matrix of characters:\n");
scanf("%c", &data);
compress(data[SIZE1][SIZE2]);
_getch();
return 0;
}
void compress(char data[SIZE1][SIZE2])
{
int hold[SIZE1*SIZE2];
int cnt = 0;
hold[SIZE1*SIZE2] = data[SIZE1][SIZE2];
for (int i = 0; i < (SIZE1*SIZE2); i++)
{
if (hold[i] == hold[i + 1])
{
cnt++;
continue;
}
else
{
printf("%c%d", hold[i], cnt);
}
}
}
This didn't work so I tried to use pointers:
void compress(char data[SIZE1][SIZE2])
{
int *hold[SIZE1*SIZE2];
int cnt = 0;
hold = data[SIZE1][SIZE2];
for (int i = 0; i < (SIZE1*SIZE2); i++)
{
if (*(hold+i) == *(hold+i+1))
{
cnt++;
}
else
{
printf("%c%d", *(hold+i), cnt);
}
}
}
I thought that the addrs of 2d arrays are stored linearly, hence they can be directly =to that of 1d.But the error says "'=':left operand must be an l-value".Im very new to pointers.Any help or corrections ....pls?
#include <stdio.h>
#define SIZE1 3
#define SIZE2 3
void compress(char data[SIZE1][SIZE2]);
int main(){
char data[SIZE1][SIZE2];
printf("Enter a %dx%d matrix of characters:\n", SIZE1, SIZE2);
for(int i=0;i<SIZE1;++i)
for(int j=0;j<SIZE2;++j)
scanf("%c", &data[i][j]);//aaaabbbcc
compress(data);
(void)getchar();
return 0;
}
void compress(char data[SIZE1][SIZE2]){
char *hold = &data[0][0];
int cnt = 1, size = SIZE1*SIZE2;
for (int i = 0; i < size; i++){
if (i < size -1 && hold[i] == hold[i + 1]){
cnt++;
//continue;
} else {
printf("%c%d", hold[i], cnt);//a4b3c2
cnt = 1;
}
}
}