Basically this problem asks me to get an input of target_sum and check the integers in the array. If a sum of a pair is equal to target_sum, I need to print it.
I wrote the code like this but it does not work. Where did I make the mistake?
void findPair (int arr[],int size,int target_sum)
{
int i,j;
for (i=0;i<size;i++){
for (j=0;j<size;j++){
if (arr[i] + arr[j] == target_sum)
{
printf("(%d,%d)",arr[i],arr[j]);
}
else
{
printf("No pair.");
}
}
}
}
int main(){
int arr[] = {8,7,2,5,3,1};
int target_sum;
printf("Enter target sum: ");
scanf("%d",target_sum);
findPair(arr,6,target_sum);
}
As #nsilent22 suggested, scanf("%d",target_sum); should be changed into scanf("%d",&target_sum);. Besides that, you could have the second for loop start at j=i+1, making your code overall look like this:
#include <stdio.h>
void findPair (int arr[],int size,int target_sum)
{
int i,j;
for (i=0;i<size;i++)
for (j=i+1;j<size;j++)
if (arr[i] + arr[j] == target_sum)
printf("\n(%d,%d)",arr[i],arr[j]);
else
printf("\nNo pair.");
}
int main(){
int arr[] = {8,7,2,5,3,1};
int target_sum;
printf("Enter target sum: ");
scanf("%d",&target_sum);
findPair(arr,6,target_sum);
}
I'm trying to make function that prints array but the output of it is wrong.
Can someone help me please?
This is the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void printArr(int arr[],int size);
int main()
{
int arr1[3] = { 1,2,3 };
int arr2[5] = { 1,2,3,4,5 };
printf("arr1: \n");
printArr(arr1, 3);
printf("\n\narr2: \n");
printArr(arr2, 5);
printf("\n\n");
return(0);
}
void printArr(int arr[], int size)
{
int i;
for (i = 0; i < size; i++);
{
printf("%d", arr[i]);
}
}
What I get is:
Remove the semi-colon at the of for:
for (i = 0; i < size; i++);
^^^
That makes the for loop run size times and executes the block after that. But by that time, i value is equal to size. This leads to out of bound access, which is undefined behaviour. Clearly, this is not what you intention was.
I'm writing a code for my C programming class and stumbled upon a problem. I'm supposed to write a program which will show as an output Pascal's triangle. I'm to use 1d arrays and in each iteration make the array bigger by using realloc. The trouble is that even though the code compiles and runs when I type eg '7' (as the height of the tringle) in the 7th column there will be trash number. I have no idea why it happens. I'm a beginner in dynamic memory allocation, so please by gentle.
Here's my code:
int i,n;
printf("Give the height:\n");
scanf("%d", &n);
int *tab = (int*)malloc(sizeof(int));
int *tab2, liczba=2;
for(i=0;i<n;i++)
{
tab2=(int *)realloc(tab,i+1);
tab2[i]=&liczba;
print(tab2, i+1);
printf("\n");
}
void print(int *tab, int size)
{
int i;
for(i=0;i<size;i++) printf("%d\t", tab[i]);
}
#include <stdio.h>
#include <stdlib.h>
void print(int *tab, int size);
int main(void){
int i, j, n;
printf("Give the height:\n");
scanf("%d", &n);
int *tab = NULL;
for(i=1;i<=n;++i){
int *temp = realloc(tab, i * sizeof(*tab));
if(temp)
tab = temp;
else {
perror("realloc");
free(tab);
exit(EXIT_FAILURE);
}
tab[i-1] = (i == 1) ? 1 : 0;
for(j=i-1;j>0;--j){
tab[j] += tab[j-1];
}
print(tab, i);
}
free(tab);
return 0;
}
void print(int *tab, int size){
int i;
for(i=0;i<size;i++){
if(i)
putchar('\t');
printf("%d", tab[i]);
}
putchar('\n');
}
How do i make it so that i can use #define variables in my functions? I need to create a program that calls upon functions with this code. Basically my functions at the bottom can change but my main function cannot change from this kind of format, so however i write my functions i have to pass the variable a and variable SIZE through the functions. But current it seems that SIZE is not actually recognized as an int variable.
#include <stdio.h>
#define SIZE 9
int i, position, tmp;
void readArray(int a[]);
void printArray(int a[]);
void sortArray(int a[]);
int main(void)
{
int a[SIZE];
readArray(a);
printArray(a);
sortArray(a);
printf("After sorting:\n");
printArray(a);
return 0;
}
//Functions//
void readArray(int a[]){
printf("Please enter %d integers: ", SIZE);
for (i=0; i<SIZE; i++) {
scanf("%d", &a[i]);
}
}
void printArray(int a[]){
for (i=0;i<SIZE;i++) {
printf("a[%d] = %3d\n", i, a[i]);
}
}
void sortArray(int a[]){
for (i=0; i<SIZE; i++) {
// In each iteration, the i-th largest number becomes the i-th array element.
// Find the largest number in the unsorted portion of the array and
// swap it with the number in the i-th place.
for (position=i; position<SIZE; position++) {
if (a[i] < a[position]) {
tmp = a[i];
a[i] = a[position];
a[position] = tmp;
}
}
}
}
Writing
#define SIZE 9
will tell the preprocessor to replace each appearance of SIZE with 9.
meaning, the following line -
void sortArray(int a[], int SIZE)
will be replaced with -
void sortArray(int a[], int 9)
I assume you understand this is illegal.
You should just delete the second function parameter.
You should rename the C variables to something other than SIZE. This is already used by the preprocessor. Also, watch out because you've written Int instead of int.
i wrote this code in C language on Xcode following the algorithm of mergesort.
The problem is that sometimes i get EXC_BAD_ACCESS and i can't manage where the error is!
The merge algorithm should work (i tried it outside the mergesort function and works!). Thank you for your help and patience!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIM 6
void mymerge (int v[], int i1,int i2, int last); //mergesort core: merge two ordinated arrays in one bigger ordinated array
void mymergesort (int v[], int lower, int upper);//mergesort
void printv (int v[],int lower, int upper);
int main () {
int i;
srand((unsigned int)time(NULL));
int v[DIM];
for (i=0; i<DIM; i++)
v[i]=rand()%15;
printv(v, 0, DIM-1);
getc(stdin);
mymergesort(v, 0, DIM-1);
printv(v, 0, DIM-1);
}
void printv (int v[],int lower, int upper){
int i;
for (i=lower; i<=upper; i++)
printf("%d\t",v[i]);
}
void mymergesort (int v[], int lower, int upper){
int mid=(upper+lower)/2;
if (upper<lower) {
mymergesort(v, lower, mid);
mymergesort(v, mid+1, upper);
mymerge(v,lower,mid+1,upper);
}
}
void mymerge (int v[], int i1,int i2, int last){
int i=i1,j=i2,k=i1,*vout;
vout=(int*)malloc((last-i1+1)*sizeof(int));
while (i<i2 && j<=last) {
if (v[i]<=v[j]) {
vout[k++]=v[i++];
}else {
vout[k++]=v[j++];
}
}
for (;i<i2;i++) vout[k++]=v[i];
for (;j<=last;j++) vout[k++]=v[j];
for (k=i1; k<=last; k++) v[k]=vout[k];
free(vout);
}
EDIT:
thank you very much! but i think think there is another problem, when I try to sort a bigger array (200 elements), the program doesn't work (i get a malloc error: incorrect checksum for freed object - object was probably modified after being freed). But if I run it from the xCode debugger everything works fine
This: vout=(int*)malloc((last-i1)*sizeof(int)); is wrong.
First, the number of elements you want is last-i1+1, not last-i1 - classic off-by-1. This kind of error is one of the reasons why the convention in C code is to make lower bounds inclusive and upper bounds exclusive - less +1 and -1 you need to do, less opportunity to screw up.
The more serious error is that you index vout starting from i1. If you do it this way, you need to allocate last+1 element for vout, and you never use the first i1 (index 0 .. i1-1).
Fix: First, allocate last-i1+1 elements. Second, initialize k to 0 at the beginning, not i1. Third, change the final copy to be
for (k=i1; k<=last; k++) v[k] = vout[k-i1];
You have two problems. The first is that your calculation of the midpoint is incorrect - you use (upper - lower)/ 2, but this is not guaranteed to lie between lower and upper. What you actually want is lower + (upper - lower) / 2. It's also not necessary to do any work if there's only 1 number in the interval to be sorted - so the mymergesort() function should look like:
void mymergesort (int v[], int lower, int upper)
{
if (upper > lower) {
int mid = lower + (upper - lower)/2;
mymergesort(v, lower, mid);
mymergesort(v, mid+1, upper);
mymerge(v,lower,mid+1,upper);
}
}
The second problem is the one in the mymerge() function already pointed out by Fabian Giesen.
#include<stdio.h>
#include<stdlib.h>
void merge(int *a, int n1, int *b, int n2, int *arr)
{
int i=0, j=0, n=0;
while(i<n1 && j<n2)
{
if (a[i] < b[j])
{
arr[n++] = a[i];
i++;
}
else
{
arr[n++] = b[j];
j++;
}
}
while( i < n1)
arr[n++] = a[i++];
while( j < n2)
arr[n++] = b[j++];
}
void merge_sort(int *a, int n)
{
int left[n/2], right[n-n/2],i=0;
if (n<=1)
return ;
while(i<n/2)
left[i] = a[i++];
while(i<n)
right[i - n/2] = a[i++];
merge_sort( left, n/2 );
merge_sort( right, n-n/2);
merge(left, n/2, right, n-n/2, a);
}
void main()
{
int a[] = { 6, 5, 3, 1,9, 8, 7, 2, 4},i;
merge_sort(a,sizeof(a)/sizeof(a[0]));
for(i=0;i<9;i++)
printf("--%d",a[i]);
printf("\n");
}
-- s.k
#include<stdio.h>
#include<conio.h>
#define max 20
/*** function for merging the adjecent subarrays in sorted order ***/
void merge(int A[max],int n,int low,int high, int mid)
{
int i=low,j=mid+1,k,temp;
while((i<=j)&&(j<=high))
{
if(A[i]>A[j]) /** if element of the second half is greater then exchg and shift **/
{
temp=A[j];
for(k=j;k>i;k--) /** shifting the elements **/
{
A[k]=A[k-1];
}
A[i]=temp;
j++;
}
i++;
}
}
/******* iterative function for merge sort ********/
void merge_sort(int A[max],int n,int low,int high)
{
int mid;
if(low<high) /** terminating condition **/
{
mid=(high+low)/2; /** calculating the mid point ***/
merge_sort(A,n,low,mid); /*** recursive call for left half of the array ***/
merge_sort(A,n,mid+1,high); /*** recursive call for right half of the array ***/
merge(A,n,low,high,mid); /** merging the both parts of the array **/
}
}
/******* begening of the main function **********/
int main()
{
int A[max],n,i;
/** reading the inputs fro users **/
printf("\n enter the size of the array\n");
scanf("%d",&n);
printf("\n enter the array \n");
for(i=0;i<n;i++)
{
scanf("%d",&A[i]);
}
/*** calling merge sort ***/
merge_sort(A,n,0,n-1);
/** printing the sorted array **/
for(i=0;i<10;i++)
{
printf("\n\t%d",A[i]);
}
getch();
return 0;
}