Retrieve & Update functions for summing two arrays in a third one - arrays

I am new in c programmaing and I need your help. I have a project in which I am given three arrays A, B, C with pointer value 1..10. I want to a create a C program using the retrieve and update functions, in order to implement the sum of the arrays A:= B + C.
My code so far,
int main(int argc, char** argv) {
int v1[3],v2[3],v3[3];
for(int i = 0 ; i < 3; i++) {
printf("Type a number for v1 :\t");
scanf("%d", &v1[i]);
printf("Type a number for v2 :\t");
scanf("%d", &v2[i]);
// Add here
v3[i] = v1[i] + v2[i];
}
printf("\nResult Arr :\n");
for(int i = 0 ; i < 3; i++)
printf("%d\n", v3[i]);
}
But I seem that I totally miss the retrieve and update functions. According to my notes the retrieve function is equal to retrieve(S, c, i). The variable c get provided the value of component S which corresponds to the value of pointer i. The update(S, c, i) provides the value of variable c to the component of the array S which corresponds to the value of pointer i.
Any ideas on how to pproach this???

you should try both retrieve and update methods first, I'm pretty sure that is your homework and not the code you sent... Anyways, my approach would be, if I understand your homework correctly, that the c in the retrieve function has to be a pointer to set the value of array[i] and the c in the update has to be a value. I'm showing how I would make the retrieve one, and how to call it.
#include <stdio.h>
int retrieve (int * array, int *c, int i){
if (array[i]==NULL){
printf("i is out of range");
return -1; // You could also return max integer for error purposes
}
*c = array[i];
return 0; // Returned with no errors
}
int main(int argc, char** argv) {
int v1[3],v2[3],v3[3];
for(int i = 0 ; i < 3; i++) {
printf("Type a number for v1 :\t");
scanf("%d", &v1[i]);
printf("Type a number for v2 :\t");
scanf("%d", &v2[i]);
// Add here
v3[i] = v1[i] + v2[i];
}
int c=1;
retrieve(v1,&c,0);
printf("%d",c);
printf("\nResult Arr :\n");
for(int i = 0 ; i < 3; i++){
printf("%d\n", v3[i]);
}
}

Related

Issue with using array pointers (C)

I am writing a program that is meant to read in two arrays and find the difference between the two (elements found in set A but not in set B).
The sets are stored using arrays of 1s and 0s (1s for elements that exist and 0s for elements that don't). I have the following code written and can't seem to understand why I am getting these warnings
warning: comparison between pointer and integer [enabled by default]
if(p==1 && q==0)
^
warning: assignment makes pointer from integer without a cast [enabled by default]
set_difference = 1;
I have the following code written. It will not return a value, either.
#define N 10
void find_set_difference(int *set_a, int *set_b, int n, int *set_difference);
int main(void)
{
int i, k;
int n;
printf("Enter the number of elements in set A: \n");
scanf("%d", &n);
int a[n];
printf("Enter the elements in set A: \n");
for(i=0; i<n; i++){
scanf("%d", &a[k]);
a[k] = 1;
}
printf("Enter the number of elements in set B: \n");
scanf("%d", &n);
int b[n];
printf("Enter the elements in set B: \n");
for(i=0; i<n; i++){
scanf("%d", &b[k]);
b[k] = 1;
}
int set_dif[N];
find_set_difference(a, b, N, set_dif);
printf("The difference of set A and set B is: \n");
for(i=0;i<10;i++){
if(set_dif[i]==1)
printf("%d ",i);
}
return 0;
}
void find_set_difference(int *set_a, int *set_b, int n, int *set_difference){
int *p, *q;
for(p=set_a; p<set_a+n; p++){
for(q=set_b; q<set_b+n; q++){
if(p==1 && q==0)
set_difference = 1;
else
set_difference = 0;
}
}
}
Any assistance with formatting and using pointers would be helpful, as I am still new to coding and am having difficulty understanding the concepts.
The following checks the value of the pointers:
if(p==1 && q==0)
You want to check the pointed values.
if(*p==1 && *q==0)
The following sets the value of the pointer:
set_difference = 1;
You want to set the pointed variable.
*set_difference = 1;
This answer only addresses the warnings you asked about. There are a number of other major problems, but I don't want to do your homework for you. Think about how many different variables do you want to set.
You are currently setting one.
You are currently setting it n*n times.
you some problems in your code:
the value of variable k isn't being initialized in the loop as it's used being as an iterator, also a[k] = 1 doesn't make any since as this is an array not hash table, assume if input1 = 1, 2, 3, 4, 5 and input2 = 6, 7, 8, 9, 10, the way you write that line makes that input1 is same as input2 :
for(i=0; i<n; i++){
scanf("%d", &a[k]);
a[k] = 1;
}
so you should do :
for(i=0, k = 0; i<n; i++, k++){
scanf("%d", &a[k]);
}
using the same variable n for 2 different arrays can result in some errors if the user entered different sizes for the 2 different arrays
so use another variable to get the size of the second array instead of n that's being used for the first array
the size of the set_dif in line :
int set_dif[N];
is better to be the size of the smallest array of them, but it wouldn't make any difference if its size is greater than that.
in this line :
if(p==1 && q==0)
you are comparing address which is pointer p with a value which is 1
so instead you should compare the value in that address with value 1, so you should do: if(*p==1 && *q==0)
in this line:
set_difference = 1;
set_difference is a pointer to the array which means it's an address, so you can't do address = Value, instead you should do the:
set_difference[i] = 1;
where i is an iterator
also in the line:
if(*p==1 && *q==0)
you should compare if(*p!=*q) as not to make the problem discussed in point 1
and the array called set_dif should be initialized with ones.
instead of:
printf("%d ",i);
write: printf("%d ",a[i]); , as to achieve what are seeking with this line, you should look for something called hash table
with all that being said, this is the full edited code:
#include <stdio.h>
void find_set_difference(int *set_a, int *set_b, int n, int m, int *set_difference);
int main(void)
{
int i, k = 0;
int n, m;
printf("Enter the number of elements in set A: \n");
scanf(" %d", &n);
int a[n];
printf("Enter the elements in set A: \n");
for(i=0, k = 0; i<n; i++, k++){
scanf(" %d", &a[k]);
}
printf("Enter the number of elements in set B: \n");
scanf("%d", &m);
int b[m];
printf("Enter the elements in set B: \n");
for(i=0, k = 0; i<n; i++, k++){
scanf("%d", &b[k]);
}
int set_dif[n];
for (int j = 0; j < n; ++j) {
set_dif[j] = 1;
}
find_set_difference(a, b, n, m, set_dif);
printf("The difference of set A and set B is: \n");
for(i=0; i< n ;i++){
if(set_dif[i] != 0)
printf("%d \t",a[i]);
}
return 0;
}
void find_set_difference(int *set_a, int *set_b, int n, int m, int *set_difference){
int *p, *q;
int i = 0;
for(p = set_a; p < set_a + n; p++, i++){
for(q = set_b; q< set_b + m ; q++){
if(*p==*q)
set_difference[i] = 0;
}
}
}
and this is some example output:
Enter the number of elements in set A:
5
Enter the elements in set A:
1
3
4
5
6
Enter the number of elements in set B:
5
Enter the elements in set B:
2
3
4
6
8
The difference of set A and set B is:
1 5

summing numbers using pointer arithmetic

I was given an assignment to write a code which takes in numbers as input from the user and provides the sum of it, specifically by the use of pointer arithmetic i.e. no array subscripting a[i] is allowed.
Below is the code that I wrote, which got compiled and even ran. But almost always it gives the sum of the input numbers as 0. I tried to fix it, but to no avail. Thus, I am asking for help, any help is greatly appreciated.
#include<stdio.h>
#define N 5
int sum_array( const int *p, int n)
{
int sum, a[N];
sum = 0;
for(p=&a[0]; p<&a[N]; p++)
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(i,N);
printf("the sum is %d\n", x);
return 0;
}
Beware, you are declaring array int a[N] in both main and sum_array. They are in different scopes, so they are different arrays (and the one from sum_array is never initialized so reading it invokes Undefined Behaviour).
The correct way is to pass the array along with its used length:
Here is a fixed version:
#include<stdio.h>
#define N 5
int sum_array( const int *a, int n) // a points to a array of at least n elements
{
int sum = 0; // initialize at definition time
for(const int *p=a; p<&a[n]; p++) // have the pointer p take all values from a
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
Finally it is mainly a matter of taste, but I was too often burnt for trying to add an instruction in a for loop without braces, so I strongly recommend using always braces for loops:
for(i=a; i<a+N; i++) {
scanf("%d", i);
}
int sum_array( const int *p, int n)
{
int sum = 0, i = 0;
for(i = 0; i < n ; i++)
sum += *(p+i);
return sum;
}
int main(void)
{
int a[N], i = 0, x = 0;
printf("Enter %d Numbers: ", N);
for(i=0; i<N; i++)
scanf("%d", a+i);
// all the input values get scanned as i or the array a
x= sum_array(a,N);
printf("the sum is %d\n", x);
return 0;
}
In x= sum_array(i,N); i is the iterator of your loop so after the loop has finished it points to the first position after the array.
You should pass the original array instead x= sum_array(a,N);
In the sum function you just throw away the passed pointer and replace it with your local a[].
int sum_array( const int *p, int n)
{
int sum = 0;
int *end = &p[n]; // first element after the array.
for(; p<end; p++) // just use p because you don't need the reference to the start of the array
{
sum += *p;
}
return sum;
}
but as you said that array notation is not allowed you can change it as follows
#include "stdio.h"
#define N 5
int sum_array( const int *p, int n)
{
int sum = 0;
const int *end = p+n; // first element after the array.
for(; p<end; p++)
{
sum += *p;
}
return sum;
}
int main()
{
int *a, *i, x;
a = malloc(N * sizeof(*a));
if (a == NULL)
exit(-1);
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
{
scanf("%d", i);
}
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
in general, when programming, the code should be kept as simple as possible while still being complete.
The program criteria shows no need to keep a number after it is applied to the sum of the numbers, So in the proposed code, the input number is only kept long enough to be applied to the sum, then it is discarded.
The following proposed code:
cleanly compiles
performs the desired functionality
is kept very simple
properly checks for; and handles any errors
And now the proposed code:
#include <stdio.h> // scanf(), printf(), fprintf(), stderr
#include <stdlib.h> // exit(), EXIT_FAILURE
#define N 5
int main( void )
{
int num = 0;
int sum = 0;
printf("Enter %d Numbers: ", N);
for(size_t i=0; i<N; i++)
{
if( scanf("%d", &num) != 1 )
{
fprintf( stderr, "failed to read number\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
sum += num;
}
printf( "the sum is %d\n", sum );
return 0;
}

Rand() not generating random variables in C

I've been trying to apply all advices found in this site but none seems to be working.
For the first part of the code I need to fill an array with random numbers (0 or 1) to simulate an epidemic spreading, but the array obtained is not the desired one at all... this is the code I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
int N, BC, t, T, i, v[N];
float b, g, p, r;
/*Variable values initialization*/
printf("Enter infection probability:\n");
scanf("%f", &b);
printf("Enter the number of individuals:\n");
scanf("%d", &N);
printf("Enter the number of time steps:\n");
scanf("%d", &T);
printf("Periodic boundary contitions? (Y:1 / N:0)\n");
scanf("%d", &BC);
/*First set of individuals*/
srand(time(NULL));
for(i = 0; i < N; i++){
v[i] = (rand()/RAND_MAX);
}
/*Check if array properly initialized*/
printf("Initial array:\n" );
for(i = 0; i < N; i++){
printf("%d-", v[i]);
}
The outcome I expected for the array was something like: 1-0-1-1-0-0-0-..., but I always get the following one:
Initial array:
0-0-2-15-0-0-0-0-0-0-
What am I doing wrong?
Thanks a million!
You should declare v[N] after
printf("Enter the number of individuals:\n");
scanf("%d", &N);
otherwise its size will be random since N isn't initialized when the memory allocated for v[] based on N is set.
If you want just 0 or 1 you should use a modulo:
srand(time(NULL));
for(i = 0; i < N; i++){
v[i] = (rand() % 2);
}
all the even values generated by rand will become 0 and all the odd values will become 1

Sum of numbers using 2 functions

Just learning C and I'm trying to understand how I get the sum of numbers using 2 functions but the results is incorrect.
I'm trying to ask the user for 10 numbers which are stored in an array in function main. The sum is then calculated in a separate function and then displayed in main.
Here is my original code without multiple functions that works:
int main()
{
int n[10];
int index;
int sum_n = 0;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
sum_n += n[index];
}
printf("The Sum of numbers is %d\n", sum_n);
}
Here is me trying to convert it to functions but the sum isn't working out:
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
}
if (n[index] = 10){
//sum_n += n[index];
printf("The Sum of numbers is %d\n",calculations(n[index]));
}
&
int calculations (int num){
int sum_n = 0;
sum_n += num;
return sum_n;
}
When I run the second program using functions for numbers 1 to 10 I'm getting:
I'm either doing something blatantly wrong or not understanding what I'm doing at all.
every time you call a function the variables declared within a function are reset.
in case you want a variable that won't be reset every time you call a function you can simply make it static.
moreover you are passing and argument n[10] but your array stores number from n[0] to n[9] . And if you want sum of all ten numbers then you have to call calculation function for every number or you could just pass whole array. here is modified code.
#include<stdio.h>
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
int ans=0;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d",&n[index]);
ans = calculations(n[index]);
}
printf("The Sum of numbers is %d\n",ans);
}
int calculations (int num){
static int sum_n;
sum_n += num;
return sum_n;
}
First you don't need array for sum in this code, Second always remember to check what returned by scanf.The code is very simple.
first part with main
int main()
{
int n;
int sum=0;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
sum+=n;
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Second using function calculation
int sum=0;
void calculation(int num){
sum+= num;
}
int main()
{
int n;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
calculation(n);
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Your function calculations() simply returns its parameter (0 + num is simply num).
The statement
int sum_n = 0;
in it resets sum_n to 0 every time of calling it.
Move this statement out of it - directly into main() function (and before calling calculations()).
Corrections mentioned in comments below.
int calculations (int *num){ //Should be a pointer or array eg. int num[] as you want to pass an array to this function
int sum_n = 0;
int i;
//Create loop here to iterate over array and sum elements
for(i=0; i<sizeof(num)/sizeof(int); i++)
sum_n+=num[i];
return sum_n;
}
And
if (n[index] = 10){ //This is logically incorrect. This should be if(index==10).
// n[index]=10 will assign 10 to a[10] and if will still pass as if(10) is true but make a note of it. Don't use assignment operator inside if, you need comparison operator `==`
printf("The Sum of numbers is %d\n",calculations(n[index])); //You should call calculations like this -> calculations(n). You should pass whole array not just an element.
}

Sorting an array in C

I'm trying to sort elements in an array from smallest to largest that a user inputs along with the size. This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAXVALUES 20
void sort(int *A[], int n) {
int i, tmp, j;
for (i = 0; i <= (n - 2); i++) {
for (j = (i + 1); j <= (n - 1); j++) {
if (*A[i] > *A[j]) {
tmp = *A[i];
*A[i] = *A[j];
*A[j] = tmp;
}
}
}
return;
}
int main(int argc, char *argv[]) {
int n, A[MAXVALUES], i;
printf("Enter an array and no. of elements in array: ");
scanf("%d%d", &A[MAXVALUES], &n);
sort(A[MAXVALUES], n);
printf("Ordered array is: \n");
for (i = 0; i <= (n - 1); i++) {
printf(" %d", A[i]);
}
return 0;
}
The compiler compiles it without any errors but it stops working after I put in the inputs. I've yet to quite grasp the theory behind arrays and pointers so could someone tell me where in my code I'm going wrong?
scanf("%d%d", &A[MAXVALUES], &n); is the problem
That's not how you read an array.
First you read the n, after that inside a loop you read every element like
scanf("%d", &A[i]); where i is the index from 0 to n
EDIT:
scanf("%d", &n);
int i = 0;
for(i = 0; i < n; i++)
{
scanf("%d", &A[i]);
}
This is what you want.
You can't use scanf() to read in a whole array at once.
This:
scanf("%d%d", &A[MAXVALUES], &n);
Makes no sense; it passes scanf() the address of the element after the last one in A, causing undefined behavior. The sort() call is equally broken.
To read in multiple numbers, use a loop. Also, of course you must read the desired length first, before reading in the numbers themselves.
Firstly I'll tell you a couple of things about your sorting function. What you want, is take an array (which in C is representable by a pointer to the type of elements that are in that array, in your case int) and the array's size(int) (optionally you can take a sorting method as an argument as well, but for simplicity's sake let's consider you want to sort things from lowest to highest). What your function takes is a pointer to an array of integers and an integer (the second argument is very much correct, or in other words it's what we wanted), but the first is a little more tricky. While the sorting function can be wrote to function properly with this argument list, it is awkward and unnecessary. You should only pass either int A[], either int *A. So your function header would be:
void sort1(int *A, int n);
void sort2(int A[], int n);
If you do this however, you have to give up some dereferencing in the function body. In particular I am referring to
if (*A[i] > *A[j]) {
tmp = *A[i];
*A[i] = *A[j];
*A[j] = tmp;
} which should become
if (A[i] > A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
You should check out the operators [] and *(dereference) precedence http://en.cppreference.com/w/c/language/operator_precedence
Now, to adapt to these changes (and further correct some code) your main would look like so:
int main(int argc, char *argv[])
{
int A[MAXVALUES], n;
do{
printf("n="); scanf("%d", &n);
}while(n < 0 || n > 20);
int i;
for(i = 0; i < n; ++i)
scanf("%d", &A[i]); //this will read your array from standard input
sort(A, n); //proper sort call
for(i = 0; i < n; ++i)
printf(" %d", A[i]);
printf("\n"); //add a newline to the output
return 0;
}

Resources