This code in C language works perfectly, I will explain what it does:
Given a positive integer "n" and a sequence of "n" integers, the sum will determine a sequence of positive integers.
Examples of inputs:
4 9 -1 4 -2
expected output: 13 / input: 3 3 0 -2 output: 3/
#include <stdio.h>
int main(){
int cont=0,n,num,sum;
scanf("%i",&n);
while(n>cont){
cont++;
scanf("%i",&num);
if(num>0){
sum=num+sum;
}
}
printf("%i",sum);
}
and this was my attempt to convert it to Ruby
cont=0
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
if num>0
sum=num+sum
end
puts"#{sum}"
and this is what im getting:
ruby test.rb
test.rb:10: syntax error, unexpected end-of-input, expecting keyword_end
puts"#{sum}"
^
. Can anyone help?
Thank you, so this is the right code that works
cont=0
sum=0
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
sum=num+sum if num>0
end
puts"#{sum}"
You were not far off. The syntax of the if-statement needs a then and an end. Also, sum needs to be zero at the start.
cont=0
sum=0 # sum needs an initial value
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
sum=num+sum
# num = num+sum if num >0
# #or
# if num >0 then
# sum=num+sum
# end
# #But both "if's" serve no purpose
end
puts"#{sum}"
Another way of writing this is:
sum = 0
gets.to_i.times{sum += gets.to_i} # no bookkeeping with cont
puts sum # more simple then puts"#{sum}"
Related
Without using an array, I am trying to do this. what is wrong with my code?
n is the number of elements,a is the first element(assumed to be maximum initially), b stores new element every time and sec variable stores the second-largest element. Numbers are all positive. This is from an online contest.
#include<stdio.h>
int main() {
int i,a,b,max,n,sec;
scanf("%d",&n);
scanf("%d",&a);
max=a;
while(n-1!=0) {
scanf("%d",&b);
if(b>max) {
sec=max;
max=b;
}
else if(b<max && b>sec)
sec=b;
else{}
n--;
}
printf("%d",sec);
return 0;
}
getting wrong answers in some test cases( i don't know )
Consider sequence 2, 12, 10 (leaving out surrounding code):
int sec; // unitialised!!!
max = a; // 12
if(b > max) // b got 10, so false!
{
sec = max; // this code is not hit! (b remains uninitalised)
max = b;
}
else if(b < max && b > sec)
// ^ comparing against uninitialised
// -> UNDEFINED BEHAVIOUR
You need to initialise sec appropriately, e. g. with INT_MIN (defined in <limits.h>); this is the minimal allowed value, with 32-bit int that would be a value of -232 - 1, i. e. -2 147 483 648. Pretty unlikely anybody would enter that value, so you could use it as sentinel.
You even could initialise max with that value, then you woudn't need special handling for the first value:
int sec = INT_MIN, max = INT_MIN;
int n;
scanf("%d", &n); // you should check the return value, which is number of
// successfully scanned values, i. e. 1 in given case,
// to catch invalid user input!
// you might check value of n for being out of valid range, at very least < 0
while(n--) // you can do the decrement inside loop header already...
{
// keep scope of variables as local as possible:
int a;
// scanf and comparisons as you had already
// again don't forget to check scanf's return value
}
if(sec == INT_MAX)
{
// likely hasn't been modified -> error, no second largest element
}
else
{
// ...
}
Now what if you do expect user to give you the value of INT_MIN as input?
You could have a separate counter, initialised to 0, you increment in both of the two if branches inside the loop; if this counter is < 2 after the loop, you didn't get at least two distinct numbers...
Lets look at the input
2 4 3
Two is the number of inputs.
4 ends up in max.
3 ends up in b.
b is not greater than max, the if does not do anything.
b is less than max, but b is not necessarily greater than sec,
because sec at this point can be anything - whatever currently is inside that non-initialised variable. sec at this point is for example not guaranteed to be 0. So the else if does not trigger and we end up in else {}.
So we end up executing the printf() at the end of the program with a still uninitialised sec. And that is unlikely to satisfy the judge.
To solve the problem, you need to initialise sec. Initialising to 0 might work, but actually you need to use the lowest possible input value.
Since you chose int, instead of unsigned int, I assume that 0 is NOT the lowest possible value. But you would have to quote the assignment/challenge to allow determining the lowest possible value. So you need to find that out yourself in order to make a solution code.
Alernatively, you can analyse the first input values to initialise max and sec (need to watch them coming in until you get two distinct values; credits to Aconcagua).
Usually it is however easier to determine the lowest possible value from requirements or the lowest possible int value from your environment.
At some level of nitpicking, you need to know the lowest possible value anyway, in order to select the correct data type for your implementation. I.e. even with analysing the first two values, you might fail for selecting the most narrow data type.
In case you "successfully" (as judged by the challenge) use 0 to initialise sec, try the input 2 1 -1.
It should fail.
Then try to find in your challenge/assignment description a reason why using 0 is allowed. It should be there, otherwise find a different challenge site to improve your coding skills.
I liked how OP initialized max with the first input value.
This brought me to the idea that the same can be done for sec.
(The value of max is a nice indicator that sec could not be determined whatever max contains. In regular case, max and sec can never be equal.)
Hence, one possibility is to initialize max and sec with the first input
and use max != sec as indicator whether sec has been written afterwards at all.
Demo:
#include <stdio.h>
int main()
{
/* read number of inputs */
int n;
if (scanf("%d", &n) != 1 || n < 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
/* read 1st input */
int max;
if (scanf("%d", &max) != 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
--n;
int sec = max;
/* read other input */
while (n--) {
int a;
if (scanf("%d", &a) != 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
if (max < a) { sec = max; max = a; }
else if (sec == max || (sec < a && a < max)) sec = a;
}
/* evaluate result */
if (sec == max) {
puts("No second largest value occurred!\n");
} else printf("%d\n", sec);
/* done */
return 0;
}
Output:
$ gcc -std=c11 -O2 -Wall -pedantic main.c
$ echo -e "3 3 4 5" | ./a.out
4
$ echo -e "3 3 5 4" | ./a.out
4
$ echo -e "3 4 3 5" | ./a.out
4
$ echo -e "3 4 5 3" | ./a.out
4
$ echo -e "3 5 3 4" | ./a.out
4
$ echo -e "3 5 4 3" | ./a.out
4
$ # edge case:
$ echo -e "2 3 3" | ./a.out
No second largest value occurred!
Live Demo on coliru
I assumed the output to be '0' for the following code but, I am getting the output as '3'.
#include<stdio.h>
int num_digit(int n);
int num_digit(int n)
{
if (n == 0)
return 0;
else
return 1 + num_digit(n/10);
}
int main() {
int k = num_digit(123);
printf("%d\n",k);
return 0;
}
The following link provides an excellent source for learning C Recursion and as #MFisherKDX pointed out help solve my confusion.
https://www.programiz.com/c-programming/c-recursion
After each time the recursion happens it returns a value.
adding up all the values :
0+1 = 1
1+1 = 2
2+1 = 3
gives the answer as 3.
This is basic recursion. Just try to create a recursion tree for the program that you have written and you should be able to figure out why is the output that you see coming as 3.
You are expecting 0 as answer, only based on the last recursive call (terminating condition), but when a recursive call happens, there is a concept of activation records which are maintained in the form of Stack data structure.
The recursion tree will look something like what is shown in Recursion Tree for shared code
num_digits(123) = 1 + num_digits(12)
num_digits(12) = 1 + num_digits(1)
num_digits(1) = 1 + num_digits(0)
num_digits(0) = 0
Using substitution:
num_digits(123) = 1 + (1 + (1 + (0)))
Please follow the parenthesis above clearly and you should be able to absolutely understand the output that you were getting out of the code that you wrote.
Recursion stack for your code is like below
1 + num_digit(123/10);
1 + num_digit(12/10);
1 + num_digit(1/10); //at this point your code will return 0 for num_digit(1/10)
and backtracking is like below
1+0=1
1+1=2
1+2=3
Hence the final answer is 3
In order to learn recursion, I want to count the number of decimal digits that compose an integer. For didactic purposes, hence, I would like to not use the functions from math.h, as presented in:
Finding the length of an integer in C
How do I determine the number of digits of an integer in C? .
I tried two ways, based on the assumption that the division of an integer by 10 will, at a certain point, result in 0.
The first works correctly. count2(1514, 1) returns 4:
int count2(int n, int i){
if(n == 0)
return 0;
else
return i + count2(n / 10, i);
}
But I would like to comprehend the behavior of this one:
int count3(int n, int i){
if(n / 10 != 0)
return i + count3(n / 10, i);
}
For example, from count3(1514, 1); I expect this:
1514 / 10 = 151; # i = 1 + 1
151 / 10 = 15; # i = 2 + 1
15 / 10 = 1; # i = 3 + 1
1 / 10 = 0; # Stop!
Unexpectedly, the function returns 13 instead of 4. Should not the function recurse only 3 times? What is the actual necessity of a base case of the same kind of count2()?
If you do not provide a return statement the result is indeterminate.
On most architectures that mean your function returns random data that happens to be present on the stack or service registers.
So, your count3() function is returning random data when n / 10 == 0 because there is no corresponding return statement.
Edit: it must be stressed that most modern compilers are able to warn when a typed function does not cover all exit points with a return statement.
For example, GCC 4.9.2 will silently accept the missing return. But if you provide it the -Wreturn-type compiler switch you will get a 'warning: control reaches end of non-void function [-Wreturn-type]' warning message. Clang 3.5.0, by comparison, will by default give you a similar warning message: 'warning: control may reach end of non-void function [-Wreturn-type]'. Personally I try to work using -Wall -pedantic unless some required 3rd party forces me to disable some specific switch.
In recursion there should be base conditions which is the building block of recursive solution. Your recursion base doesn't return any value when n==0 — so the returned value is indeterminate. So your recursion count3 fails.
Not returning value in a value-returning function is Undefined behavior. You should be warned on this behavior
Your logic is also wrong. You must return 1 when `(n >= 0 && n / 10 == 0) and
if(n / 10 != 0)
return i + count3(n / 10, i);
else if (n >= 0) return 1;
else return 0;
I don't think you need that i+count() in the recursion. Just 1+count() can work fine...
#include <stdio.h>
#include <stdlib.h>
static int count(), BASE=(10);
int main ( int argc, char *argv[] ) {
int num = (argc>1?atoi(argv[1]):9999);
BASE= (argc>2?atoi(argv[2]):BASE);
printf(" #digits in %d(base%d) is %d\n", num,BASE,count(num)); }
int count ( int num ) { return ( num>0? 1+count(num/BASE) : 0 ); }
...seems to work fine for me. For example,
bash-4.3$ ./count 987654
#digits in 987654(base10) is 6
bash-4.3$ ./count 123454321
#digits in 123454321(base10) is 9
bash-4.3$ ./count 1024 2
#digits in 1024(base2) is 11
bash-4.3$ ./count 512 2
#digits in 512(base2) is 10
I am learning C , I have written one C program which asks the user to enter a starting number and ending number , and it prints out the number stating from starting number to ending number . For example , if a user enters 5 as the starting number and 10 as the ending number , it prints out 5 6 7 8 9 10 . Here is the code : -
#include <stdio.h>
#include <stdlib.h>
int main()
{
int start ;
int end ;
int counter ;
// Asking the starting number
printf("Enter the starting number : ") ;
scanf("%d" , &start) ;
// Asking the last number
printf("Enter the last number : ") ;
scanf("%d" , &end) ;
for (counter = start ; counter <= end ; counter++)
{
printf("%d\n" , counter) ;
}
return 0;
}
The above code runs perfectly for small gap numbers (like 5 to 10 , 1000 to 1025) , But whenever I type the large gap numbers like 100 to 500 , It prints out the numbers starting from 205 to 500 , Even I scroll up I can't find the numbers from 100 to 204 . I am using Code::Blocks (version 13.12) . Can anybody figure it out whats wrong with this code ? Thanks :)
Command line display has a limited history. You are printing a large amount of numbers old lines get removed.
Print you numbers into a file using fopen() and fprintf(), so you can inspect them all.
As everybody has mentioned, your command line history has run out of its limit and hence, you cannot scroll back to the starting point. So, you're missing out the complete output.
Assuming you're on linux, run your executable like
./a.out > test1.txt
and then open and check the newly created file using vi
vim test1.txt
Hope you'll get the complete o/p.
You can make it a bit easier on yourself by printing the numbers out in sequence without newlines to confirm. That will eliminate the scrolling issue:
for (counter = start ; counter <= end ; counter++)
{
printf(" %d" , counter) ;
}
printf ("\n");
Try adding a space in your printf() instead of newline character '\n' like
printf("%d " , counter) ;
Your program will print the whole sequence, just that you are not able to see it.
Try writing the output in a file and then you will be able to see the whole output.
This thing is happening because console has a limited capacity, otherwise your code will run perfectly fine.
So i am trying to make a program that finds the factorial using def.
changing this:
print ("Please enter a number greater than or equal to 0: ")
x = int(input())
f = 1
for n in range(2, x + 1):
f = f * n
print(x,' factorial is ',f)
to
something that uses def.
maybe
def intro()
blah blah
def main()
blah
main()
Not entirely sure what you are asking. As I understand your question, you want to refactor your script so that the calculation of the factorial is a function. If so, just try this:
def factorial(x): # define factorial as a function
f = 1
for n in range(2, x + 1):
f = f * n
return f
def main(): # define another function for user input
x = int(input("Please enter a number greater than or equal to 0: "))
f = factorial(x) # call your factorial function
print(x,'factorial is',f)
if __name__ == "__main__": # not executed when imported in another script
main() # call your main function
This will define a factorial function and a main function. The if block at the bottom will execute the main function, but only if the script is interpreted directly:
~> python3 test.py
Please enter a number greater than or equal to 0: 4
4 factorial is 24
Alternatively, you can import your script into another script or an interactive session. This way it will not execute the main function, but you can call both functions as you like.
~> python3
>>> import test
>>> test.factorial(4)
24
def factorial(n): # Define a function and passing a parameter
fact = 1 # Declare a variable fact and set the initial value=1
for i in range(1,n+1,1): # Using loop for iteration
fact = fact*i
print(fact) # Print the value of fact(You can also use "return")
factorial(n) // Calling the function and passing the parameter
You can pass any number to n for getting factorial