using output of a program as input in same program - c

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;
}

Related

Adding the same number multiple times to an empty array in C

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;
}

Trying to write a program to fill an array with random numbers in C

My issue is that I am getting segmentation fault (core dumped) each time I try, I have yet to clean up my code, but I am stumped.
I must enter the values in with the compiler e.g "./filename 0 100" whereby 0 is min and 100 is max.
It must then fill the array of 10 elements with random numbers (0-100). I am so close, just can't fathom the main function.
Also, how can I print the array {0,1,2,3} in format "[0,1,2,3]" including the commas, without it looking like "[0,1,2,3, ]"
#include <stdlib.h>
#include <stdio.h>
int getRandom(int min, int max);
void fillArray(int data[], int size, int min, int max);
void printArray(int data[], int size);
int main(int argc, char *argv[]) {
int a;
int b;
if (argc>=3){
a = atoi(argv[1]);
b = atoi(argv[2]);
int arr[10];
printf("\t An array with random values from 0 to 100 \n");
fillArray(arr,10 ,a, b);
printArray(arr, 10);
} else {
printf("Incorrect number of arguments - please call with assignment min max\n");
}
return 0;
}
int getRandom(int min, int max) {
int result = 0;
int low = 0;
int high = 0;
if (min<max) {
low = min;
high = max+1;
} else {
low = max + 1;
high = min;
}
result = (rand() % (high-low)) + low;
return result;
}
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){
data[i] = getRandom(min,max);
}
}
void printArray(int data[], int size){
int i;
printf("[");
for(i=0; i<size; i++){
printf("%d,", data[i]);
}
printf("]");
}
I agree with #Steve Friedl that the main problem with your program lies in the fillArray function. There i should run from 0 to size.
As for your second question, testing whether you're printing the last number helps to suppress the unwanted comma:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d", data[i]);
if (i < size - 1)
printf(",");
}
printf("]");
}
If you prefer a more compact solution (although with an optimizing compiler there's not really a difference), you could write it as:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d%c", data[i], i < size-1 ? ',' : ']');
}
}
Also, in your main function, you should include a and b in your printing:
printf("\t An array with random values from %d to %d \n", a, b);
I believe this is blowing things up for you:
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){ // <-- HERE
data[i] = getRandom(min,max);
}
}
The calling function allocates 10 items in the arr array, and that's passed as the size parameter, but you're not using that parameter to limit filling up the array. If the max value is 100, then it's trying to fill one hundred slots instead of just ten.
for (i = 0; i < size; i++)
data[i] = getRandom(min,max);
should fix at least this issue.
EDIT: The comma thing, I prefer to add commas before the items unless this is the first. In this case it doesn't matter much, but it's more general, especially for variable-length lists where you don't know you're at the end until you get there. Augmenting the helpful response from #JohanC :
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
if (i > 0) printf(",");
printf("%d", data[i]);
}
printf("]");
}

Reverse array with recursion in C programming

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);
}

Recursive function calculating average from int array three by three elements

Calculating average three by three elements and replacing those elements with the average result.
Example array [1,2,7,-2,5,0, 2,8]
After transformation [3,3,3,1,1,1,5,5]
Something is wrong, I can't get it to work.
#include <stdio.h>
int main ( ) {
int n, c[n];
int *avg;
int pom=0;
printf("Enter lenght of array\n");
scanf("%d",&n);
printf("Enter elements");
for(i = 0;i < n; i++)
scanf("%d",c[i]);
avg=Average(c , n, pom);
for(i = 0; i < n; i++)
printf("Avg elements= %d",*(avg+i))
return 0;
}
int Average(int arr[], int size, int z)
{
int k, l, m, Asum;
if (size < 0) {
return arr;
} else {
k=arr[z];
l=arr[z+1];
m=arr[z+2];
Asum=(k + l + m)/3;
arr[z]=Asum;
arr[z+1]=Asum;
arr[z+2]=Asum;
}
return Average(arr,size--,z++);
}
int n, c[n]; is a problem. n is uninitialized so the size of the array is who-knows-what? This is undefined behavior.
Instead
int main(void) {
int n;
int *avg;
int pom=0;
printf("Enter length of array\n");
if (scanf("%d",&n) != 1) return -1;
int c[n];
for(i = 0;i < n; i++)
// scanf("%d",c[i]);
scanf("%d",&c[i]); // pass the address of an `int`
Likely other issues too.
Try simple input first, imagine what happens when you enter only 1 number, what will the Average function do? Don't run the code but try to execute it in your head or with pencil and paper. If you think the program only has to work with three or more numbers, try three.
A serious program would explicitly reject invalid input.

How do you load an array with up to 10,000 numbers in C with a for loop?

This is what I have so far. My random number generator works but I'm not sure how to load the numbers a user wants into an array. It also check to make sure more than 2 and less than 10,000 numbers have been entered.
#include <stdio.h>
int randu(int randoms);
int main (int argc, char *argv[]) {
int numsor;
int randoms[];
int x=0;
if (argc == 1){
printf("How many numbers do you wish to sort? \n");
scanf("%d", &numsor);
}
if (argc == 2){
sscanf(argv[1], "%d", &numsor);
}
if (argc > 2){
printf("how many numbers do you wish to sort? \n");
scanf("%d", &numsor);
}
while (numsor<2 || numsor>10000){
if (numsor < 2){
printf("Error please enter a number more than 2. \n");
}
else{
printf("Error please enter a number less than 10,000. \n");
}
scanf("%d", &numsor);
}
}
int randu(int numsor){
static int seed=17;
seed=(25179*seed+13849)%65536;
return seed;
};
This is the exact pseudo code I'm supposed to go by.
Write a program that will allow the user to generate as many random numbers as they wish (up to
10,000), sort them into ascending order, and print the sorted numbers.
You must use an array to store the numbers, and subroutines to generate and sort the numbers. You MUST make sure that the user selects at least 2 numbers but not more than 10,000. Quantity of numbers user wishes to sort may come from command line and if not, the user should be prompted. Sorted output MUST be on one line separated by a single space.
Pseudocode for Main:
If user enters the quantity of numbers to generate and sort on command line
o Convert and assign that number to the appropriate variable  Otherwise
o Ask the user how many numbers they wish to generate and sort
o Read the input into the appropriate variable
While the user’s input for the quantity of numbers is less than 2 or greater than 10,000
o Display an error message
o Ask how many numbers they wish to generate and sort o Read the input
----This is where my problems begin.------
Use a for loop to load specified quantity of random numbers into the array
Invoke the bubble sorter (Pass the array and number of items in it)
Use a for loop to print the sorted array from first item to last.
int randu(void);
Definitions:
int randu(){
static int seed= 17;
seed = (25179*seed+13849)%65536; return seed;
}
void bubble(int *, int);
void bubble(int a[], int n) { int i, j;
for (i = 0; i < n-1; i++) for (j = n-1; i < j; j--)
if (a[j-1] > a[j]) swap(&a[j-1],&a[j]);
void swap(int *, int *);
void swap(int *a, int *b) { int temp;
temp = *a; *a = *b; *b = temp;
}
}
Just do this: int* randoms = (int *)malloc(sizeof(int)*numsor); // allocate ints
and just use
for(int i = 0; i < numsor; i++)
{
randoms[i] = generate random number here ;
}
#include "stdio.h"
#include "malloc.h"
int randu() {
static int seed= 17;
seed = (25179*seed+13849)%65536;
return seed;
}
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void bubble(int a[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
for (j = n-1; i < j; j--) {
if (a[j-1] > a[j]) {
swap(&a[j-1],&a[j]);
}
}
}
}
void main (int argc, char *argv[]) {
int numsor;
/* Your input logic here ... */
int* randoms = (int*)malloc(sizeof(int) * numsor);
for (int i = 0; i < numsor; i++) {
randoms[i] = randu();
}
bubble(randoms, numsor);
for (int i = 0; i < numsor; i++) {
printf("[%d]: %d\n", i, randoms[i]);
}
}

Resources