reverse an array with recursion - c

When I try to run this it asks me to input 11 numbers instead of 10 with is really weird then it out puts like an even weirder result please help.
void function(int array[],int length,int start)
{
if (length<start)
{
return;
}
int temp=array[start];
array[start]=array[length];
array[length]=temp;
function(array,length-1,start+1);
}
int main()
{
int array[10],num=0,num2=10;
printf("enter the array:\n");
for (int i =0; i<num2; i++)
{
scanf("%d\n",&array[i]);
}
function(array,num2,num);
for (int t = 0; t<num2; t++)
{
printf("%d\n",array[t]);
}
}
then this is the out put for the array 1,2 ... 10,11
enter the array:
1
2
3
4
5
6
7
8
9
10
11
return
214696143
10
9
8
7
6
5
4
3
2
(lldb)
please help

The last index of an array with size 10 is actually 9. So this line:
function(array,num2,num);
Should be:
function(array,num2-1,num);
Also, your use of scanf is incorrect. Eliminate the \n character. Read more about scanf here: http://www.cplusplus.com/reference/cstdio/scanf/
I corrected your code and tested it here: https://onlinegdb.com/B1Yy4yBqN

Try this:
#include <stdio.h>
void function(int array[],int start, int end)
{
if (start < end)
{
int temp;
temp = array[start];
array[start] = array[end];
array[end] = temp;
function(array, start+1, end-1);
}
}
int main()
{
int array[10],num=0,num2=10;
printf("enter the array:\n");
for (int i =0; i<num2; i++)
{
scanf("%d",&array[i]);
}
function(array,num,num2 - 1);
for (int t = 0; t<num2; t++)
{
printf("%d\n",array[t]);
}
}
Note that in C, the array starts from 0. The last index is 9 not 10. You need to access to the last element using length - 1 instead of length

Related

Find minimum number of wires to connect the bulbs code

I have written this C code to find a minimum number of wires required to switch on all the bulbs.
The problem is that there is x number of computers, some of which are On and some are Off and the distance between these bulb from the first bulb is given. The computer can be switched ON by connecting it to its nearby ON the bulb.
So the inputs are as follows:
X = 6 (number of bulbs)
1 0 1 1 0 1(1 means the bulb is ON and 0 means the bulb is OFF)
2 4 8 36 37 40 (distance between one bulb from the first bulb)
and the output will be:
3 (Reason: 4 - 2 = 2, 37 - 36 = 1, 2 + 1 = 3)
#include <stdio.h>
int main(){
int n,pre,post,sum = 0;
scanf("%d",&n);
int arr[n],dist[n];
for(int i =0;i<n;i++){
scanf("%d ",&arr[i]);
}
for(int i =0;i<n;i++){
scanf("%d ",&dist[i]);
}
for(int i =0;i<6;i++){
if(arr[i] == 0){
pre = dist[i]-dist[i-1];
post = dist[i+1]-dist[i];
if(pre>post){
sum +=post;
}
else{
sum+=pre;
}
}
}
printf("\n %d",sum);
}
It keeps on taking the inputs. Please tell me what is the error in this code?
Thanks in advance.
Edited: I missed that scanf("%d",n) by mistake. It was there in my original code and the problem still persists.
As Sandrin mentioned, n is not defined.
Assuming your input file is:
6
1 0 1 1 0 1
2 4 8 36 37 40
You need to add code to set n:
scanf("%d ",&n);
And, you need to insert this before the definitions of your matrix
Here's the refactored code:
#include <stdio.h>
int
main(void)
{
int n, pre, post, sum = 0;
#if 1
scanf("%d ",&n);
#endif
int arr[n], dist[n];
for (int i = 0; i < n; i++)
scanf("%d ", &arr[i]);
for (int i = 0; i < n; i++)
scanf("%d ", &dist[i]);
for (int i = 0; i < 6; i++) {
if (arr[i] == 0) {
pre = dist[i] - dist[i - 1];
post = dist[i + 1] - dist[i];
if (pre > post) {
sum += post;
}
else {
sum += pre;
}
}
}
printf("\n %d", sum);
return 0;
}
Putting a side technical errors (e.g. n not initialized), the algorithms assumes that all problems can be solved by single pass. This is not true for cases like:
1 0 0 0 0 1
0 1 3 4 6 7
Where the code will choose to connect bulbs [0,1], [2,3], and [4,5], based on pre/post distances. However, bulbs 2 and 3 will remain disconnected.
A better algorithm will attempt to find, for each sequence of off bulbs, which is the most expensive connection, and avoid it.
I have come up with this solution for my code and I have tried to consider all the test cases. If you find any test case that won't run feel free to tell.
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av){
int n,pre,post,sum = 0;
scanf("%d",&n);
int *input,*distance;
input = malloc(n * sizeof(int));
for (int i=0; i < n; i++)
{
scanf("%d", &input[i]);
}
distance = malloc(n * sizeof(int));
for (int i=0; i < n; i++)
{
scanf("%d", &distance[i]);
}
for(int i =0;i<6;i++){
if(input[i] == 0){
pre = distance[i]-distance[i-1];
if(input[i+1]==1){
post = distance[i+1]-distance[i];
input[i] =1;
if(pre>post){
sum +=post;
}
else{
sum+=pre;
}
}
else{
sum = sum+pre;
}
printf("%d.....%d....%d\n",pre,post,sum); //Debugging
}
}
printf("\n %d",sum);
free(input);
free(distance);
}

Array in C containing Incorrect Values

The goal of this program is to add the first and last elements of an array together and set that value as the first element of an output array, and then continue moving inwards as such. All of the sums will be stored in an output array. For this program, the rules stipulate that I may only use pointers and pointer arithmetic (i.e. no subscripting, no '[]', etc.) I have gotten the program to work for arrays of length 2 as well and length 4 (as I have only implemented functionality for even-lengthed arrays) however when I try any array of length 6 or above, the program adds together incorrect values that are not in the first array.
I have already tried using two different debuggers to isolate where the problem is coming from and for the life of me I can not figure it out. I have spent a few hours looking over my notes on C and going through the code, reworking it however I can. I feel as if there is something wrong with how I am interacting between the array and the pointer variables, but I am unsure. I couldn't seem to find any questions on Stack Overflow too similar to this one (yes, I looked).
void add(int *a1, int array_size, int *a2) {
int * p;
int * temp = (a1+(array_size-1));
if (array_size % 2 == 0) {
array_size = array_size/2;
for (p = a2; p < (a2+array_size); p++) {
*p = *a1 + *temp;
printf("%d", *a1);
printf(" + %d", *temp);
a1++;
temp--;
printf(" = %d\n", *p);
}
}
}
For arrays of length 2 and 4 (again, I am only testing even numbers for now), the code works fine.
Example Output:
Enter the length of the array: 2
Enter the elements of the array: 1 2
1 + 2 = 3
The output array is: 3
Enter the length of the array: 4
Enter the elements of the array: 1 2 3 4
1 + 4 = 5
2 + 3 = 5
The output array is: 5 5
Now this is where it is going wrong.
When I do this:
Enter the length of the array: 6
Enter the elements of the array: 1 2 3 4 5 6
I expect:
1 + 6 = 7
2 + 5 = 7
3 + 4 = 7
The output array is: 7 7 7
But instead, the output is:
1 + 0 = 1
2 + 3 = 5
3 + 4 = 7
The output array is: 1 5 7
My best guess is that something went wrong with my use of pointers or perhaps pointer syntax. Any help I can get, positive or negative, would be greatly appreciated.
This is the main() function:
int main() {
int size = 0;
int out_size = 0;
int arr[size];
printf("Enter the length of the array: ");
scanf("%d", & size);
printf("\nEnter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}
if (size % 2 == 0) {
out_size = size/2;
}
else{
out_size = ((size-1)/2) + 1;
}
int out[out_size];
//calling the add function and using the addresses of arrays + array size
add(arr, size, out);
//iterating through and printing output array which has now been
//altered by the move function
printf("\nThe output array is: ");
for (int i = 0; i < out_size; i++) {
printf("%d ", out[i]);
}
return 0;
}
You are using an array of size 0:
int main() {
int size = 0;
int out_size = 0;
int arr[size]; // <- Here is your problem
You could move the array declarations after the size reading:
int main() {
int size = 0;
int out_size = 0;
printf("Enter the length of the array: ");
scanf("%d", & size);
int arr[size];
printf("\nEnter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}

Printing stars for a specific number of freq in arrays

I am still new to C, and I need to figure a way to print the same number of stars as the number of frequencies.
Here's my code:
int arrayHistogram(int array[]){
int i;
int j;
int count=0;
int freq[SIZE];
char stars[SIZE];
for(i = 0; i < SIZE; i++){
count =1;
for(j = i+1; j < SIZE; j++){
if(array[i]==array[j]){
count++;
freq[j]=0;
}
}
if(freq[i] != 0){
freq[i] = count;
}
}
//for ( i = 0; i < SIZE; i++){
//int num = freq[i];
//stars[i]= '*'*num;
}
printf("Value ");
printf("Frequency ");
printf("Histogram\n");
for(i = 0; i < SIZE; i++){
if(freq[i] != 0){
printf("%5d%10d%10d\n", array[i], freq[i], stars[i]);
}
}
}
I know that I can't multiply char by int here to print the stars, but I put here just to show where I need to print those stars (i.e. the histogram).
My Output:
Value Frequency Histogram
7 4 -46
8 3 126
4 6 84
Expected output:
Value Frequency Histogram
7 4 ****
8 3 ***
4 6 ******
Well, you already know everything to do that i.e. loop.
Simply, loop up to a frequency and print that many stars.
Something like this (pseudo code):
loop until freq[i]
print '*'
end loop
It's just an idea. You know how a loop works. Just put a nested loop (i.e. for loop) where you need to print the stars. Mind the newline. You need a newline at the end of each line after printing the stars.
UPDATE:
As observed, you've frequencies up to 10 i.e. a fixed size that you already know. You can simply use a string of stars and then print it using printf() with %.*s format specifier with field width and string length.
Here's an example (live code):
#include <stdio.h>
#define SIZE 10
int main(void)
{
const char* stars = "**********";
const int freqs[ SIZE ] = { 3, 5, 6, 2, 0, 7, 10, 9, 4, 8 };
for ( int i = 0; i < SIZE; i++ )
{
printf("%5d \t %10.*s\n", freqs[i], freqs[i], stars);
}
return 0;
}
OUTPUT:
3 ***
5 *****
6 ******
2 **
0
7 *******
10 **********
9 *********
4 ****
8 ********
how about building char stars[SIZE] with a loop?
int nStars = freq; // in you situation.
for(int i=0; i < nStars;++i)
{
stars[i] = '*'; // set char i to be '*'
}
stars[nStars] = '\0'; // don't forget to terminate your string
you can make a simple utility function void fillChar(char* buff, char ch, int count); of it.
Take Caution not to exceed the size of the allocated string or bad things gona happen.
Cheers.

C Insertion Sort Program Fails With Many Inputs

Heyo!
I'm new to C and have hit a brick wall trying to sort a set of numbers.
If I input '5 3 0 9 5', it will correctly return 9 5 5 3 0.
However, '5 3 0 0 9 9 10 11 13 14 9' doesn't return a thing. Some debugging shows it gets to the 3, then just stops.
Where should I start looking?
Here's my code, but general suggestions are fine:
#include <stdio.h>
#include <stdlib.h>
int getvals(int A[]);
void val_swap(int *a,int *b);
int main() {
int len = 0;
int vals[len];
len = getvals(vals);
int i = 0, j = 0;
/* Search through the values from start to finish */
for (; i < len; i++) {
/* Search back through the values, right to left. If we find a smaller value, swap. */
for (j = i-1; j >= 0 && vals[j+1] > vals[j]; j--) {
/* Swap */
val_swap(&vals[j], &vals[j+1]);
}
}
/* Print the sorted array */
int k = 0;
for (; k < len; k++) {
printf("%d ", vals[k]);
}
return 0;
}
int getvals(int A[]) {
/* Gets a list of integer values from the user */
int num, arr_len = 0;
printf("Enter numbers. CTRL + D to end: ");
while(scanf("%d", &num)) {
A[arr_len] = num;
arr_len++;
}
return arr_len;
}
void val_swap(int *a, int *b) {
int tmp;
/* Save the value of b to temp var */
tmp = *b;
/* Swap the pointer values */
*b = *a;
/* Reassign value */
*a = tmp;
}
Maybe the returned value of getvals is less than the amount of '5 3 0 0 9 9 10 11 13 14 9' , so many data.
But I am wondering whether it can pass the compilation, int vals[len], when len is 0, we don't say whether this is right, but the size of vals has already fixxed because the space of vals is in stack, no heap's.
So in my opinion, there are no enough spaces to run the program.

Value changing error of the array's first element when passed to a method in C

I have created one array, got input from the user, and passed that array into a method.
After passing it, the value of first element changes and I can't understand why and how.
For instance:
I enter 55 1 2 6 7 5 4 0 displays 70 1 2 6 7 5 4.
Similarly, 121 5 6 1 2 0 displays 26227 5 6 1 2.
int main(int argc, char *argv[]) {
int sequence[100];
int i;
int sequenceSize =0;
for(i =0; i < 100; i++){
scanf("%d",&sequence[i]);
if(sequence[i] == 0){
break;
}
sequenceSize++;
}
method(sequence, sequenceSize);
return 0;
}
void method( int A[] , int sequenceSize){
int M;
printf("This is the array \n");
for(M = 0; M < sequenceSize; M++){
printf("%d ", A[M]);
}
}
I believe it's a problem of your IDE. Clean your project before running.
You can test your program here
https://www.onlinegdb.com/online_c_compiler

Resources