I'm try to complete a task set by a lecturer and I have the following code:
#include <stdio.h>
#define N 100
int main(void)
{
int i, a, cnt = 1;
for (a = 1; a < 6; a++){
for (i = 0; i < N; i++, cnt++) {
if (a%2 > 0){
a = 3*a + 1;
}
else{
a = (a/2);
}
printf("%3d\n", a);
if (a == 1){
printf("Count: %d\n", cnt);
return 0;
}
}
}
return 0;
}
The point of this code is to run a hailstone sequence on each integer, a. For now I have it to start at a = 1, then adding 1 to a, and running the sequence again up until a = 5.
This code runs it for the initial value of a but doesn't then add one to a to run it again. I really can't see why it won't do the outer loop again, please help!
A hailstone sequence is where it takes the integer before it in the sequence, if this integer is odd it computes 3*a +1, and if the integer is even it computes a/2. I've told the sequence to stop once a = 1.
Thanks in advance!!
Instead of return 0; in second loop add break; to move out of the inner loop and continue with outer loop.
If you don't want to add break this is another way and there are minor changes in your code which I have highlighted below.
1. You will have to reinititlize cnt for every new value of a.
2. You will have to take a new variable instead of a for calculations
3. For moving out of loop you can increase value of i.
#include<stdio.h>
int main()
{
int i, a, cnt=1, b;
for(a=1; a<6; a++){
cnt = 1;
b = a;
for(i=0; i<100; i++, cnt++){
if(b%2 > 0){
b = 3*b + 1;
}
else{
b = b/2;
}
printf("%d ", b);
if(b==1){
printf("\nCount %d\n", cnt);
i = 100;
}
}
}
return 0;
}
I'm only a student too, but try removing the first "return 0;", I think that's what is ending the code early.
return will end the function. I think what you are looking for is break
Related
I have started relearning C (self study), and ran into a problem with an if statement not always executing inside of a loop. What's odd is that on it's own, the function executes correctly, but unless I add a printf() statement referencing the variable in the loop then it won't attempt to test the if statement.
Specifically, the line printf("%d ", aCounter); in the while loop in the main(void) function is what's required for it to attempt test the if statement. I had a similar problem using a for loop (as you can see it's commented out). I am confused as to why it doesn't test the if statement without the printf() mentioned. And yet it does successfully find: 1, 6, 24, 28, and 496 with the printf() statement. It only finds "1" without it.
#include <stdio.h>
int isPerfect(unsigned int n);
int main(void) {
/* for (unsigned int i = 1; i <= 1000; i++) {
if (isPerfect(i) == 1) {
printf("%d is perfect\n", i);
}
}
*/
int aCounter = 0;
while (aCounter < 1000) {
aCounter++;
if (isPerfect(aCounter) == 1 ) {
printf("%d is perfect\n", aCounter);
for (int aTemp = 1; aTemp < aCounter; aTemp++) {
if (aCounter % aTemp ==0) {
printf("%d is a factor of %d\n", aTemp, aCounter);
}
}
}
printf("%d ", aCounter);
//aCounter++;
}
int a = 6;
if (isPerfect(a) == 1 ) {
printf("%d is perfect\n", a);
}
printf("%d is perfect: %d\n", 6, isPerfect(6));
printf("%d is NOT perfect: %d\n", 8, isPerfect(8));
printf("%d is perfect: %d\n", 6, isPerfect(6));
}
int isPerfect(unsigned int n) {
int aNumber;
for (int i =1; i <= n; i++) {
if (n % i == 0) {
aNumber += i;
if (aNumber == n)
{
return 1;
}
}
}
return 0;
}
I'm not sure about the expected output of your program, but I can see that inside the isPerfect(unsigned int n) function, we have a statement aNumber += i; which basically does is aNumber = aNumber + 1;, i.e, update the value of aNumber by 1. But as we can see, in the very first statement inside this function where aNumber is defined, it isn't initialized, so updating its value to 1 seems pointless as it's previous value is unknown. Initializing its value , let's say int aNumber = 0;
will do the job.
But uninitialized variable in C need not always contain a garbage value.
automatic (local) variables are not guaranteed to be zero, can contain
garbage but global variables and static variables are guaranteed to be
zero
please refer to this post StackOverflow post for more details.
.
I've been trying to build a recursive function which calculates the max value, but even I can see the total value when I print in the function, I can't return the value to the main function. Can you tell me where do I do wrong? Thanks for help!
note : more explanation about what I ve been trying to build is : user defines an object and as long as user doesn't give the price, I keep asking what the object is..
small example :
Define the object:
Car
What is Car?:
4*Wheel+1*Frame
What is Wheel?:
2*Rim
What is Rim?
5.0
What is Frame?:
10.0
Total is : 50.0
Current code:
#include <stdio.h>
#include <stdlib.h>
#define INPUT_SIZE 101
void delete_space(char arr[])
{
int a, i, j, len;
for(a = 0; a < INPUT_SIZE; a++)
{
for(i = 0; i < INPUT_SIZE; i++)
{
if(arr[i] == ' ')
{
for(j = i; j < INPUT_SIZE; j++)
{
arr[j] = arr[j + 1];
}
}
}
}
}
double result(char input[], double coeff, double total)
{
/* if the input is number, num_of_obj is 0, if the input is object, num_or_obj is more than 0.
*/
int i, k = 1, num_of_obj = 0;
char temp_input[INPUT_SIZE];
char temp_input_1[INPUT_SIZE];
char x;
int* p;
double value;
p = (int*)calloc(1, sizeof(int));
p[0] = 0;
printf("What is %s:?\n", input);
scanf("%[^\n]s", temp_input);
getchar();
delete_space(temp_input);
for(i = 0; i < INPUT_SIZE; i++)
{
if(temp_input[i] == '*')
{
num_of_obj++;
}
}
if(num_of_obj == 0) // if the input is number.
{
sscanf(temp_input, "%lf", &value);
total = total + coeff * value;
printf("total : %lf", total);
return total;
}
if(num_of_obj > 0)
{
for(i = 0; i < INPUT_SIZE; i++)
{
if(temp_input[i] == '+')
{
p = (int*)realloc(p, (k + 1) * sizeof(int));
p[k] = i + 1;
k++;
}
}
for(i = 0; i < k; i++)
{
sscanf(&temp_input[p[i]], "%lf%c%[^+]s", &coeff, &x, temp_input_1);
result(temp_input_1, coeff, total);
}
}
printf("test");
return total;
}
int main()
{
double total = 0;
char input[INPUT_SIZE];
printf("Define the object :\n");
scanf("%[^\n]s", input);
getchar();
delete_space(input);
printf("total : %.2lf", result(input, 0, 0));
return 0;
}
I believe that the main issue is the recursive call: result(temp_input_1, coeff, total);, which is ignoring the returned result.
Two possible solutions: (1) do the aggregation in result OR (2) tail recursion. I'm not sure that this case fit into tail recursion (or that there are any benefits here). Consider removing the 'total' from result prototype, and doing the aggregation (over the 'components') in the loop.
double result(char input[], double coeff) {
double total ;
...
for(i = 0; i < k; i++)
{
sscanf(&temp_input[p[i]], "%lf%c%[^+]s", &coeff, &x, temp_input_1);
total += result(temp_input_1, coeff, total);
}
Side comment: Consider also removing the 'delete_space' function. I believe it does not property fix the string. Much easier to skip over the spaces in the scanf call.
Welcome to stackoverflow! I too am new here, but if you word your questions right, you'll get better answers. If this is a homework assignment, I highly recommend including that, it can be hard to follow descriptions.
So as a general rule of thumb, when writing C functions its best to use as few return statements as possible. But I too have difficulty with this.
It looks like your are checking for
is first condition met?
if not check next condition
should you be using if, if else, and else?
Also you have if statements with no else, generally needed, especially in a recursive function (you might be skipping over the next step after the last recursive call)
Hope this helps! Swamped with the end of the semester myself or else I would have attempted a solution!
You need three things to write a recursive method successfully:
A terminating condition, so that the method doesn't call itself forever,
Some work to do, and
A recursive call.
Consider the following code:
typedef struct node{
void* item;
struct node* next;
} Node;
int CountNodes(Node* list)
{
if (list == null) return 0;
return 1 + CountNodes(list.next);
}
This code works because it counts the current node plus all remaining nodes. The recursive call counts the next node and all remaining nodes. And so on.
I'm trying to print out 100 numbers from an array using a loop and then add them all together. So far I have:
#include <stdio.h>
#include <stdlib.h>
int main(){
int* number = malloc(101 * sizeof(int));
int num = 0;
number[num] = 1;
while (number[num] <= 100){
printf(" %d\n ", number[num]);
num = num +1;
number[num] = number[num]+1;
}
return 0;
}
but this just prints 1 once.
number[num] = number[num]+1;
You only properly set number[0]. Now you are trying to take whats in number[1] and add to it, in the first iteration. You didn't set it to anything though, leaving it uninitialised. This is undefined behaviour. What you most likely wanted to do is
number[num] = number[num-1]+1;
To add one to the previous number before after printing it. Now it will print fine.
To add them up, simply do
for (int a = 0; a < 100; a++) {
number[100] += number[a]; // add number[a] to result
}
printf("%d\n",number[100]);
Also, don't forget to free your dynamically allocated array at the end.
Try this:
#include <stdio.h>
int main () {
int n[ 100 ]; /* n is an array of 100 integers */
int i,j;
int sum = 0;
/* initialization */
for ( i = 0; i < 100; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 100; j++ ) {
printf("Element[%d] = %d\n", j, n[j]);
sum += n[j];
}
printf("Sum of Elements = %d\n", sum);
return 0;
}
Remember that you should declare an array, then initialize it, print it out and after all print out the sum
You can just print out 1 to 100, then you could quickly use some maths to get the count of all numbers added together, for example, one of Gauss' algorithms, specifically http://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/
There’s a popular story that Gauss, mathematician extraordinaire, had a lazy teacher. The so-called educator wanted to keep the kids busy so he could take a nap; he asked the class to add the numbers 1 to 100.
Here's what I would do: -
int i = 0;
for (i = 1; i <= 100; i++) {
printf("%d", i);
}
// gauss technique 100(100 + 1) / 2
int count = (100 * 100 + 100 * 1) / 2;
printf("all numbers added: %d", count);
I'm going through the Big Nerd Ranch book on Objective-C, which takes you through some early C stuff. I've played with C before, and am pretty experienced in PHP.
Anyhow, I'm doing the challenges and this one is not working the way I think it should. It's pretty simple - start at 99, loop through and subtract three until you get to zero, and every time you get a number that is divisible by 5 print "Found one." Pretty straightforward. However, subtracting by three in the for loop is not working
#include <stdio.h>
int main (int argc, const char * argv[])
{
int i;
for(i = 99; i > 0; i-3){
printf("%d\n", i);
if(i % 5 == 0) {
printf("Found one!\n");
}
}
return 0;
}
It creates and endless loop at 99, and I'm not sure why.
i-3 doesn't modify the variable i. Do something like -
for( i=99; i>0; )
{
// ....
i -= 3;
}
It should be i-=3 instead of i-3.
#include <stdio.h>
int main (int argc, const char * argv[])
{
int i;
for(i = 99; i > 0; i-=3){
printf("%d\n", i);
if(i % 5 == 0) {
printf("Found one!\n");
}
}
return 0;
}
i-3 does not change the value of i.
i-=3 does.
Your loop statement doesn't modify the value of i. Just doing i - 3 doesn't change i, it just returns the value of i - 3.
Use: for(i = 99; i > 0; i = i - 3)
In the for loop, it should be i=i-3.
You are just subtracting 3 from i, but you are not assigning it to i.
Use i = i - 3 instead of just i - 3.
Change your for statement like this:
for(i = 99; i > 0; i = i - 3) {
// Write your code here.
}
The Last Term in the For loop is the increment of decrement operation. While i-3 is none. If you want the Value of i to get reduced by 3, then you should store that value in i itself.
To do that Following code should be written: i = i-3 or shorthand i-=3.
I wrote this program:
#include <stdio.h>
/*Part B
Write a program that:
defines an array of 10 ints
assigns factorial(x) to array element x, for x in the range 0 through 9, inclusive
copies those array elements into a second array of 10 ints, but in reverse order (i.e., element 0 is factorial(9), element 1 is factorial(8), and so on)
prints out that second array to the terminal*/
int factorial(int n){
int factorial = 1;
while(n>1){
factorial = n*factorial;
}
return factorial;
}
int main(int argc, char **argv){
int arr1[10];
int arr2[10];
int i = 0;
for(i = 0; i<10; i++){
printf("%d", i);
arr1[i] = factorial(i);
}
for(i = 9; i>=0; i--){
arr2[i] = arr1[9-i];
printf("%d ", arr2[i]);
}
printf("\n");
return 0;
}
but when I run it it just sits there. I think it's something to do with the call to factorial, because when I comment that out it works instantly, but with it in, it isn't even getting to the first printf.
What am I doing wrong?
while(n > 1){
factorial = n*factorial;
}
you missed n--;
Your while loop:
while(n>1){
factorial = n*factorial;
}
Will run forever. There is nothing in that loop that can change n, so if the loop is entered then we know n will always be greater than 1. You should decrement n within your loop:
while(n > 1){
factorial = n--*factorial;
}
If you aren't used to seeing decremenent like that you can also do it on a new line:
while(n>1){
factorial = n*factorial;
n--;
}
You should decrement n in factorial function.
You have a wrong implementation of factorial method.
int factorial(int n){
int factorial = 1;
while(n>1){
factorial = n*factorial;
n--;
}
return factorial;
}
Your code simply didn't do anything with n variable and kept multiplying, without ever decreasing n value. Hope this helps