My program keeps crashing. The codes seems legit and correct. Wonder what's the problem.
#include <stdio.h>
void queue(int length,int turns){
int permutations,totalTurns;
turns++;
if (length>0){
queue(length-1,turns);
if (length>1){
queue(length-2,turns);
}
}
else{
permutations++;
totalTurns+=turns;
}
}
int main()
{
while(true){
int length;
float average;
int permutations=0;
int totalTurns=0;
printf("Queue length: ");
scanf("%d", &length);
queue(length,-1);
average=totalTurns/permutations;
printf("The average turns are %f", average);
}
}
int permutations=0;
average=totalTurns/permutations;
You're dividing by zero.
Note that the permutations variable you've declared in main() is different from the one in queue().
You should probably return the permutations value from queue(), like this:
int queue(int length,int turns){
int permutations = 0;
...
return permutations;
}
int main(void) {
...
int permutations = queue(length,-1);
}
You should declare permutations as a global variable, i.e. outside main function as well as totalTurns because as others mentioned it's always 0 because even thought you declare it in function queue it's being forgotten outside it.
#include <stdio.h>
static int permutations=0;
static int totalTurns=0;
void queue(int length,int turns){
turns++;
if (length>0){
queue(length-1,turns);
if (length>1){
queue(length-2,turns);
}
}
else{
permutations++;
totalTurns+=turns;
}
}
int main()
{
while(true){
int length;
float average;
int totalTurns=0;
printf("Queue length: ");
scanf("%d", &length);
queue(length,-1);
average=totalTurns/permutations;
printf("The average turns are %f", average);
}
}
Related
I am quite new to C. I don't really understand how to get the pointers right. I know it can be done without pointers , but I have to use them
#include <stdio.h>
#include <stdlib.h>
void palindrome(int *n)
{
int ok=0,*p,*m;
m=n;
while(*n!=0)
{
*p=*p*10+*n%10;
*n=*n/10;
}
if (*m==*p) ok=1;
if (*m!=*p) ok=0;
if (ok==1)
printf("Number is palindrome.");
if (ok==0)
printf("Number is not palindrome");
}
int main()
{
int n;
printf("Give value to n: ");
scanf("%d",&n);
palindrome(n);
}
The expected resut would be , for example, number 212 is palindrome, number 312 is not palindrome
Here is the code. I think you should try and understand how pointers work before actually using them. I didn't want to provide you the code, but since you are new, i am providing a working code. Try understand how it is working instead of just copy pasting this code to where ever you have to put.
#include <stdio.h>
#include <stdlib.h>
void palindrome(int *n)
{
int ok=0;
int *p = (int *)malloc(sizeof(int));
int *m = (int *)malloc(sizeof(int));
*p=0;
*m=*n;
while(*n!=0)
{
*p=*p*10+*n%10;
*n=*n/10;
}
if (*m==*p) ok=1;
if (*m!=*p) ok=0;
if (ok==1)
printf("Number is palindrome.");
if (ok==0)
printf("Number is not palindrome");
}
int main()
{
int n;
printf("Give value to n: ");
scanf("%d",&n);
palindrome(&n);
return 0;
}
#arpit-agrawal
You forgot to add free, at the end of
void palindrome(int *n)
{
...
free(p);
free(m);
}
I Wrote this code which can identify whether a number is a Armstrong number or not
#include <stdio.h>
#include <stdlib.h>
int n;
const int input()
{
printf("insert n:");
scanf("%d",&n);
return n;
}
int Num_amount()
{
int amount=0;
while(n>=10)
{
amount++;
n=n/10;
if(n<10)
amount++;
}
return amount;
}
int Armstrong()
{
n=input();
int v;
int z=0;
int y=10
int x=Num_amount();
int m[100]={};
int i;
for(i=0;n>=10;i++)
{
v=n%10;
m[i]=pow(v,x);
z=z+m[i];
y=y*10;
}
return z;
}
int main()
{
int z=Armstrong();
printf("%d",z);
}
When run with n=153 i always get 0.After several debugging,I found out the problem is somewhere in the Armstrong function(most likely)
int Armstrong()
{
n=input();
int v;
int z=0;
int y=10
int x=Num_amount();
int m[100]={};
int i;
for(i=0;n>=10;i++)
{
v=n%10;
m[i]=pow(v,x);
z=z+m[i];
y=y*10;
}
return z;
}
The debug watches indicate that instead of execute the for loop,it went straight to the return z line,I have tried everything but still can't figure it out.Can you tell me what the problem is?
You are getting the wrong result because of some logical error. When you are choosing a variable to be global, you need to consider that the variable value can be modified by any function and in this case, you have already modified its value in num_amount function. You have also made some logical error in Num_amount and Armstrong function.
You haven't included math.h header file for pow.
Here is your modified code,
#include <stdio.h>
#include <stdlib.h>
#include<math.h> //<-------------Should have included
int n;
const int input()
{
printf("insert n:");
scanf("%d",&n);
return n;
}
int Num_amount() //<------------modified
{
int z = n; //<--------take a copy of global n
int amount=0;
while(z>0)
{
amount++;
z=z/10;
}
return amount;
}
int Armstrong() //<------------modified
{
n=input();
int v;
int z=0;
int x=Num_amount();
int i;
while(n>0)
{
v=n%10;
z+=pow(v,x);
n/=10; //<-------modification of global n
}
return z;
}
int main()
{
int z=Armstrong();
printf("%d",z);
}
Found a lot problems with the code. Here is a modified version.
1. Do not use a global variable.
2. Make calculation for power easier.
3. Return the status of result, not the result. You want to check whether number is Armstrong or not.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int no_digits(int n){
int digits = 0;
while(n){
digits++;
n = n/10;
}
return digits;
}
int armstrong(){
int n;
printf("insert n:");
scanf("%d",&n);
int digits = no_digits(n);
int curnum = 0,original = n;
while(n){
curnum += pow(n%10,digits);
n /= 10;
}
if(original == curnum)
return 1;
return 0;
}
int main(){
if(armstrong())
printf("Is Armstrong\n");
else printf("Not Armstrong\n");
}
Let's take a look at your loop:
for(i=0;n>=10;i++)
{
v=n%10;
m[i]=pow(v,x);
z=z+m[i];
y=y*10;
}
What's the value of n at this point? You've set it in the previous call to Num_amount like so:
while(n>=10)
{
amount++;
n=n/10;
if(n<10)
amount++;
}
So, after Num_amount has finished executing, n must be less than 10, meaning the loop in Armstrong won't execute.
This is a big reason why you shouldn't use globals, even in a toy program like this. If you use it for different purposes in different places, you just create headaches like this.
At the very least, you should change your code such that n is passed as a parameter to Num_amount and Armstrong.
Your function Num_amount() return "n" value is already less than 10 and for loop never run.
I need to write a function to compute a^b but I am not allowed to use pow. Any ideas? I am lost.
It looks like problem is in main now...
Somewhere it gets that vys is what i characterise it. So if i set that vys=1 in main i get 1 in output..
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
void multiplied(int b, int n)
{
int i=1, vys=1;
while (i<=n)
{
vys *=b;
i++;
}
return vys;
}
main(void)
{
int b=0, n=0, vys=1;
printf("Give numbers b and n but they must be in interval <0,10>!\n");
scanf("%d %d", &b, &n);
if ((b < 0 || b>10) || (n<0 || n>10))
{
printf("Numbers are not in interval <0,10>!\n");
}
else
{
printf("Number is in interval so i continue...\n");
sleep(2);
vys= multiplied(&b, &n);
printf("%d", vys);
}
Let's be explicit.
First, this
void multiplied(int *b, int *n)
returns an int, so say so.
int multiplied(int *b, int *n)
Next, you initialised variables in main: do the same here.
int i, vys;
Like this:
int i=1, vys=1;
Now let's look at the loop:
while (i<=n)
{
vys=*b**b;
i++;
}
As it stands, you are setting vys to something over and over again in the loop.
You want to multiply up, e.g. 2, then 2*2, then 2*2*2, .... if you want a power of two:
while (i<=n)
{
vys *= *b;
i++;
}
Now, you don't need to pass pointers.
int multiplied(int b, int n)
{
int i=1, vys=1;
while (i<=n)
{
vys *= b;
i++;
}
return vys;
}
Edit:
Watch out for when you call the function:
main(void)
{
int b=0, n=0, vys;
//input and checking code as you have it
multiplied(&b, &n); //<---- return ignored
printf("%d", vys); //<-- print uninitialsed local variable
}
Change you last two lines:
vys = multiplied(&b, &n); //<---- return captured
printf("%d", vys); //<-- print returned variable
Edit 2:
With the change to use int in the function and not pointers, pass the ints not their addresses:
vys = multiplied(b, n); //<---- pass the ints not their addresses
printf("%d", vys); //<-- print returned variable, which should vary now
Here you have a simple code:
#include <stdio.h>
long long intpow(int a, int b)
{
long long tempres = 1;
while(b--)
tempres *= a;
return tempres;
}
int main(void) {
printf("%lld\n", intpow(5,10));
return 0;
}
you need much larger int to accommodate the result.
You can play with it yourself: https://ideone.com/4JT6NQ
I'm a beginner and I am having a problem with the code I'm writing ..
I'm receiving the following error: "Unexpected unqualified-id before '{' token in line 9"
Also, I don't know how to set the output and make it shown so if you guys could really help me with that I would be grateful ..
And just to let you know .. I'm using the "Code Blocks"
#include<stdio.h>
#include<conio.h>
int read_temps(float temps[]);
int hot_days(int numOfTemp, float temps[]);
int printf_temps(int numOfTemp,float temps[],int numOfHotDays);
int main(void);
{
int index=0;
float tempVal;
float temps[31];
int numOfTemp,numOfHotDays;
do
{
printf("\n Enter the noon temperature (500 as a sential value)");
scanf("%f",&tempVal);
if(tempVal!=500.0)
{
temps[index]=tempVal;
index++;
}
}while(tempVal!=500.0);
return index;
{
int i;
int count=0;
for(i=0;i<numOfTemp;i++)
{
if(temps[i]>32.0)
count++;
}
return count;
}
{
float sum=0.0;
int i;
printf("\nTemperatures of the month");
printf("\n-------------------------");
for(i=0;i<numOfTemp;i++)
{
printf("\nDay %d : %.2fF",i+1,temps[i]);
sum=sum+temps[i];
}
printf("\nNumber of Hot Days : %d",numOfHotDays);
printf("\nAverage Temperature for a month : %.2f",sum/numOfTemp);
}
{
clrscr();
numOfTemp=read_temps(temps);
numOfHotDays=hot_days(numOfTemp,temps);
clrscr();
printf_temps(numOfTemp,temps,numOfHotDays);
getch();
}
}
int main(void);
{
Remove the semicolon. You seem to misunderstand the format of function declaration and definition.
Function definition:
void foo(void)
{
//something
}
Function declaration:
void foo(void);
The code:
int main(void);
{
is actually a prototype for main followed by an opening brace. Since the prototype is a distinct semantic element, the brace is not a legal token at that point.
You need to remove the trailing semicolon ;:
int main(void)
{
You also seem to have unreachable code in your main function following:
return index;
That return statement is executed unconditionally following the do...while loop so the code following it can never be executed.
That will become a lot clearer once you tidy up your formatting style (eg, use a four-space indent consistently).
In other words, something like this, where the unreachable code and unnecessary braces become obvious (the unnecessary braces are most likely the result of you forgetting to put in function definitions for the three sub-functions that you have prototypes for (a)):
#include <stdio.h>
#include <conio.h>
int read_temps (float temps[]);
int hot_days (int numOfTemp, float temps[]);
int printf_temps (int numOfTemp, float temps[], int numOfHotDays);
int main (void) {
int index = 0;
float tempVal;
float temps[31];
int numOfTemp, numOfHotDays;
do {
printf ("\n Enter the noon temperature (500 as a sentinel value)");
scanf ("%f", &tempVal);
if (tempVal!=500.0) {
temps[index] = tempVal;
index++;
}
} while (tempVal != 500.0);
return index;
{
int i;
int count = 0;
for (i = 0; i < numOfTemp; i++) {
if (temps[i] > 32.0)
count++;
}
return count;
}
{
float sum = 0.0;
int i;
printf ("\nTemperatures of the month");
printf ("\n-------------------------");
for (i = 0;i < numOfTemp; i++) {
printf ("\nDay %d : %.2fF", i+1, temps[i]);
sum = sum + temps[i];
}
printf ("\nNumber of Hot Days : %d", numOfHotDays);
printf ("\nAverage Temperature for a month : %.2f", sum/numOfTemp);
}
{
clrscr ();
numOfTemp = read_temps (temps);
numOfHotDays = hot_days (numOfTemp, temps);
clrscr ();
printf_temps (numOfTemp, temps, numOfHotDays);
getch ();
}
}
And one final note, though it's unrelated to your immediate problem. You should strive as much as possible to write portable code, which would entail avoiding the non-standard conio header file and the use of clrscr and getch (especially when getchar is available).
(a) If that is the case, you'll need to add the definition lines before each function and move them to outside of the main function.
It's just semicolon after your main. Try this one.
#include<stdio.h>
#include<conio.h>
int read_temps(float temps[]);
int hot_days(int numOfTemp, float temps[]);
int printf_temps(int numOfTemp,float temps[],int numOfHotDays);
int main(void)
{
int index=0;
float tempVal;
float temps[31];
int numOfTemp,numOfHotDays;
do
{
printf("\n Enter the noon temperature (500 as a sential value)");
scanf("%f",&tempVal);
if(tempVal!=500.0)
{
temps[index]=tempVal;
index++;
}
}while(tempVal!=500.0);
return index;
{
int i;
int count=0;
for(i=0;i<numOfTemp;i++)
{
if(temps[i]>32.0)
count++;
}
return count;
}
{
float sum=0.0;
int i;
printf("\nTemperatures of the month");
printf("\n-------------------------");
for(i=0;i<numOfTemp;i++)
{
printf("\nDay %d : %.2fF",i+1,temps[i]);
sum=sum+temps[i];
}
printf("\nNumber of Hot Days : %d",numOfHotDays);
printf("\nAverage Temperature for a month : %.2f",sum/numOfTemp);
}
{
clrscr();
numOfTemp=read_temps(temps);
numOfHotDays=hot_days(numOfTemp,temps);
clrscr();
printf_temps(numOfTemp,temps,numOfHotDays);
getch();
}
}
You have not provided your used methods and used return before end of main.
That generate dead code. so anyhow this won't give expected output.
Correct that first. or update your question
#include <stdio.h>
#include <stdlib.h>
#define MAX 25
int readTotalNums();
void fillArray (int nums[], int total);
void sortIt (int nums[], int total);
int findMean (int nums[], int total);
int findMedian (int nums[], int total);
int findMode (int nums[], int total);
void printResults (mean, median, mode);
int goAgain ();
int main()
{
int nums[MAX];
int total;
double mean, median, mode;
do
{
total=readTotalNums();
fillArray(total,nums);
sortIt(nums, total);
mean= findMean (nums,total);
mode=findMode(nums,total);
median=findMedian(nums, total);
printResults(mean,mode, median);
}while(goAgain());
return 0;
}
int readTotalNums()
{
int total;
do
{
printf("How many numbers would you like to enter? (1-25)\n");
scanf("%i",&total);
while(getchar()!='\n');
}while (total<1 || total>MAX);
return total;
}
void fillArray (int nums[], int total)
{
int x;
for (x=0; x<total; x++)
{
printf("enter your numbers\n");
scanf("%i", &nums[x]);
while(getchar()!='\n');
}
}
So I decided to just put up what I have already... because maybe the problem comes before my fillArray function...
I keep getting a "This program has stopped working" message, which, I know you usually get if you don't strip your carriage return. I'm very much a newbie, just trying to make it though my only programming class I have to take for my major, so any help would be appreciated!!
You should pass to scanf a pointer to the location it should store the input, not the value that is already there. scanf("%i", &nums[x]);
The second argument to scanf should be a pointer. Here you are passing an integer. Since this is homework I won't give you the exact code, but that is the problem as far as I can tell.
The scanf function expects pointers, not integers. Didn't you get a compiler warning when you compiled? Try this:
scanf("%i", nums + x);
or equivalently
scanf("%i", &nums[x]);