The problem goes as follows:
Write a recursive function with three arguments: an array (a), the
number of elements of the array (n) and a number - k.
If k is positive and smaller than n it should print the first k positive
numbers of the array.
If k is negative and its absolute value is smaller than n the first k negative numbers should be printed.
If k is larger than n and positive all positive numbers should be printed.
If k is larger than n and negative all negative numbers should be
printed.
This is my attempt
#include <stdio.h>
#include <stdlib.h>
int function(int a[100], int n, int k)
{
int b[n], i;
if (k!=0 && n>1)
{
for (i=0; i<n; i++)
{
b[i]=a[i+1];
}
if (k<n || abs(k)<n)
{
if (k>0)
{
if (b[0]>0)
{
printf("%d", b[0]);
k=k-1;
}
}
if (k<0)
{
if (b[0]<0)
{
printf("%d", b[0]);
k=k+1;
}
}
return function(b, n-1, k);
}
}
else return 0;
}
int main()
{
int i, n, a[100], k;
printf("n = ");
scanf("%d", &n);
for (i=0; i<n; i++)
{
printf("a[%d] = ", i);
scanf("%d", &a[i]);
}
printf("k = ");
scanf("%d", &k);
printf("The new array is: \n");
function(a, n, k);
return 0;
}
But it only prints one number and I don't know how to fix it. Does anyone understand where I went wrong?
EDIT: If the array is {1, -1, 2, -2, 3, -3} and k=2, the expected result is {1, 2}. If k=-2 the expected result is {-1, -2}
EDIT 2: b is an array that contains all the elements of the a array other than a[0]
I found three issues with your code.
1) When I copied your code (converting to C# because that's what I work with), it threw an ArgumentOutOfRangeException for me here:
for (i=0; i<n; i++)
{
b[i]=a[i+1]; <------
}
When i is 99, it tries to copy a[100] into b[99], but there's no a[100]. You should change the for loop to this instead:
for (i=0; i<n-1; i++)
2) Your code is essentially treating a like a queue and popping the first number off (by copying all the others into a new array b), but instead of looking at that first number to determine whether or not to print it, you're skipping it and looking instead at the first item you just put into b:
if (k>0)
{
if (b[0]>0) <------
{
printf("%d", b[0]); <-----
k=k-1;
}
}
You should change your comparisons (and printf lines) to look at a[0] instead of b[0].
3) Whenever k is larger than n, then your entire logic block will get skipped (for example, I mistakenly set k to 34 instead of 3, and when I did, the if block reads if (34 < 6 || abs(34) < 6), which is always false.
Related
Basically I'm just trying to sort all user input numbers by positive or negative. So far I'm just trying to create an array of only positive integers, but can't seem to get it right.
Been stuck on this for a while and can't quite understand why my program is allocating negative integers to my array that's supposed to be for positive integers only, despite my if statements instructing otherwise. Any input would be greatly appreciated!
#include <stdio.h>
#include <stdlib.h>
int main() {
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
int positive_total = 0, negative_total = 0;
int negative_elements[20];
int positive_elements[20];
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
for (i=0; i<num_of_elements; i++) {
printf("\nEnter element a%d. \n:", i+1);
scanf("%d", &elements[i]);
}
for (j=0; j<num_of_elements; j++)
{
if (elements[j] > 0)
{
positive_elements[positive_total] = elements[j];
positive_total++;
} else if (elements[j] < 0) {
negative_elements[negative_total] = elements[j];
negative_total++;
}
}
int num;
for (num=0; num<=positive_total;num++) {
printf("\npositive element %d is %d", num, positive_elements[num]);
}
int MAX_pos_element = 0;
for (x=0; x<=positive_total; x++) {
if (MAX_pos_element < positive_elements[x]) {
MAX_pos_element = positive_elements[x];
printf("\n%d is larger than %d", MAX_pos_element, positive_elements[x]);
printf("\nelement[%d] has the largest value: %d", x, MAX_pos_element);
}
}
return 0;
}
With:
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
you are allocating an array of zero length because num_of_elements is still zero.
Use the following:
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
int elements[num_of_elements];
Now num_of_elements is initialized.
(Note: you should also check the return value of scanf to be sure a number was read.)
The program is initially invalid and has undefined behavior.
You may not declare a variable length array with zero number of elements as you are doing
int num_of_elements = 0, i, j, x;
int elements[num_of_elements];
You should declare the array after you entered a positive value of the variable num_of_elements.
For example
printf("How many elements in N? \n:");
scanf("%d", &num_of_elements);
int elements[num_of_elements];
Also in loops like this
for (num=0; num<=positive_total;num++) {
printf("\npositive element %d is %d", num, positive_elements[num]);
}
you have to use the condition num < positive_total instead of num <= positive_total.
I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.
This is my code, I don't understand my mistake.
int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};
printf("Enter amount of numbers: "); // asking user for amount of numbers
scanf("%d", &d);
for (j=0; j<d; j++){
printf("Enter number %d: ", i+1); // scanning input into 'x' array
scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
if (x[i] % 2 == 0) { // sorting into even array
even[i]=x[i];
printf("%d \n", even[i]);
}
}
printf("\n Odd numbers: ");
for (i=0; i<d;i++){
if (x[i] % 2 != 0) { // sorting into odd array
odd[i]=x[i];
printf("%d \n", odd[i]);
}
}
This error message keeps coming up:
$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:
int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).
scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:
for (j = 0; j < d; j++) {
printf("Enter number %d: ", j + 1); // scanning input into 'x' array
scanf("%d", &x[j]);
}
Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.
I am trying to get user input and store them in an array Fib[i]. After that print the Fib[i] array. When the user enters -1 the loop will quit and the program will end. But my code is not printing or terminating.
#include <stdio.h>
double Fib[50];//globally declared
int fib(int n)
{
int i;
for(i=0; i<50; i++)
{
scanf("%d", &Fib[i]);
if(i==-1)
break;
//printf("numbers entered %d\n", Fib[i]); // <- doesn't terminate if printf is here
}
printf("numbers entered %d\n", Fib[i]); //doesn't print anything??
}
int main()
{
int i, n;
//calling the function
fib(n);
return 0;
}
user input:
4
5
-1
Expected output:
Numbers entered
4
5
First issue: you declare Fib as an array of double:
double Fib[50];
But you use %d to read the values, which is for reading an int:
scanf("%d", &Fib[i]);
Using the wrong format specifier invokes undefined behavior. You presumably want to store integers, so change the array to int:
int Fib[50];
Next is your array breakout condition:
if(i==-1)
i is your array index, which ranges from 0 to 49, so this will never be true. You want to stop when the user enters -1, and that value will be in Fib[i]:
if(Fib[i]==-1)
Finally, printing the array:
printf("numbers entered %d\n", Fib[i]);
This doesn't print the array. It just prints the element at the last index of i, and the value at that index will always be -1. You need a separate loop to print the values:
int j;
printf("numbers entered:\n");
for (j=0; j<i; j++) {
printf("%d\n", Fib[j]);
}
This code has many code writing standard issues but it seems you are new so I am making minimal changes just for your understanding
#include <stdio.h>
double Fib[50];//globally declared
int fib(int n)
{
int i,j;
for(i=0; i<50; i++)
{
scanf("%lf", &Fib[i]);
if(Fib[i]==-1)
break;
}
printf("numbers entered \n");
for(int j=0;j<i;j++)
{
printf("%lf\n",Fib[j]);
}
}
int main()
{
int i, n;
fib(n);
return 0;
}
I am making simple example of little game about guessing numbers.
And I want to build a function which check the numbers and make two values as follows:
1) hits-the number of digits that contain in both number and in same place for both numbers.
2) misses-the number of the digits which contain in both number but not in the same place.
For example:
int systemNumber=1653;
int userGuess=5243;
in this example, in both numbers there are the digits 5 and 3. In both numbers the digit 3 in the same place. But, the digit 5 in systemNumber is not in the same place as userNumber. So, we have here 1 hit and 1 miss.
I've written the code for it with arrays, and I'd like to know if there is a way that I will be able to do this without array and strings.
Here is my code. Please, if you have any improvement for my code, I'd like to know it :)
#include <stdio.h>
#include <stdlib.h>
void checkUserCode(int num1[4], int num2[4]); // declare the function which check the guess
int hits=0, misses=0; // hits and misses in the guess
int main(void)
{
int userCode=0;
int userCodeArray[4];
int systemCodeArray[4]={1, 4, 6, 3};
int i=0;
// printing description
printf("welcome to the guessing game!\n");
printf("your goal is to guess what is the number of the system!\n");
printf("the number have 4 digits. Each digit can be between 1 to 6\nGood Luck!\n");
// input of user guess
printf("enter number: ");
scanf("%d", &userCode);
for (i=3; i>=0; i--)
{
userCodeArray[i]=userCode%10;
userCode=userCode/10;
}
checkUserCode(systemCodeArray, userCodeArray);
printf("there are %d hits and %d misess", hits, misses); // output
return 0;
}
/*
this function gets two arrays and check its elements
input (parameters): the two arrays (codes) to check
output (returning): number of hits and misses
if the element in one array also contains in the other array but not the same index: add a miss
if the element in one array also contains in the other array and they have the same index: add a hits
*/
void checkUserCode(int num1[4], int num2[4])
{
int i=0, j=0;
for (i=0; i<4; i++)
{
for (j=0; j<4; j++)
{
if(num1[i]==num2[j])
{
if (j==i)
hits++;
else
misses++;
}
}
}
}
Here is an example I wrote a while ago, which I tweaked for your problem:
I basically uses two for loops, the outer loop going over the first number, 1653, and the inner loop going over the second number, 5243. It basically compares each individual number in the first number against all the numbers in the second number.
Depending on the counters, it evaluates if equal numbers have been matched in the same positions, using modulo %10 to compare each number.
This is the code:
#include <stdio.h>
#include <stdlib.h>
int
main(void) {
int num1 = 1653;
int num2 = 5243;
int pos1, pos2, hit = 0, miss = 0, i, j;
pos1 = 0;
for (i = num1; i > 0; i /= 10) {
pos2 = 0;
for (j = num2; j > 0; j /= 10) {
if (i % 10 == j % 10) {
if (pos1 == pos2) {
hit++;
} else {
miss++;
}
}
pos2++;
}
pos1++;
}
printf("hits = %d\n", hit);
printf("misses = %d\n", miss);
return 0;
}
Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8