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);
}
Related
I am writing a program to generate all possible permutations of a given series of numbers and then generate all possible binary trees from that permutations so, what I thought is having a program which generates permutations and stores the result to a file and then write further code to read line by line (which has all permutations ) and generate binary trees out of them, so right now I have written half program which generates permutation and it stores the result in file.
#include <stdio.h>
//function to print the array
void printarray(int arr[], int size)
{
FILE *fp;
int i,j;
fp=fopen("result.txt","w");
for(i=0; i<size; i++)
{
// printf("%d\t",arr[i]);
fprintf(fp,"%d\t",arr[i]);
}
printf("\n");
fclose(fp);
}
//function to swap the variables
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
//permutation function
void permutation(int *arr, int start, int end)
{
if(start==end)
{
printarray(arr, end+1);
return;
}
int i;
for(i=start;i<=end;i++)
{
//swapping numbers
swap((arr+i), (arr+start));
//fixing one first digit
//and calling permutation on
//the rest of the digits
permutation(arr, start+1, end);
swap((arr+i), (arr+start));
}
}
int main()
{
//taking input to the array
int size;
printf("Enter the size of array\n");
scanf("%d",&size);
int i;
int arr[size];
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
//calling permutation function
permutation(arr, 0, size-1);
return 0;
}
but the problem here in this program is that this program only stores one permutation and does not stores other permutations in result.txt file, how do I go on storing result this way. Also program does not ends a blank cursor blinking which gives a false impression of infinite while loop.
I had to press Ctrl+c to end the program how to get rid of this?
your fopen("result.txt","w"); truncates file each time opened.
use fopen("result.txt","a"); instead
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define N 10
void print(int *num, int n)
{
FILE *fp;
fp=fopen("result.txt","a");
int i;
for ( i = 0 ; i < n ; i++)
// printf("%d ", num[i]);
fprintf(fp,"%d ",num[i]);
fprintf(fp,"\n");
fclose(fp);
}
int main()
{
int num[N];
int *ptr;
int temp;
int i, n, j;
printf("\nHow many number you want to enter: ");
scanf("%d", &n);
printf("\nEnter a list of numbers to see all combinations:\n");
for (i = 0 ; i < n; i++)
scanf("%d", &num[i]);
for (j = 1; j <= n; j++) {
for (i = 0; i < n-1; i++) {
temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
print(num, n);
}
}
return 0;
}
I have been trying to write the Radix sort algorithm in C.
When I run my code with base 10 it works fine for all inputs, however, with base 16 it sorts only the first 10 elements correctly. In addition, for any other base it is not working.
I would like to make an implementation that generalize for any base.
Here is the code a have so far, could you find any issues?
#include <stdio.h>
#include <stdlib.h>
int size=32;
int getMax(int arr[], int n) {
int mx = arr[0];
int i;
for (i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
void countSort(int arr[], int n, int exp, int base) {
int output[n];
int i;
int count[base];
memset(count,0,sizeof count);
for (i=0;i<n;i++)
count[(arr[i]/exp)%base]++;
for (i=1;i<base;i++)
count[i]=count[i]+count[i-1];
for (i=n-1;i>=0;i--) {
output[count[ (arr[i]/exp)%base ]-1]=arr[i];
count[ (arr[i]/exp)%base ]--;
}
for (i=0;i<n;i++)
arr[i]=output[i];
}
void radixsort(int arr[],int n,int base) {
int exp;
int m=getMax(arr,n);
for (exp=1;m/exp>0;exp=exp*10)
countSort(arr,n,exp,base);
}
int main(int argc,char *argv[]) {
int num,i=0,j,n,m;
int *arr,*newarr=NULL;
FILE *fp1;
FILE *fp2;
int base=atoi(argv[1]);
fp1=fopen(argv[2],"r");
if (fp1 == NULL) {
printf("Warning:File does not exists;please enter valid file name");
exit(0);
}
fp2=fopen(argv[3],"w");
if (fp2 == NULL) {
printf("Warning:File does not exists");
exit(0);
}
arr= malloc(sizeof(int)*size);
fprintf(fp2,"before sorting:");
while(fscanf(fp1,"%d",&num)==1) {
if(i<size) {
arr[i]=num;
i++;
fprintf(fp2,"%d ",num);
n=i;
} else {
newarr = malloc(sizeof(int)*2*size);
for(m=0;m<size;m++) {
newarr[m]=arr[m];
}
free(arr);
size=size*2;
arr=&newarr[0];
}
}
radixsort(arr,n,base);
fprintf(fp2,"\nAfter Sorting:");
for (j=0;j<n;j++)
fprintf(fp2,"%d ",arr[j]);
fclose(fp1);
fclose(fp2);
return 0;
}
Looks like for (exp=1;m/exp>0;exp=exp*10)is the problem. I think you need to use base instead of 10.
EDIT: I tried compiling and running this code and was not able to get it to work, even for base 10.
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');
}
The program I"m trying to finish is a program using the bubble sort algorithm. I am not sure what is the problem or in which function the problem is in. The problem is the program does not sort the array in properly. (It also must be arranged in ascending order).
Here is the code:
#include <stdio.h>
#include "simpio.h"
void getArray (int arr[], int size);
void sortArray (int arr[], int size);
void swap (int arr[], int num, int number);
void dispArray (int arr[], int size);
bool checkBigger (int arr[], int num, int number);
main()
{
int size;
printf("Enter number of elements: ");
size=GetInteger();
int arr[size];
getArray(arr, size);
sortArray(arr, size);
dispArray(arr, size);
getchar();
}
void getArray (int arr[], int size)
{
int num;
printf("Please enter the value of the elements: \n");
for(num=0; num<size; num++)
{
arr[num]=GetInteger();
}
}
void sortArray (int arr[], int size)
{
int num, number, d;
for(num=0;num<size-1;num++)
{
for(d=0; d<size-num-1; d++)
{
number=num+1;
checkBigger(arr, num, number);
}
}
}
void swap (int arr[], int num, int number)
{
int tem;
tem=arr[num];
arr[num]=arr[number];
arr[number]=tem;
}
void dispArray (int arr[], int size)
{
int num;
printf("The sorted list is:\n");
for(num=0; num<size; num++)
{
printf("%d\t", arr[num]);
}
}
bool checkBigger (int arr[], int num, int number)
{
if(arr[num]>arr[number])
{
swap(arr, num, number);
}
}
Thank you very much.
void sortArray (int arr[], int size)
{
int num, number, d;
for(num=0;num<size-1;num++)
{
for(d=0; d<size-num-1; d++)
{
number=d+1;
checkBigger(arr, d, number);
}
}
}
pretty sure your problem is with you algorithm, try to simulate your algorithm in pen and paper. it will help your understanding of your code and the algorithm better :)
for your convenience here i am including a bubble sort algorithm i did some while ago
void bubbleSort( int a[], int n)
{
int i,j,temp; // for a={1,2,3,4,5} n is 5
n = n - 1; // bcz otherwise it will get out of index
for(i=0; i<n; i++)
{
for(j=0; j<n-i; j++)
{
if(a[j]>a[j+1])
{
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
}
}
i hope this helps
All I follow from the above examples is an implementation of the exchange sort.
The exchange sort on the outer loop checks each entry in the table against the first element, exchanging when necessary. At then end of the inner loop, the lowest element is in position 1, then it begins with position 2, comparing it to the remaining elements, and doing an exchange. Even if the array was already in order, the sort cannot stop. It has to do a n*(n-1) compares. An array of 50 elements, already sorted will do 50*49 comparisons.
The bubble sort works differently
set a swap flag to zero. Then
slide along the array, comparing position(i) to position(i+1). If a swap takes place, you do the sort again.
here is some pseudo code.
swap = 0
do {
for (i=o;i< no-elements-1;i++) {
if (array[i] > array[i+1])
{
do the exchange
set swap=1
}
/**/
} while (swap == 1);
The above illustrates the bubble sort.
Note. if the data is in order, there is no swap and there is no second loop. The sort algorithm is able to quit early.
if a fifty element array is in order, the sort would have done 50 comparisons and would have stopped.
The exchange sort, which is described earlier would have to do 50*49 or 2450 comparisons.
// BUBBLE SORT.
#include <stdio.h>
#define MAX 20
int main()
{
int arr[MAX];int no;
printf("PLEASE ENTER THE CURRENT SIZE OF THE ARRAY\n");
scanf("%d",&no);
int i;
printf("PLEASE ENTER THE ELEMENTS OF THE ARRAY\n");
for(i=0;i<no;i++)
scanf("%d",&arr[i]); /*reading the elements*/
/* sorting begins*/
int j,k,l;
int temp;
int flag=0;
for(k=0;k<no-1;k++)
{
flag=0;
j=k;
for(i=0;i<no-j-1;i++) /* not going to the part that has been sorted*/
{
if(arr[i]>arr[i+1])
{
flag=1;
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
else
continue;/* not necessary*/
}
if(flag==0) /*implies that the array is alraedy sorted*/
break;
}
printf("THE SORTED LIST:\n\n");
for(i=0;i<no;i++)
printf("%d\n",arr[i]);
}
I'm trying to create a simple(?) selection sort program in C that selects the largest integer of an integer array and places it in the location a[n-1], places the second largest number in a[n-2], etc until the smallest number is placed in a[0]. I've run through the below code on paper and it seems like it should work, but when I compile it I'm getting faulty results. Am I missing something obvious?
/* The program implements selection sort*/
#include <stdio.h>
#include "simpio.h"
#define n 5
void GetArray(int a[]);
void SelectionSort(int a[]);
int FindMax(int a[], int high);
void swap(int a[], int p1, int p2);
void PrintArray(int a[]);
main()
{
int a[n];
GetArray(a);
SelectionSort(a);
PrintArray(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,i);
swap(a,max,(n-1-i));
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=high;i<n;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;
}
void PrintArray(int a[])
{
int i;
for(i=0;i<n;i++)
printf("a[%d]=%d\n", i, a[i]);
}
Change these method to:
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;
}
I actually tested my answer and it works.
Selection sort is process of comparing minimum element from the list and placing from the least index.
Now consider below code snippet.
public void selectionSort(int[] elements) {
for(int i=0;i<elements.length;i++) {
int minPosition = i;
for(int j=i+1;j<elements.length;j++) {
if(elements[minPosition]>elements[j])
minPosition = j;
}
int temp = elements[i];
elements[i] = elements[minPosition];
elements[minPosition] = temp;
}
}
Thanks for reading, let me know feedback to improve from myside
Shouldn't:
max=FindMax(a,i);
swap(a,max,(n-1-i));
Be:
max=FindMax(a,i);
swap(a,max,i);
otherwise, next time through the loop, you'll find the same max value in the top position in the array.
A very basic implementation of selection sort
#include<stdio.h>
main()
{
int i,j,n=7,a[]={1,2,5,3,8,9,5},key;
for(j=1;j<n;j++)
{
key=a[j]; //a[j] is the new element to be added to the sorted
//sequence
i=j-1;
while(i>=0 && key<a[i]) //traverse through the sorted sequence
{a[i+1]=a[i];i--;} //until the place of key is found
a[i+1]=key;
}
for (j=0;j<n;j++)
printf("%d",a[j]);
}
#include<stdio.h>
#include<conio.h>
int removex(int arr[],int small,int n)
{
int i=0;
for(;i<n;i++)
if(arr[i]==small) //searching that no to delete
break;
for(;i<n-1;i++)
arr[i]=arr[i+1]; //delete by overloading no
return n-1;
}
void selectSort(int arr[],int sort[],int n)
{
int j=0,k=0,small;
while(n!=0)
{
small=arr[0];
for(j=0;j<n;j++)
if(arr[j]<small)
small=arr[j]; //finding smallest no
sort[k++]=small;
n=removex(arr,small,n); //removing that from list as we included that no into sorted list
}
}
void main()
{
int arr[10],arr2[10],i,n;
clrscr();
printf("Enter how many elements");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
selectSort(arr,arr2,n);
printf("sorted list is\n");
for(i=0;i<n;i++)
printf("%d\n",arr2[i]);
getch();
}