Hi i was wondering why i can't manage to change the value of the variable "cinter" in this:
int nbobject=7, cinter, i, *inter;
printf("\nHow many elements in array :");
scanf("%d", &cinter);
inter=malloc(nbObject*sizeof(int));
printf("\nEnter the elements :");
for(i=0;i<cinter;i++){
scanf("%d",&inter[i]);
}
qsort(inter, cinter, sizeof *inter, compare);
noDuplicate(inter, cinter);
cinter=noDuplicate(inter,cinter);
for(i=0;i<cinter;i++){
printf("%d", inter[i]);
}
printf("\nNumber of elements in array : ");
printf("%d", cinter);
printf("\nArray elements : ");
for (i=0;i<cinter;i++){
printf("%d ", inter[i]);
}
int noDuplicate( int arr[],int size ){
int i=0, j=0;
for (i = 1; i < size; i++){
if (arr[i] != arr[j]){
j++;
arr[j] = arr[i]; // Move it to the front
}
}
// The new array size..
size = (j + 1);
return size;
}
So what i did is simply sort the array and remove the duplicate. I'd like for the variable "cinter" that's number of elements in the array to be reduced by the number of removed elements so that i can use it later on to know how many relevant elements are in the array but no matter what i always end up with the same number in the end.
Output :
How many elements in array : 6
Enter the elements : 2 1 2 3 5 1
Number of elements in array : 6
Array elements : 1 2 3 5 3 5
EDIT : #Arash here's a code you can run, all i need is to be able to change the value of cinter while i delete duplicates so i can use it later to know exactly how many relevant items are in my array.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
static int compare (void const *a, void const *b){
int const *pa = a;
int const *pb = b;
return *pa - *pb;
}
void main(){
int nbObjets=7, *inter;
size_t cinter;
size_t i, j;
printf("\nHow many elements in the array :");
scanf("%d", &cinter);
inter=malloc(nbObjets*sizeof(int));
printf("\nEnter the elements :");
for(i=0;i<cinter;i++){
scanf("%d",&inter[i]);
}
qsort(inter, cinter, sizeof *inter, compare);
noDuplicate(inter, cinter);
cinter=noDuplicate(inter, cinter);
printf("\nNumber of elements in the array (cinter) : ");
printf("%d", cinter);
printf("\nArray elements : ");
for (i=0;i<cinter;i++){
printf("%d ", inter[i]);
}
}
int noDuplicate( int arr[], size_t size ){
size_t i=0, j=0;
for (i = 1; i < size; i++){
if (arr[i] != arr[j]){
j++;
arr[j] = arr[i]; // Move it to the front
}
}
// The new array size..
size = (j + 1);
return size;
}
EDIT : I got it to work by making the changes that Arash told me to do, thanks for the help guys !
You can use pass by address to fix the problem:
void noDuplicate( int arr[],size_t *size ){
size_t i=0, j=0;
for (i = 1; i < *size; i++){
if (arr[i] != arr[j]) {
j++;
arr[j] = arr[i]; // Move it to the front
}
}
// The new array size..
*size = (j + 1);
}
Then you call it this way:
noDuplicate(inter, &cinter);
You try to return the new size at the end in a void function. And the compiler doesn't complain? Make it int (and, btw, not size_t).
int noDuplicate( int arr[],size_t size )
{
(BTW: Throwing such an unformatted code in a Q is not very helpful.)
Of course in your main() you should assign the return value to cinter or whatever.
cinter = noDuplicate(inter, cinter);
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 am trying to output different elements from two arrays. So if i have an array A: {9, 0, 1} and B is {0, 8, 1}, I need to output an element which included in the first set, but are not included in the second :9 Can not think how I should compare all elements from the first array with the second one.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10],b[10],c,n,i,j;
printf("enter a number: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter a[%d]: ",i+1);
scanf("%d",&a[i]);
}
printf("\n");
for(j=0;j<n;j++){
printf("Enter b[%d]: ",j+1);
scanf("%d",&b[j]);
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]); }
printf("\n");
for (i = 0; i < n; i++) {
printf("%d ", b[i]); }
printf("\n");
return 0;
}
I'd like to show my thoughts but i think it's stupid:
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(a[i]!= b[j]){
c=a[i];
}
}
printf("%d ",c);
}
This can be easily solved using Binary search. Follow the simple steps.
Step 1: Sort the second array.
Step 2: For each element of the first array, binary search it in the second array, if its not present , print it, otherwise dont.
The time complexity is O(m log n), where m is length of first array and n is length of second array.
If you want a more efficient solution, as suggested by #Sumeet Singh, you can sort the second array with qsort, then find similar elements from the first array with bsearch(binary search).
Your current solution is O(N^2) time, which will be very slow with large n, but you can achieve more efficiency with this approach.
Here is some code I wrote up with demonstrates this:
#include <stdio.h>
#include <stdlib.h>
#define NNUMBERS 10
void get_array_input(int array1[], int array2[], size_t *n);
void search_elements(int array1[], int array2[], size_t n);
void print_arrays(int array[], size_t n);
int cmp_func(const void *a, const void *b);
int main(void) {
int array1[NNUMBERS], array2[NNUMBERS];
size_t n;
/* input from user */
get_array_input(array1, array2, &n);
printf("\nFirst array: ");
print_arrays(array1, n);
printf("\nSecond array: ");
print_arrays(array2, n);
/* sorting the second array */
qsort(array2, n, sizeof(*array2), cmp_func);
printf("\nSorted Second array: ");
print_arrays(array2, n);
/* the search begins */
search_elements(array1, array2, n);
return 0;
}
void get_array_input(int array1[], int array2[], size_t *n) {
size_t i;
printf("Enter n: ");
if (scanf("%zu", n) != 1) {
printf("Invalid n value.\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < *n; i++) {
printf("Enter array1[%zu]: ", i);
if (scanf("%d", &array1[i]) != 1) {
printf("Invalud array value.\n");
exit(EXIT_FAILURE);
}
}
for (i = 0; i < *n; i++) {
printf("Enter array2[%zu]: ", i);
if (scanf("%d", &array2[i]) != 1) {
printf("Invalud array value.\n");
exit(EXIT_FAILURE);
}
}
}
void search_elements(int array1[], int array2[], size_t n) {
size_t i;
void *key;
printf("\nElements in first array which are not in second array: ");
for (i = 0; i < n; i++) {
key = bsearch(&array1[i], array2, n, sizeof(*array2), cmp_func);
if (!key) {
printf("%d ", array1[i]); /* not found, so print it */
}
}
printf("\n");
}
void print_arrays(int array[], size_t n) {
size_t i;
for (i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
/* cmp function needed for qsort and bsearch */
/* many ways to write these */
int cmp_func(const void *a, const void *b) {
const int *num1 = (const int *)a;
const int *num2 = (const int *)b;
if (*num1 > *num2) {
return +1;
} else if (*num1 < *num2) {
return -1;
}
return 0;
}
Input:
Enter n: 3
Enter array1[0]: 9
Enter array1[1]: 0
Enter array1[2]: 1
Enter array2[0]: 0
Enter array2[1]: 8
Enter array2[2]: 1
Output:
First array: 9 0 1
Second array: 0 8 1
Sorted Second array: 0 1 8
Elements in first array which are not in second array: 9
You are on the right path. You are taking each value from the first array and comparing to each value in the second.
What you need to do now is to only print a[i] if there isn't any b[j] such that they are the same. The easiest way is to set a flag (say, unique=1). You can give this flag any name you find suitable, but in this case I'm thinking it says that the number a[i] is "unique" to the array a. So in this case you start with the premise that, yes, you won't find a[i] in the arrayb, and then you try to disprove your assumption. If at any time of you search you find an instance of a[i] == b[j], then your premise was wrong, so you set unique=0.
After you have compared this a[i] against all elements in b, you review your flag. And you print the appropriate message depending on whether you found this element in b or not.
Note that this assumes that the same value doesn't appear twice in a.
I have edited your code a little bit and this code gives you desired output:
#include <stdio.h>
int main(void){
int a[10],b[10],c,n,i,j;
int counter=0;
printf("enter a number: ");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter a[%d]: \n",i+1);
scanf("%d",&a[i]);
}
printf("\n");
for(j=0;j<n;j++){
printf("Enter b[%d]: \n",j+1);
scanf("%d",&b[j]);
}
for(i=0;i<n;i++){
counter=0;
for(j=0;j<n;j++){
if(a[i]!=b[j]){
counter++;
}
}
if(counter == n){
printf("%d ",a[i]);
}
}
return 0;
}
Let's explain this code a little bit:
In the last nested for loop, outer loop takes one element from array a. Inner loop gets every element of array b in order to compare it to taken element from array a. If none of the elements of array b is equal to a's taken element, counter will be equal to n(array size). Then we can print this element taken from a(it means there is no match between this taken element and array b's all of elements.
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 was having some problem when trying to do a reverse array using recursion. Here is the function prototype:
void rReverseAr(int ar[ ], int size);
And here is my code:
int main()
{
int ar[10], size, i;
printf("Enter array size: ");
scanf("%d", &size);
printf("Enter %d numbers: ", size);
for (i = 0; i<size; i++)
scanf("%d", &ar[i]);
rReverseAr(ar, size);
printf("rReverseAr(): ");
for (i = 0; i<size; i++)
printf("%d ", ar[i]);
return 0;
}
void rReverseAr(int ar[], int size) {
int start = 0, end = size - 1, temp;
if (start < end) {
temp = ar[start];
ar[start] = ar[end];
ar[end] = temp;
start++;
end--;
rReverseAr(ar, size - 1);
}
}
The expected output should be when user entered 1 2 3 and it supposed to return 3 2 1. However, with these code, the output that I am getting is 2 3 1.
Any ideas?
Your code is almost right. The only problem is that instead of "shrinking" the array from both sides, you shrink it only from the back.
The recursive invocation should look like this:
rReverseAr(ar + 1, size - 2);
You do not need to increment start or decrement end, because their values are not used after modification.
A Simple way :
#include<stdio.h>
using namespace std;
void revs(int i, int n, int arr[])
{
if(i==n)
{
return ;
}
else
{
revs(i+1, n, arr);
printf("%d ", arr[i]);
}
}
int main()
{
int i, n, arr[10];
scanf("%d", &n);
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
revs(0, n, arr);
return 0;
}
Iterate array with recursion in C : link
What you are doing is to exchange values of the 1st and last elements and do the recursion.
Every time you should move your address to the next element as the starter for the next array exchange.
A possible way:
void rReverseAr(int ar[], int size){
int buffer=ar[0];
ar[0] = ar[size-1];
ar[size-1] = buffer;
if ((size!=2)&&(size!=1)) rReverseAr(ar+1,size-2);
}
#include <stdio.h>
int main(){
void sorting(){
int a[4];
a[0]=1;
a[1]=6;
a[2]=15;
a[3]=3;
a[4]=19;
int size = 4;
int t =1;
if (size ==0) return; // ie if you reach to the end stop
int i;
for (i=0;i<size-1;i++){
if(a[i+1] >a[i]) { //if the +1 element is bigger than before it do the swap
int j;
j= a[i+1];
a[i+1]=a[i]; //swap
a[i] = j; //swap
}
}
sorting(*a,size - 1);//recursion
void print_int() {
int i; // Loop counter
for (i = 0; i < 4; i++) {
printf("%d\n", a[i]);
}}
}
It compiles ok but when I try to run the file nothing appears? My intentions were to create an array sort them then display them.
Also, the code where the recursion happened "sorting(*a,size - 1);//"
if I tried to replace *a with a[] an error will happen. Why is that?
the error is "error expected expression before ']' token"!
thank you.
int a[4];
But you access a[4]=19; index 4 that is out of bound. You can access highest index 3.
I think function void sorting() should be defined outside main .Nested functions are GNU extensions in GCC.
Your code has to many problems. Here is a working Array sort:
#include <stdio.h>
void bubble_sort(int *array, int length){
int i,j, k, temp;
for (i = 0 ; i < length-1; i++){
for (k = 0 ; k < length-i-1; k++){
if (array[k] > array[k+1]){
temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
}
}
}
printf("The sorted Array List:\n\n");
for ( j = 0 ; j < length ; j++ ){
printf("%d ", array[j]);
}
}
int main(void){
int array[] = {1,6,15,3,19};
int length = sizeof array / sizeof array[0];
bubble_sort(array, length);
printf("\n");
return 0;
}
You should read about functions declarations and definitions.
About arrays you should know that if you declare:
int array[4];
Your working array is from 0 to 3 and not from 0 to 4.
Take a look at the following:
int main(void){
int array[] = {1,6,15,3,19};
int size = 5;
int i;
for(i=0;i<size;i++){
printf("%d ",array[i]);
}
return 0;
}
I have size=5 and not size=4- like you tried. You should be careful about number of Array elements.
Aside from all the problems spotted by others, you must repeatedly execute the for loop until no more exchanges are made, which is the standad way of bubbling. As you use recursion, it is of course nonsense to declare the array to be sorted (and its size) inside the function called recursively.