#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
void addToArray(int type, int *int_arr, float *flt_arr, int i, ...);
void getNumbers(char , int , int , int *, float *);
void printNumbers(char , int , int *, float *);
int main(int argc, char const *argv[]) {
char type, *type_str, *type_use = malloc(3*sizeof(char)); //type of numbers
int amt_nums; // amount of numbers
float *Farr = malloc(sizeof(*Farr));
int *Iarr = malloc(sizeof(*Iarr));
//get type and number of elements
do {
fpurge(stdin);
printf("Would you like floats(f) or ints(i) (Enter f or i): ");
scanf("%c", &type);
} while( (type!='f') && (type!='i') );
printf("How many numbers would you like to store in the array : ");
scanf("%d", &amt_nums);
//set program up to deal with both types
if (type == 'i'){
Iarr = malloc( (amt_nums * sizeof(*Iarr)) );
type_str = malloc(4*sizeof(char));
strcpy(type_str, "int");
strcpy(type_use, "%d");
}else{
Farr = malloc( (amt_nums * sizeof(*Farr)) );
type_str = malloc(6*sizeof(char));
strcpy(type_str, "float");
strcpy(type_use, "%f");
}
getNumbers(type, 0, amt_nums, Iarr, Farr);
printNumbers(type, amt_nums, Iarr, Farr);
return 0;
}
void printNumbers(char type, int count, int *int_arr, float *flt_arr){
/*
loop through array and print out elements
*/
int i;
if (type == 'f') {
//loop through float numbers
for (i = 0; i < count; i++) {
printf("%f ", flt_arr[i]);
}
}else{
//loop through int numbers
for (i = 0; i < count; i++) {
printf("%d ", int_arr[i]);
}
}
}
void getNumbers(char type, int start, int stop, int *int_arr, float *flt_arr){
int i;
if (type == 'f') {
//get input of type float and add it to array
for (i = start; i < stop; i++) {
float temp;
printf("please enter a float: ");
scanf("%f", &temp);
addToArray(2, int_arr, flt_arr, 2, i, temp);
}
}else{
//get input of type int and add tp array
for (i = start; i < stop; i++) {
int temp;
printf("please enter an int: ");
scanf("%d", &temp);
addToArray(1, int_arr, flt_arr, 2, i, temp);
}
}
}
void addToArray(int type, int *int_arr, float *flt_arr, int i, ...){
//get args
va_list arg_list;
//loop through args
va_start(arg_list, i);
int pos = va_arg(arg_list, int); //get position of array index to be added
if (type == 1) {
int var = va_arg(arg_list, int); // get the variable passed in
int_arr[pos] = var; //set arra[pos] = to variable passed in
}else{
float var = va_arg(arg_list, float);// get the variable passed in
flt_arr[pos] = var;//set arra[pos] = to variable passed in
}
//end args
va_end(arg_list);
}
Comments
0 B
|👍
/👎