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);
}
Related
The program should eliminate any repeating digits and sort the remaining ones in ascending order. I know how to print unique digits but I donĀ“t know how to create a new vector from them that i can later sort.
#include <stdio.h>
void unique(double arr[], int n) {
int i, j, k;
int ctr = 0;
for (i = 0; i < n; i++) {
printf("element - %d : ",i);
scanf("%lf", &arr[i]);
}
for (i = 0; i < n; i++) {
ctr = 0;
for (j = 0, k = n; j < k + 1; j++) {
if (i != j) {
if (arr[i] == arr[j]) {
ctr++;
}
}
}
if (ctr == 0) {
printf("%f ",arr[i]);
}
}
}
int main() {
double arr[100];
int n;
printf("Input the number of elements to be stored in the array: ");
scanf("%d", &n);
unique(arr, n);
}
You can always break a larger problem down into smaller parts.
First create a function that checks if a value already exists in an array.
Then create a function that fills your array with values. Check if the value is in the array before adding it. If it is, you skip it.
Then create a function that sorts an array. Alternatively, qsort is a library function commonly used to sort arrays.
This is far from efficient, but should be fairly easy to understand:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUMS 256
int find(double *arr, size_t length, double val)
{
for (size_t i = 0; i < length; i++)
if (val == arr[i])
return 1;
return 0;
}
size_t fill_with_uniques(double *arr, size_t limit)
{
size_t n = 0;
size_t len = 0;
while (n < limit) {
double value;
printf("Enter value #%zu: ", n + 1);
if (1 != scanf("%lf", &value))
exit(EXIT_FAILURE);
/* if value is not already in the array, add it */
if (!find(arr, len, value))
arr[len++] = value;
n++;
}
return len;
}
int compare(const void *va, const void *vb)
{
double a = *(const double *) va;
double b = *(const double *) vb;
return (a > b) - (a < b);
}
int main(void)
{
double array[MAX_NUMS];
size_t count;
printf("Input the number of elements to be stored in the array: ");
if (1 != scanf("%zu", &count))
exit(EXIT_FAILURE);
if (count > MAX_NUMS)
count = MAX_NUMS;
size_t length = fill_with_uniques(array, count);
/* sort the array */
qsort(array, length, sizeof *array, compare);
/* print the array */
printf("[ ");
for (size_t i = 0; i < length; i++)
printf("%.1f ", array[i]);
printf("]\n");
}
Above we read values from stdin. Alternatively, fill_with_uniques could take two arrays, a source and a destination, and copy values from the former into the latter, only when they would be unique.
Remember to never ignore the return value of scanf, which is the number of successful conversions that occurred (in other words, variables assigned values). Otherwise, if the user enters something unexpected, your program may operate on indeterminate values.
I want to write a function, who gives me the maximum of an array and it should be with call by reference.
Here is my Code:
void max_array (int *array[], int len, int *max){
for (int i = 0; i < len; ++i) {
if (*max < &array[i]){
*max = array[i];
}
}
}
int main() {
void print_array (int array [], int len);
int array[] = {5,3,2,6,4,6,1};
int len = 8;
int max = 0;
max_array(array, len, &max);
printf("Max of Array: %d \n", max);
return 0;
}
Like u see there is something wrong.
My Output is like 158879987 so an address.
You are storing 8 in variable len, however your array has only 7 elements.
In the function, you have specified the first parameter incorrectly. Arrays are always passed by reference, you don't need a * and [], choose one.
void max_array (int *array, int len, int *max){
for (int i = 0; i < len; ++i) {
if (*max < array[i]){
*max = array[i];
}
}
}
remember to alter the value in the len variable.
I have a function that takes array 1 and copies/manipulates it to array 2. Basically what it does is take the user input in array one, lets say (2, 3, 3) and array 2 is stored as (2, 0, 3, 0, 3). I know this works because it worked without implementing a function but sadly I have to have one. I cannot for the life of me figure out how to call the function, I believe I don't need a return since its a void and not returning a value. Below is my code any help would be appreciated.
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main() {
int i = 0;
int n = 0;
int a1[n];
int a2[2*n];
printf("Enter the length of the array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i = 0; i < n; i++){ //adds values to first array
scanf("%d",&a1[i]);
}
insert0(); //call function which is wrong and I cannot get anything to work
for( i = 0; i < n*2; i++){ //prints array 2
printf("%d", a2[i]);
}
void insert0 (int n, int a1[], int a2[]){ //inserts 0's between each number
for(i = 0; i < n; i++){
a2[i+i] = a1[i];
a2[i+i+1] = 0;
}
}
}
Modifying n after declaraing a1 and a2 won't magically increase their size. Declare a1 and a2 after reading the size into n to use variable-length arrays.
You must pass proper arguments to call insert0.
Defining functions inside functions is GCC extension and you shouldn't do that unless it is required.
a2 should have n*2 - 1 elements, not n*2 elements.
After moving it out of main(), i is not declared in insert0, so you have to declare it.
You should check if readings are successful.
Corrected code:
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main() {
int i = 0;
int n = 0;
printf("Enter the length of the array: ");
if(scanf("%d", &n) != 1){
puts("read error for n");
return 1;
}
if(n <= 0){
puts("invalid input");
return 1;
}
int a1[n];
int a2[2*n-1];
printf("Enter the elements of the array: ");
for(i = 0; i < n; i++){ //adds values to first array
if(scanf("%d", &a1[i]) != 1){
printf("read error for a1[%d]\n", i);
return 1;
}
}
insert0(n, a1, a2);
for( i = 0; i < n*2-1; i++){ //prints array 2
printf("%d", a2[i]);
}
}
void insert0 (int n, int a1[], int a2[]){ //inserts 0's between each number
int i;
for(i = 0; i < n; i++){
a2[i+i] = a1[i];
if (i+1 < n){ // don't put 0 after the last element
a2[i+i+1] = 0;
}
}
}
I am writing a function separate from main that reads in an array of structs and prints each array element's struct elements. My problem however is the condition statement for looping though this array to print each element. sizeof(a)/sizeof(a[]) just doesnt work in the function because it is equal to zero within the prototype. Is there something i am missing? I've tried pointer arithmetic and it does not work either.
void printNames( person a[]){
int i;
for(i = 0;i<sizeof(a)/sizeof(a[0]);i++)
printf("Name: %s | Age: %d\n", a[i].name, a[i].age);
}
int main(int argc, char *argv[]){
if (argc == 1 || argc%2 == 0){
printf("Invalid arguments.\n Usage: %s name1 age1 name2 age2 ...", argv[0]);
return 0;
}
printf("You have entered %d person(s) into the program.\n", argc/2);
person people[argc/2];
int i;
for (i = 0; i<argc/2;i++){
strcpy(people[i].name, argv[i*2+1]);
people[i].age = atoi(argv[i*2+2]);
if(people[i].age <= 0){
printf("Invalid age <= 0. Try again.");
return 0;
}
}
a becomes a pointer when passed as parameter to a function, so it cannot figure out the size of the array just from having this pointer, you have to inform the function about its size:
void printNames(person *a, size_t num)
{
int i;
for (i = 0; i < num; i++)
printf("Name: %s | Age: %d\n", a[i].name, a[i].age);
}
Then call printNames from main like this:
printNames(people, sizeof(people)/sizeof(*people));
In C, array parameters are decayed into pointers. So, the expression sizeof(a)/sizeof(a[0]) becomes sizeof(int *)/sizeof(int) which results in 1 (assuming the size of int and int * is 4) and hence the for loop within the printNames() is executed only once regardless of the size of the array.
Therefore, sizeof shouldn't be used to obtain the number of elements in these cases. Instead, we can pass an additional parameter for array size to printNames().
Consider the following C program:
#include<stdio.h>
void func(int array[])
{
int i;
int arraySize = sizeof(array)/sizeof(array[0]); /* arraySize <-- 1<-- 4/4 */
for (i = 0; i < arraySize; i++)
{
array[i] = i;
}
}
int main()
{
int i;
int array[4] = {0, 0 ,0, 0};
func(array);
for(i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
printf(" %d " ,arr[i]);
getchar();
return 0;
}
Output: 0 0 0 0 on a Intel Architecture-32 machine.
So the corrected program is:
#include<stdio.h>
void func(int array[], size_t arraySize)
{
int i;
for (i = 0; i < arraySize; i++)
{
array[i] = i;
}
}
int main()
{
int i;
int array[4] = {0, 0 ,0, 0};
func(array, 4);
for(i = 0; i < sizeof(array)/sizeof(array[0]); i++)
printf(" %d ", array[i]);
getchar();
return 0;
}
I am trying to find the max number in an array. I have created a function and I am using the following code:
int maxValue( int myArray [], int size)
{
int i, maxValue;
maxValue=myArray[0];
//find the largest no
for (i=0;i)
{
if (myArray[i]>maxValue)
maxValue=myArray[i];
}
return maxValue;
}
However I get a syntax error before ) token. What am I doing wrong and am I even doing this right? Any help would be greatly appreciated.
You must pass a valid array with at least one member to this function:
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int
maxValue(int myArray[], size_t size) {
/* enforce the contract */
assert(myArray && size);
size_t i;
int maxValue = myArray[0];
for (i = 1; i < size; ++i) {
if ( myArray[i] > maxValue ) {
maxValue = myArray[i];
}
}
return maxValue;
}
int
main(void) {
int i;
int x[] = {1, 2, 3, 4, 5};
int *y = malloc(10 * sizeof(*y));
srand(time(NULL));
for (i = 0; i < 10; ++i) {
y[i] = rand();
}
printf("Max of x is %d\n", maxValue(x, sizeof(x)/sizeof(x[0])));
printf("Max of y is %d\n", maxValue(y, 10));
return 0;
}
By definition, the size of an array cannot be negative. The appropriate variable for array sizes in C is size_t, use it.
Your for loop can start with the second element of the array, because you have already initialized maxValue with the first element.
A for loop has three parts:
for (initializer; should-continue; next-step)
A for loop is equivalent to:
initializer;
while (should-continue)
{
/* body of the for */
next-step;
}
So the correct code is:
for (i = 0; i < size; ++i)
the paren after the for seems to be missing some contents.
normally it should be something like
for (i=0; i<size; i++)
include:
void main()
{
int a[50], size, v, bigv;
printf("\nEnter %d elements in to the array: ");
for (v=0; v<10; v++)
scanf("%d", &a[v]);
bigv = a[0];
for (v=1; v<10; v++)
{
if(bigv < a[v])
bigv = a[v];
}
printf("\nBiggest: %d", bigv);
getch();
}