Sum of Arrays and Pointers with Functions - c

I have 2 arrays. I read them trough a function. Then I sum them trough another function and print the sum array trough another function. I have to use pointers all the time. Problem is, it prints the sum of the last two elements of the array as the whole sum array. How can I fix this?
#include<stdio.h>
void read(int *pdato);
void print(int *pdato);
void sum(int *pdato1,int *pdato2, int *pdato);
int main(){
int A[5],B[5],C[5],i;
printf("Data for first array:\n");
read(A);
printf("Data for the second array\n");
read(B);
sum(A,B,C);
printf("Result:\n");
print(C);
return 0;
}
void read(int *pdato){
int i;
for(i=0;i<5;i++){
printf("[%d]:",i);
scanf("%d",pdato);
}
}
void sum(int *A,int *B, int *C){
int i;
for(i=0;i<5;i++){
*(C+i)=*(A+i)+*(B+i);
}
}
void print(int *pdato){
int i;
for(i=0;i<5;i++){
printf("[%d]:%d\n",i,*pdato);
}
}

Should be
printf("[%d]:%d\n",i,pdato[i]);
and
scanf("%d",&pdato[i]);

Building off of #Massey101, here is the answer without using array notation:
Should be
printf("[%d]:%d\n",i,*(pdato + i));
and
scanf("%d",pdato + i);

Another solution is below. Increment pointer after every data read to point to correct memory location to store inputs.
for(i=0;i<5;i++) {
scanf("%d",pdato);
pdato++;
}
Increment pointer while printing results, so that it will fetch results from correct memory location as show below
for(i=0;i<5;i++) {
printf("[%d]:%d\n",i,*pdato);
pdato++;
}

Related

Sorting an array in ascending order using pointers in C

I am writing a program that creates an array of random numbers from 1 to 100 and sorts them in ascending order. Below is working code that does this, but I need to modify it so that the "swap" function makes use of pointers. The call for the swap function should look like this: swap(???,???) where the two inputs are pointers. What is the best way to accomplish this?
#include<stdio.h>
#include<math.h>
int main()
{
void fillArray(int sizeArray, int array[sizeArray]);
void printArray(int sizeArray, int array[sizeArray]);
void sortArray(int sizeArray, int array[sizeArray]);
int sizeArray;
printf("\nSize of the array? ");
scanf("%d", &sizeArray);
int array[sizeArray];
fillArray(sizeArray,array);
sortArray(sizeArray, array);
printArray(sizeArray, array);
}
void fillArray(int sizeArray, int array[sizeArray])
{
int increment;
for(increment=0; increment<sizeArray; increment++)
{
array[increment]=rand()%101;
}
}
void sortArray(int sizeArray, int array[sizeArray])
{
void swap(int increment2, int increment, int array[]);
int increment, increment2, temp;
for (increment=0; increment < sizeArray ; increment++)
{
for (increment2=increment+1; increment2 < sizeArray; increment2++)
{
swap(increment2, increment, array);
}
}
}
void swap(int increment2, int increment, int array[])
{
int temp;
if (array[increment2] < array[increment])
{
temp=array[increment];
array[increment]=array[increment2];
array[increment2]=temp;
}
}
void printArray(int sizeArray, int array[sizeArray])
{
int increment=0;
printf("\nHere's the sorted array:\n");
while(increment<21)
{
printf("\n array[%d] is %d", increment, array[increment]);
increment++;
}
}
The output should look like this:
output
Define your swap function as below:
void swap(int *increment2, int* increment)
Modify your for loop where you call the swap function:
for (increment=0; increment < sizeArray ; increment++)
{
for (increment2=increment+1; increment2 < sizeArray; increment2++)
{
swap(array[increment2], array[increment]);
}
}
Then, modify your swap function:
void swap(int *increment2, int* increment)
{
int temp;
if (increment2 < increment)
{
temp= *increment2;
*increment2=*increment;
*increment2=temp;
}
}
You need to fix your function call for the parameters to be with pointers.
void swap(int *increment2, int* increment)
Then in your swap function you need
You will need to deference the integer*.
Example
int n1;
int* x = 100
n1 = *x;
You may need to
deference in the future example
Your function accepts pointers
void swap(int *increment2, int* increment)
If you have integers or another data type to reference them, refer to their address, you can perform & for referencing.
int i = 5;
int* x;
x = &i;
x is now an integer pointer to the address of i.
Your calling code needs to pass the address of the integers to compare and swap. Either of the following forms is acceptable, and they are equivalent.
swap(array+increment2, array+increment);
swap(&array[increment2], &array[increment]);
The first form takes the address of the first element (array) and adds the index (increment2) to get the address of the correct element.
The second version is more straightforward, perhaps. It uses the & address-of operator to take the address of array[increment2], which is the desired integer.
Your swap function need to be defined as follows:
void swap(int** p2, int** p1)
{
int temp;
if (*p2 < *p1)
{
temp=*p1;
*p1=*p2;
*p2=temp;
}
}
Note how the pointers are dereferenced with the * operator to get the integer values for comparison (and storage in temp).

passing 2d array to function with in c

Is there any way to pass 2D array to a function as function(arr,m,n)
and the function defenition as void function(int **p,int m,int n)
ie, Without explicitly specifying array size ??
Let us C has a good explanation about how to pass two D array as parameter.
I usually use these two ways for passing 2D array as parameter. But you need to specify the size explicitly.
void display1(int q[][4],int row,int col){
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%d",q[i][j]);
printf("\n");
}
}
void display2(int (*q)[4],int row,int col){
int i,j;
int *p;
for(i=0;i<row;i++)
{
p=q+i;
for(j=0;j<col;j++)
printf("%d",*(p+j));
printf("\n");
}
}
int main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,0,1,6};
display1(a,3,4);
display2(a,3,4);
}

Function which receives a 1 d array and print its value there?

I wanted to write a function which can receive a 1-D array and print its value there.Also wanted to know how 2-D array can be received by a function and print its value there.
In C you pass arrays by pointers, and usually a second parameter, which contains its length.
For Example: void printArray(char * arrayStart, int length) (for a char array)
and I assume you know how to write a simple for-loop to iterate over all elements of your array and print them. For 2D Arrays you would use char ** arrayStartinstead.
(When calling the function you pass the array in the following fashion:
char myArray[] = "some Text"
printArray(myArray, 9);
)
sample code here:
#include<stdio.h>
void print_1D(int *arr,int m)
{
int i;
for(i=0;i<m;i++)
printf("%d ",arr[i]);
putchar('\n');
}
void print_2D(int *arr[num],int m,int n) //<---observe here
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",arr[i][j]);
putchar('\n');
}
}
int main()
{
int oneD[anySize1] = {2,5,67,23,32,....};
int twoD[anySize2][num] = { {23,17,..},{....},{....},....}; //<---and here
int m = anySize1,n = anySize2;
print_1D(oneD,m);
print_2D(twoD,m,n);
return 0;
}
if 2d is array is declared like this
int arr2D[10][20];
then function declaration must be,
void print_2D(int *arr[20],int m,int n)
or
void print_2D(int arr[][20],int m,int n)

Accessing an array present in main in a function

I have this code:
#include <stdio.h>
void sample(int b[3])
{
//access the elements present in a[counter].
for(int i=0;i<3;i++)
printf("elements of a array are%d\n",b[i]);
}
int main()
{
int count =3;
int a[count];
int i;
for(i=0;i<count;i++)
{
a[i]=4;
}
for(i=0;i<count;i++)
{
printf("array has %d\n",a[i]);
}
sample(//pass the array a[count]);
}
I want to access the array declared in this main function in a user defined function outside main() by passing it as parameter of this function. How can I do this?
The function expecting it usually has to know where the array is and the size of it. To do that, you'd pass a pointer to the first element of the array.
Your sample function could look like
void sample(int *b, size_t count) {
for(int i = 0; i < count; i++) {
printf("elements of a array are%d\n",b[i]);
}
}
You can 'pass' the array by passing a pointer to its first element and of course, also pass the length of the array.
sample(a, count);
You could also simplify this by omitting the count parameter if you can be sure the array will be at least 3 element long.
sample(a); //pass beginning address of array is same as sample(&a[0]);
Function declaration
void sample(int b[]);
Function definition
void sample(int b[]) // void sample(int *b)
{
//access the elements present in a[counter].
//You can access array elements Here with the help of b[0],b[1],b[2]
//any changes made to array b will reflect in array a
//if you want to take SIZE into consideration either define as macro or else declare and define function with another parameter int size_array and From main pass size also
}
pass the parameter as sample(a);
However this code will not work. You cannot use a variable to pass as size of array.
#include<stdio.h>
#define SIZE 3
void sample(int b[]) {
//access the elements present in a[counter] .
for(int i=0;i<3;i++){
printf("elements of a array are%d\n",b[i]);
}
}
int main() {
int a[SIZE];
int i;
for(i=0;i<SIZE;i++){
a[i]=4;
}
for(i=0;i<SIZE;i++){
printf("array has %d\n",a[i]);
}
sample(a);
}
Arrays are always passed as reference. You need to pass address of array to actual parameters and accept it using pointer in formal parameter. Below code should work for you.
void sample(int *b) //pointer will store address of array.
{
int i;
for(i=0;i<3;i++)
printf("elements of a array are%d\n",b[i]);
}
int main()
{
int count =3;
int a[count];
int i;
for(i=0;i<count;i++)
{
a[i]=4;
}
for(i=0;i<count;i++)
{
printf("array has %d\n",a[i]);
}
sample(a); //Name of array is address to 1st element of the array.
}
To pass a complete array to a function you need to pass its base address i.e.&a[0] and its length. You can use the following code:
#include<stdio.h>
#include<conio.h>
void sample(int *m,int n)
{
int j;
printf("\nElements of array are:");
for(j=0;j<n;j++)
printf("\n%d",*m);
}
int main()
{
int a[3];
int i;
for(i=0;i<3;i++);
{
a[i]=4;
}
printf("\nArray has:");
for(i=0;i<3;i++)
{
printf("\n%d",a[i]);
}
sample(&a[0],3)
getch();
return 0;
}

removing duplicate values from an array in C

I am trying to create a program in C that removes duplicate values in an integer array. My strategy is to first sort the array via a selectionsort function, and then call a function removedup that removes any consecutive, duplicate values in the array.
My code:
#include <stdio.h>
#include "simpio.h"
#define n 10
void GetArray(int a[]);
void SelectionSort(int a[]);
int FindMax(int a[], int high);
void swap(int a[], int p1, int p2);
int removedup(int a[]);
void printArray(int a[]);
main()
{
int a[n];
GetArray(a);
SelectionSort(a);
printf("The original, sorted array is\n");
printArray(a);
printf("The array with removed duplicates \n");
printArray(removedup(a));
getchar();
}
void GetArray(int a[])
{
int i;
for(i=0;i<n;i++)
{
printf("Enter integer# %d", i+1);
a[i]=GetInteger();
}
}
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,n-i-1);
swap(a,max,n-i-1);
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=0;i<high;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
void swap(int a[], int p1, int p2)
{
int temp;
temp=a[p2];
a[p2]=a[p1];
a[p1]=temp;
}
int removedup(int a[])
{
int i, count, OutArray[count], j;
count=0;
for(i=0;i<n-1;i++)
{
if(a[i]==a[i+1])
{
a[i+1]=a[i+2];
count++;
}
}
count++;
for(j=0;j<count;j++)
{
OutArray[i]=a[i];
}
return OutArray;
}
I have two questions:
1) How do I fix the error the compiler in giving me in the main body when calling removedup inside the printarray function, saying "invalid conversion from int to int*"? (line 22)
2) How do I accurately define the size of OutArray[] in the removedup function? Currently I have it defined as the size variable, but the value of this variable isn't accurately defined until after the declaration of OutArray.
Notice your prototypes ...
int removedup(int a[]);
void printArray(int a[]);
And also notice you're calling printArray() with the result of removedup().
printArray(removedup(a));
The result of removedup() is an int; printarray() requires a int[].
int and int[] are not compatible.
I suggest you remove duplicates and print array in two distinct statements.
You should be able to fix the compiling problems after reading comp.lang-c FAQ on arrays and pointers.
After you get your array sorted, you can use the following function to remove the duplicates:
int dedup(int arr[], int size) {
int curr = 0, next = 0;
while (next < size) {
while (next < size && arr[next] == arr[curr])
next++;
if (next < size)
arr[++curr] = arr[next++];
}
return size ? curr+1 : 0;
}
It takes two arguments, the array and its size. The duplicates are removed in-place, which means that the array is modified, without allocating a new array to store the unique elements.
Remember that the dedup function expects the elements to be sorted! I've noticed you are using your own implementation of selection sort, which makes me think this is homework. In that case, I feel a little reluctant on giving you a complete solution, although understanding it should be a good exercise anyway.
EDIT: I should've explained the last line of code.
return size ? curr+1 : 0; is equivalent to:
if (size)
return curr+1;
else
return 0;
Just a shorter way of saying the same thing.

Resources