Recap - Dynamic Input
Part of the Fundamentals section of Coddy's R journey — lesson 45 of 78.
Challenge
EasyRead numbers from input one at a time until the user enters "end". For each number, check if it's positive or negative. Keep track of two separate counts: one for positive numbers and one for negative numbers. Zero should not be counted in either category.
After the loop ends (when "end" is entered), print the counts on separate lines using cat() in this format:
Positive: X
Negative: YWhere X is the count of positive numbers and Y is the count of negative numbers.
For example, if the inputs are:
5
-3
0
8
-1
-7
endThe output should be:
Positive: 2
Negative: 3The positive numbers are 5 and 8 (count: 2). The negative numbers are -3, -1, and -7 (count: 3). Zero is not counted.
Try it yourself
# Read input from stdin
con <- file("stdin", "r")
# Initialize counters
positive_count <- 0
negative_count <- 0
# TODO: Write your code here
# Use a repeat loop to read numbers until "end" is entered
# For each input:
# - Check if it's "end" to break the loop
# - Convert to number and check if positive or negative
# - Update the appropriate counter (don't count zero)
# Output the results
cat("Positive:", positive_count, "\n")
cat("Negative:", negative_count, "\n")All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values