0% found this document useful (0 votes)
19 views56 pages

Temperature and Area Calculation Programs

uyu

Uploaded by

drsaranyarcw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views56 pages

Temperature and Area Calculation Programs

uyu

Uploaded by

drsaranyarcw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:1

Program To Convert The Given Temperature From Fahrenheit To


Celsius And Vice Versa Depending Upon User‘S Choice.

Aim:
To write a program to convert temperature from Celsius to Fahrenheit and
vice-versa depending on user choice.

Algorithm:
1. Start.
2. Display conversion menu: (1) Celsius → Fahrenheit, (2) Fahrenheit → Celsius.
3. Read user choice choice.
4. If choice = 1 then
4.1 Prompt and read C (temperature in Celsius).
4.2 Compute F = (C × 9/5) + 32.
4.3 Display F.
5. Else if choice = 2 then
5.1 Prompt and read F (temperature in Fahrenheit).
5.2 Compute C = (F − 32) × 5/9.
5.3 Display C.
6. Else display “Invalid choice”.
7. Stop.

1
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

# Convert Celsius to Fahrenheit


celsius_to_fahrenheit <- function(celsius)

{ return((celsius * 9/5) + 32)


}

# Example: Convert 25 degrees Celsius to


Fahrenheit

celsius_temp <- 25
fahrenheit_temp <- celsius_to_fahrenheit(celsius_temp)
cat(celsius_temp, "degrees Celsius is equal to", fahrenheit_temp, "Fahrenheit\n")

2
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

25 degrees Celsius is equal to 77 Fahrenheit

3
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

# Convert Fahrenheit to Celsius


fahrenheit_to_celsius <- function(fahrenheit) {
return((fahrenheit - 32) * 5/9)
}

# Example: Convert 77 degrees Fahrenheit to


Celsius
fahrenheit_temp <- 77
celsius_temp <- fahrenheit_to_celsius(fahrenheit_temp)
cat(fahrenheit_temp, "degrees Fahrenheit is equal to", celsius_temp, "Celsius\n")

4
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

77 degrees Fahrenheit is equal to 25 Celsius

5
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:

The temperature was successfully converted between Celsius and Fahrenheit as per user choice.

6
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:2

Program, To Find The Area Of Rectangle, Square, Circle And Triangle By


Accepting Suitable Input Parameters From User.
Aim:
To calculate the area of a rectangle, square, circle, and triangle based on user input.

Algorithm:
1. Start.
2. Display shape selection menu.
3. Read user’s choice.
4. If rectangle:
o Read length and width.
o Compute area = length × width.
5. If square:
o Read side.
o Compute area = side × side.
6. If circle:
o Read radius.
o Compute area = π × radius².
7. If triangle:
o Read base and height.
o Compute area = ½ × base × height.
8. Display the calculated area.
9. Stop.

7
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

# Function to calculate the area of a rectangle


calculate_rectangle_area <- function() {
length <- [Link](readline(prompt = "Enter the length of the rectangle: "))
width <- [Link](readline(prompt = "Enter the width of the rectangle: "))
area <- length * width
cat("Area of the rectangle:", area, "\n")
}

# Function to calculate the area of a square


calculate_square_area <- function() {
side <- [Link](readline(prompt = "Enter the side length of the square: "))
area <- side * side
cat("Area of the square:", area, "\n")
}

# Function to calculate the area of a circle


calculate_circle_area <- function() {
radius <- [Link](readline(prompt = "Enter the radius of the circle: "))
area <- pi * radius^2
cat("Area of the circle:", area, "\n")
}

# Function to calculate the area of a triangle


calculate_triangle_area <- function() {
base <- [Link](readline(prompt = "Enter the base of the triangle: "))
height <- [Link](readline(prompt = "Enter the height of the triangle: "))
area <- 0.5 * base * height
cat("Area of the triangle:", area, "\n")
}

# Main program loop


while (TRUE) {
cat("\nSelect a shape to calculate its area:\n")
cat("1. Rectangle\n")
cat("2. Square\n")
cat("3. Circle\n")
cat("4. Triangle\n")
cat("5. Exit\n")

8
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

choice <- [Link](readline(prompt = "Enter your choice (1-5): "))

if (choice == 1) {
calculate_rectangle_area()
} else if (choice == 2) {
calculate_square_area()
} else if (choice == 3) {
calculate_circle_area()
} else if (choice == 4) {
calculate_triangle_area()
} else if (choice == 5) {
cat("Exiting program.\n")
break
} else {
cat("Invalid choice. Please enter a number between 1 and 5.\n")
}
}

9
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 2
Enter the side length of the square: 5
Area of the square: 25

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 1
Enter the length of the rectangle: 3
Enter the width of the rectangle: 4
Area of the rectangle: 12

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 3
Enter the radius of the circle: 5
Area of the circle: 78.53982

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit

10
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Enter your choice (1-5): 4


Enter the base of the triangle: 2
Enter the height of the triangle: 3
Area of the triangle: 3

Select a shape to calculate its area:


1. Rectangle
2. Square
3. Circle
4. Triangle
5. Exit
Enter your choice (1-5): 5
Exiting program.
>

11
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:

The program successfully calculated the area of the selected geometric shape.

12
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO: 3

Write a program to find list of even numbers from1to n using


R- Loops.

Aim:

To generate and display a list of even numbers from 1 to N using loops.

Algorithm:

1. Start.

2. Read the value of N.

3. Initialize an empty list.

4. For each number from 1 to N:

o If the number is even, add it to the list.

5. Display all even numbers.

6. Stop.

13
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

find_even_numbers <- function(n)


{
# Initialize an empty vector to store even numbers
even_numbers <- c()

# Loop from 1 to n for (i in


1:n) {
# Check if the current number is even if (i %% 2 ==
0) {
# Add the even number to the vector even_numbers <-
c(even_numbers, i)
}
}

# Return the list of even numbers


return(even_numbers)
}

# Example usage:
n_value <- 10
result <- find_even_numbers(n_value) print(result)

14
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

[1] 2 4 6 8 10 12 14 16 18

15
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:

All even numbers between 1 and N were displayed successfully.

16
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO: 4

Create a function to print squares of numbers in sequence


Aim:

To print the squares of numbers in sequence from 1 to N.

Algorithm:

1. Start.
2. Read value of N.
3. For each number from 1 to N:
o Compute square = number × number.
o Display the square.
4. Stop.

17
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

print_squares_in_sequence <- function(n) {


# Generate a sequence of numbers from 1 to n numbers <- 1:n

# Calculate the squares of these numbers squares <- numbers^2

# Print each number and its square in a formatted way for (i in


1:length(numbers)) {
cat(numbers[i], "^2 = ", squares[i], "\n")
}
}
print_squares_in_sequence(5)

18
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

1 ^2 = 1
2 ^2 = 4
3 ^2 = 9
4 ^2 = 16
5 ^2 = 25

19
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:

The squares of numbers from 1 to N were printed successfully.

20
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:5

Write a program to join columns and rows in a data frame using cbind() and
rbind() in R.

Aim:

To join data frames by columns using cbind() and by rows using rbind().

Algorithm (cbind):
1. Start.
2. Create the first data frame.
3. Create the second data frame.
4. Combine them using cbind().
5. Display the combined data frame.
6. Stop.

Algorithm (rbind):
1. Start.
2. Create the first data frame.
3. Create the second data frame.
4. Combine them using rbind().
5. Display the combined data frame.
6. Stop.

21
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

a. cbind()

# Create the first data frame

df1 <- [Link](Name = c("Alice",


"Bob"), Age = c(25, 30)
)

# Create the second data frame

df2 <- [Link](Height = c(160, 175),


Weight = c(55, 70)
)

# Combine the data frames by columns


combined_df_cols <- cbind(df1, df2)

# Print the combined data frame


print(combined_df_cols)

22
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

Name Age Height Weight

1 Alice 25 160 55

2 Bob 30 175 70

23
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

b. rbind()

# Create the first data frame df3 <-


[Link](
Name = c("Charlie", "David"), Score =
c(90, 85)
)

# Create the second data frame df4 <-


[Link](
Name = c("Eve", "Frank"), Score =
c(92, 88)
)

# Combine the data frames by rows combined_df_rows


<- rbind(df3, df4)

# Print the combined data frame


print(combined_df_rows)

24
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

Name Score

1 Charlie 90

2 David 85

3 Eve 92

4 Frank 88

Result:

Data frames were successfully combined using both cbind() and rbind().

25
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:6

Implement different String Manipulation functions in R.

Aim:

To implement and demonstrate various string manipulation functions in R.

Algorithm:
1. Start.
2. Read or define a sample string.
3. Apply functions:
o nchar(), toupper(), tolower()
o substr(), paste(), strsplit()
o sub(), gsub(), grep(), grepl()
4. Display the results of each operation.
5. Stop.

26
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

# Define a sample string


my_string <- "R Programming is FUN!"

# 1. nchar(): Get the number of characters in a string


cat("Number of characters:", nchar(my_string), "\n")

# 2. toupper(): Convert to uppercase


cat("Uppercase:", toupper(my_string), "\n")

# 3. tolower(): Convert to lowercase


cat("Lowercase:", tolower(my_string), "\n")

# 4. substr(): Extract a substring


cat("Substring (chars 3 to 10):", substr(my_string, 3, 10), "\n")

# 5. paste(): Concatenate strings


string1 <- "Hello"
string2 <- "World"
cat("Concatenated string:", paste(string1, string2), "\n")
cat("Concatenated with separator:", paste(string1, string2, sep = "-"), "\n")

# 6. strsplit(): Split a string by a delimiter


split_string <- strsplit(my_string, " ")
cat("Split string:", unlist(split_string), "\n") # unlist to view as a vector

# 7. sub(): Replace the first occurrence of a pattern


modified_string_sub <- sub("Programming", "Coding", my_string)
cat("After sub():", modified_string_sub, "\n")

# 8. gsub(): Replace all occurrences of a pattern


another_string <- "Apple pie, apple juice, apple sauce"
modified_string_gsub <- gsub("apple", "orange", another_string)
cat("After gsub():", modified_string_gsub, "\n")

# 9. grep(): Find matching patterns


matching_indices <- grep("is", my_string)
cat("Indices where 'is' is found:", matching_indices, "\n") # Returns 1 if found in the string

27
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

# 10. grepl(): Check if a pattern exists (returns logical)


contains_fun <- grepl("FUN", my_string)
cat("Does the string contain 'FUN'?", contains_fun, "\n")

28
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

Number of characters: 21
Uppercase: R PROGRAMMING IS FUN!
Lowercase: r programming is fun!
Substring (chars 3 to 10): Programm
Concatenated string: Hello World
Concatenated with separator: Hello-World
Split string: R Programming is FUN!
After sub(): R Coding is FUN!
After gsub(): Apple pie, orange juice, orange sauce
Indices where 'is' is found: 1
Does the string contain 'FUN'? TRUE

29
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:

Various string manipulation operations were performed successfully.

30
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:7

Implement different data structures in R(Vectors, Lists, Data Frames)

Aim:

To demonstrate use of vectors, lists, and data frames in R.

Algorithm:
1. Start.
2. Create numeric, character, and logical vectors.
3. Create a list with mixed data types.
4. Create a data frame with multiple columns.
5. Access and display the data structure elements.
6. Stop.

31
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Vectors
# Numeric vector
numeric_vector <- c(1, 5, 9, 13)
print(numeric_vector)

# Character vector
character_vector <- c(“apple”, “banana”, “cherry”)
print(character_vector)

# Logical vector
logical_vector <- c(TRUE, FALSE, TRUE)
print(logical_vector)

32
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

[1] 1 5 9 13
[1] "apple" "banana" "cherry"
[1] TRUE FALSE TRUE

33
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Lists
# Creating a list with different data types
my_list <- list(
name = "Alice",
age = 30,
scores = c(85, 92, 78),
is_student = TRUE
)
print(my_list)

# Accessing elements of a list


print(my_list$name)
print(my_list[[3]][2]) # Accessing the second element of the 'scores' vector

34
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

$name

[1] "Alice"

$age
[1] 30

$scores
[1] 85 92 78

$is_student
[1] TRUE

[1] "Alice"
[1] 92

35
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Data Frames

# Creating a data frame


employee_data <- [Link](
ID = c(101, 102, 103),
Name = c("John Doe", "Jane Smith", "Peter Jones"),
Department = c("HR", "IT", "Finance"),
Salary = c(60000, 75000, 62000)
)
print(employee_data)

# Accessing columns of a data frame


print(employee_data$Name)
print(employee_data[, "Department"])

# Accessing rows of a data frame


print(employee_data[2, ]) # Second row
print(employee_data[employee_data$Salary > 70000, ])
# Rows where salary is greater than 70000

36
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

ID Name Department Salary


1 101 John Doe HR 60000
2 102 Jane Smith IT 75000
3 103 Peter Jones Finance 62000

[1] "John Doe" "Jane Smith" "Peter Jones"


[1] "HR" "IT" "Finance"

ID Name Department Salary


2 102 Jane SmithIT 75000
ID Name Department Salary
2 102 Jane SmithIT75000

37
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:8

Write a program to read a csv file and analyze the data in the file in R.

Aim:
To demonstrate use of vectors, lists, and data frames in R.

Algorithm:
1. Start.
2. Create numeric, character, and logical vectors.
3. Create a list with mixed data types.
4. Create a data frame with multiple columns.
5. Access and display the data structure elements.
6. Stop.

1. Prepare your CSV file:

Ensure you have a CSV file available. For this example, assume a file named [Link]
in your working directory with the following content: Code
Name,Age,City,Score
Alice,25,New York,85
Bob,30,London,92
Charlie,22,Paris,78
David,28,Berlin,95
Eve,26,Tokyo,88

2. R Program:
Code
# Set your working directory (optional, but good practice if the file isn't in your default
directory)
# setwd("C:/Users/YourUsername/Desktop") # Replace with your actual path

# 1. Read the CSV file into a data frame


# stringsAsFactors = FALSE prevents character columns from being converted to factors
automatically
data <- [Link]("[Link]", stringsAsFactors = FALSE)

# 2. Inspect the data


# Display the first few rows print("First few
rows of the data:") head(data)

38
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

# Get the structure of the data frame (data types of columns) print("\nStructure of the data:")
str(data)

# Get summary statistics for numerical columns


print("\nSummary statistics of the data:") summary(data)

# Get the dimensions (number of rows and columns)


print("\nDimensions of the data (rows, columns):") dim(data)

# 3. Perform basic data analysis


# Calculate the mean of a numerical column (e.g., Score) mean_score <-
mean(data$Score)
print(paste("\nMean Score:", mean_score))

# Find the maximum value in a numerical column (e.g., Age) max_age <-
max(data$Age)
print(paste("Maximum Age:", max_age))

# Filter data based on a condition (e.g., people with Score > 90) high_scorers <-
subset(data, Score > 90)

print("\nIndividuals with a score greater than 90:") print(high_scorers)


# Count the occurrences of unique values in a categorical column (e.g., City) city_counts <-
table(data$City)
print("\nCount of individuals by City:")
print(city_counts)

39
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

head(data)
Name Age City Score
1 Alice 25 New York 85
2 Bob 30 London 92
3 Charlie 22 Paris 78
4 David 28 Berlin 95
5 Eve 26 Tokyo 88

str(data)
'[Link]': 5 obs. of 4 variables:
$ Name : chr "Alice" "Bob" "Charlie" "David" ...
$ Age : int 25 30 22 28 26
$ City : chr "New York" "London" "Paris" "Berlin" ...
$ Score: int 85 92 78 95 88

summary(data)
Name Age City Score
Length:5 Min. :22.0 Length:5 Min. :78.0
Class :character 1st Qu.:25.0 Class :character 1st Qu.:85.0
Mode :character Median :26.0 Mode :character Median :88.0
Mean :26.2 Mean :87.6
3rd Qu.:28.0 3rd Qu.:92.0
Max. :30.0 Max. :95.0

dim(data)
[1] 5 4

print(paste("\nMean Score:", mean_score))


[1] "\nMean Score: 87.6"

print(paste("Maximum Age:", max_age))

[1] "Maximum Age: 30"


>

"\nIndividuals with a score greater than 90:"


> print(high_scorers)

40
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Name Age City Score


2 Bob 30 London 92
4 David 28 Berlin 95

print("\nCount of individuals by City:")


[1] "\nCount of individuals by City:"
> print(city_counts)

Berlin London New York Paris Tokyo


1 1 1 1 1

41
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:
The CSV file was read and analyzed, and summary statistics and filtered data were
obtained successfully.

42
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:9

Create pie chart and bar chart using R.

[Link]

Aim:

To create a bar chart and a pie chart using R.

Algorithm (Bar Chart):


1. Start.
2. Define data values and labels.
3. Use barplot() to generate the chart.
4. Stop.

Algorithm (Pie Chart):


1. Start.
2. Define category values and labels.
3. Use pie() to generate the pie chart.
4. Stop

43
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

A <- c(17, 2, 8, 13, 1, 22)


B <- c("Jan", "feb", "Mar", "Apr", "May", "Jun")

barplot(A, [Link] = B, xlab ="Month",


ylab ="Articles", col ="green",
main ="GeeksforGeeks-Article chart")

44
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

45
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

[Link]

expenditure <- c(600, 300, 150, 100, 200)

result <- pie(expenditure,


main = "Monthly Expenditure Breakdown",
labels = c("Housing", "Food", "Cloths", "Entertainment", "Other")
)

print(result)

46
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

47
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:

Bar chart and pie chart were generated successfully.

48
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:10

Program to find factorial of the given number using recursive function.

Aim:
To calculate the factorial of a number using a recursive function in R.

Algorithm:
1. Start.
2. Define recursive function factorial(n):
o If n = 0 or n = 1 → return 1.
o Else return n × factorial(n − 1).
3. Read input number.
4. Call factorial() function.
5. Display result.
6. Stop.

49
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

rec_fac <- function(x)


{
if(x==0 || x==1)
{
return(1)
}
else
{
return(x*rec_fac(x-1))
}
}

rec_fac(3)

50
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

[1] 6

51
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:

The factorial of the number was calculated using recursion successfully.

52
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

EX NO:11

Write a R program to count the number of even and odd numbers from array of N
numbers

Aim:
To count how many even and odd numbers are present in a given set of N numbers.

Algorithm:
1. Start.
2. Read the array of N numbers.
3. Initialize even_count = 0 and odd_count = 0.
4. For each number in the array:
o If number is even → even_count++,
o Else → odd_count++.
5. Display both counts.
6. Stop.

53
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

# Function to count even and odd numbers in a vector


count_even_odd <- function(numbers) {
even_count <- 0
odd_count <- 0

for (num in numbers) {


if (num %% 2 == 0) {
even_count <- even_count + 1
} else {
odd_count <- odd_count + 1
}
}

return(list(even = even_count, odd = odd_count))


}

# Example usage:
# Create a sample array (vector in R) of numbers
my_numbers <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)

# Call the function to count even and odd numbers


counts <- count_even_odd(my_numbers)

# Print the results


cat("Number of even numbers:", counts$even, "\n")
cat("Number of odd numbers:", counts$odd, "\n")

54
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Output:

Number of even numbers: 7


Number of odd numbers: 8

55
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN

Result:

The program successfully counted and displayed the number of even and odd values.

56

Common questions

Powered by AI

The R program reads a CSV file, storing it as a data frame while preventing automatic conversion of character columns to factors. It offers several data analysis capabilities: head() shows initial data rows, str() outlines the data structure, and summary() provides statistical summaries for numerical columns. The dim() function retrieves data frame dimensions. For enhanced analysis, it calculates the mean of the 'Score' column and identifies the maximum age using mean() and max() functions. Filtering for records meeting conditions (e.g., Score > 90) and counting categorical occurrences (e.g., by City) utilize subset() and table() functions for insightful data segmentation and aggregation .

The use of varied data structures provides considerable flexibility and robustness in R. Vectors, as basic homogeneous storage, support straightforward numeric, character, or logical operations, crucial for scripting and iterative processes. Lists enable complex, mixed-type storage, essential for heterogenous data sets and nested structures. Meanwhile, data frames offer tabular views necessary for structured data analysis akin to databases and spreadsheets, facilitating operations like filtering, aggregation, and summary statistics. These structures thus underpin agile data analysis workflows by offering tailored solutions for data manipulation, visualization, and processing, impacting efficiency and clarity in data-driven projects .

The algorithm starts by reading the value of N and initializing an empty list for even numbers. It iterates through numbers 1 to N, checking for evenness by verifying if (i %% 2 == 0). Even numbers satisfying this condition are appended to the list. Once the loop completes, the list of even numbers is printed. The computational efficiency is optimal for moderate N values due to direct element-wise checking and appending. However, as N grows large, the algorithm remains linear in complexity O(N), considering throughput builds directly from 1 to N iterations without complex nested operations .

The R string manipulation program demonstrates various functions: nchar() for length, toupper() and tolower() for case conversion, substr() for substring extraction, paste() for concatenation, strsplit() for splitting strings, sub()/gsub() for substitution, grep() and grepl() for pattern matching. These functions facilitate complex data processing tasks: nchar() and case conversions are useful for text standardization; substr() and strsplit() are crucial for parsing and extracting information; paste() supports data concatenation; and substitution functions enable data cleaning by replacing text. Pattern matching functions like grep() and grepl() are essential for filtering datasets based on text criteria .

Data binding in R employs cbind() and rbind() to combine data frames by columns and rows respectively. cbind() takes two data frames sharing the same number of rows and consolidates them horizontally, adding new variables to the existing dataset. Conversely, rbind() appends data frames with identical column structures vertically, adding additional observations. While both functions facilitate data structure integration, their choice depends on whether the data expansion is meant to introduce new data in separate variables or extend existing variables with further observations .

The temperature conversion is implemented through two R functions: one for Celsius to Fahrenheit and another for Fahrenheit to Celsius. The function celsius_to_fahrenheit(celsius) converts temperatures by applying the formula F = (C × 9/5) + 32, while fahrenheit_to_celsius(fahrenheit) converts using C = (F − 32) × 5/9. Correctness is ensured by these mathematically established conversion formulas and direct usage in the functions, allowing for precise conversion without manual error .

The function print_squares_in_sequence(n) efficiently calculates and displays squares by generating a sequence from 1 to N, then computing squares as numbers^2 in a single vectorized operation. This balances computational load by bypassing explicit loops for each calculation, leveraging R's vectorization to reduce overhead. For ease of use, the function then iterates over the resulting vector for formatted output, blending efficient computation with easily interpretable results. This approach facilitates simple interaction and seamless processing within a reasonable range for N, avoiding iterative bottlenecks .

The geometric area calculation program utilizes a control flow structure centered around a main menu that loops to offer continuous user interaction until exit is chosen. By prompting the user to select a shape (rectangular, square, circle, or triangle), and reading necessary parameters, it guides users through step-by-step input processes for calculating shape-specific areas. The use of conditional structures (if-else) directly manages input conditions and computation choices. This design aids in improving user experience by providing clear instructions, feedback, and the ability to make multiple calculations in a single session .

The algorithm outlined starts by displaying a menu of conversion choices (Celsius to Fahrenheit and Fahrenheit to Celsius). It then reads the user's choice. If the choice is 1, it prompts the user for a temperature in Celsius, computes the Fahrenheit equivalent using the formula F = (C × 9/5) + 32, and displays the result. If the choice is 2, it prompts for a temperature in Fahrenheit, converts it using C = (F − 32) × 5/9, and displays the Celsius result. If the user input does not match the options, it displays an 'Invalid choice' message, ensuring the program handles unexpected input gracefully .

The program facilitates flexibility by allowing the choice between different shapes (rectangle, square, circle, triangle) and computes area based on user-provided dimensions. For each shape, the required parameters (length and width for a rectangle, side for a square, radius for a circle, and base and height for a triangle) are read from the user. It then performs specific calculations for each shape using appropriate mathematical formulas: area = length × width for rectangles, area = side^2 for squares, area = π × radius^2 for circles, and area = 0.5 × base × height for triangles. This modular approach ensures accuracy by isolating and using specific computations for different shapes .

You might also like