0% found this document useful (0 votes)
14 views

New Age Programming languages

In this notes, you can know some important questions and their answers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

New Age Programming languages

In this notes, you can know some important questions and their answers.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

K.R.

MANGALAM UNIVERSITY

Practical File
New Age Programming Languages
COURSE CODE: ENSP465

SUBMITTED TO: SUBMITTED BY:


Mr. Deepak Kaushik AKSHAY DIXIT
Assistant Professor MCA Sem 3rd
(SOET) 2301560116
Sr No. Program Name Page No. Signature
1 Program 1: Implement a Go program to perform basic 4-6
arithmetic operations.
2 Program 2: Implement a program using control 7-8
structures to check if a given number is prime.

3 Program 3: Implement a program Using arrays and 9-10


strings to reverse a string entered by the user.
4 Program 4: Implement a program Using structs to store 11-12
and display employee details.
5 Program 5: Implement a program to read and display 13-14
content from a file.
6 Program 6: Implement a program Using basic functions 15-16
to calculate simple interest.
7 Program 7: Implement a program using list operations to 17-18
find the maximum number in a list.
8 Program 8: Implement a program to create a recursive 19-20
function to calculate the factorial of a number.
9 Program 9: Implement a program to determine if a given 21
input is positive, negative, or zero using pattern
matching
10 Program 10: Implement a program to display a greeting 22
message after a delay using asynchronous programming.

11 Program 11: Implement a program using sequences and 23-24


functions to compute squares.
12 Program 12: Implement a program to store and display 25-26
information using a map.
13 Program 13: Implement a program to filter out even 27-28
numbers from a given list.
14 Program 14: Implement a program to handle division by 29-30
zero using exception handling.
15 Program 15: Implement a program to merge two lists 31
into one and display the result

16 Program 16: Implement a program using basic string 32-33


operations to check if a string is a palindrome.

2
17 Program 17: Implement a program using loops and lists 34
to calculate the sum of elements.
18 Program 18: Implement a program design a `Student` 35-36
class with properties and display student details.

19 Program 19: Implement a program to demonstrate the 37-38


use of safe calls and the Elvis operator.
20 Program 20: Implement a program to display a message 39-40
after a delay using coroutines.

3
Program 1: Basic Calculator
Objective and Problem Statement: Use functions for arithmetic
operations. Implement a Go program to perform basic arithmetic
operations.
package main

import (
"fmt"
)

// Function for addition


func add(a, b float64) float64 {
return a + b
}

// Function for subtraction


func subtract(a, b float64) float64 {
return a - b
}

// Function for multiplication


func multiply(a, b float64) float64 {
return a * b
}

// Function for division


func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero is not allowed")
}
return a / b, nil

4
}

func main() {
var a, b float64
var operator string

// Taking user input


fmt.Println("Enter first number:")
fmt.Scanln(&a)

fmt.Println("Enter second number:")


fmt.Scanln(&b)

fmt.Println("Enter operator (+, -, *, /):")


fmt.Scanln(&operator)

// Perform the selected operation


switch operator {
case "+":
fmt.Printf("Result: %.2f\n", add(a, b))
case "-":
fmt.Printf("Result: %.2f\n", subtract(a, b))
case "*":
fmt.Printf("Result: %.2f\n", multiply(a, b))
case "/":
result, err := divide(a, b)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Result: %.2f\n", result)
}
default:

5
fmt.Println("Invalid operator")
}
}

Output:

6
Program 2: Check Prime Number
Objective and Problem Statement: Use control structures to check if a
given number is prime.
package main

import (
"fmt"
"math"
)

// Function to check if a number is prime


func isPrime(number int) bool {
if number <= 1 {
return false // 0 and 1 are not prime numbers
}
if number == 2 {
return true // 2 is the only even prime number
}
if number%2 == 0 {
return false // even numbers greater than 2 are not prime
}
// Check divisors from 3 to the square root of the number
for i := 3; i <= int(math.Sqrt(float64(number))); i += 2 {
if number%i == 0 {
return false
}
}
return true
}

func main() {

7
var number int

// Taking user input


fmt.Println("Enter a number:")
fmt.Scanln(&number)

// Check if the number is prime


if isPrime(number) {
fmt.Printf("%d is a prime number.\n", number)
} else {
fmt.Printf("%d is not a prime number.\n", number)
}
}

Output:

8
Program 3: String Reversal
Objective and Problem Statement: Use arrays and strings to reverse a
string entered by the user.
package main

import (
"fmt"
)

func reverseString(input string) string {


// Convert the string to a slice of runes to handle multi-byte characters
runes := []rune(input)
n := len(runes)

// Reverse the slice of runes


for i := 0; i < n/2; i++ {
runes[i], runes[n-i-1] = runes[n-i-1], runes[i]
}

// Convert the reversed slice of runes back to a string


return string(runes)
}

func main() {
var input string

// Taking user input


fmt.Println("Enter a string:")
fmt.Scanln(&input)

// Reverse the string

9
reversed := reverseString(input)

// Print the reversed string


fmt.Println("Reversed string:", reversed)
}

Output:

10
Program 4: Manage Employee Data
Objective and Problem Statement: Use structs to store and display
employee details.
package main

import (
"fmt"
)

type Employee struct {


firstName string
lastName string
age int
salary int
}

func main() {
emp6 := Employee{
firstName: "Shyam",
lastName: "Shyam",
age: 22,
salary: 20000,
}
fmt.Println("First Name:", emp6.firstName)
fmt.Println("Last Name:", emp6.lastName)
fmt.Println("Age:", emp6.age)
fmt.Printf("Salary: $%d\n", emp6.salary)
emp6.salary = 30000
fmt.Printf("New Salary: $%d", emp6.salary)
}

11
Output:

12
Program 5: Simple File Reader
Objective and Problem Statement: Read and display content from a
file.
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
// Ask the user for the file name
fmt.Print("Enter the file name to read: ")
var fileName string
fmt.Scanln(&fileName)

// Open the file


file, err := os.Open(fileName)
if err != nil {
fmt.Printf("Error opening file: %v\n", err)
return
}
defer file.Close() // Ensure the file is closed when the program ends

// Read and display the file content line by line


fmt.Println("\nFile Content:")
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}

13
// Check for scanner errors
if err := scanner.Err(); err != nil {
fmt.Printf("Error reading file: %v\n", err)
}
}

Output:

14
Program 6: Simple Interest Calculator
Objective and Problem Statement: Use basic functions to calculate
simple interest.
package main

import (
"fmt"
)

// Function to calculate simple interest


func calculateSimpleInterest(principal float64, rate float64, time float64) float64 {
return (principal * rate * time) / 100
}

func main() {
var principal, rate, time float64

// Taking user input for principal, rate, and time


fmt.Println("Enter the principal amount:")
fmt.Scanln(&principal)

fmt.Println("Enter the annual interest rate (in percentage):")


fmt.Scanln(&rate)

fmt.Println("Enter the time period (in years):")


fmt.Scanln(&time)

// Calculate simple interest


interest := calculateSimpleInterest(principal, rate, time)

// Display the result

15
fmt.Printf("The simple interest is: %.2f\n", interest)
}

Output:

16
Program 7: Find Maximum in List
Objective and Problem Statement: Use list operations to find the
maximum number in a list.
package main

import (
"fmt"
)

// Function to find the maximum number in a list


func findMax(numbers []int) int {
if len(numbers) == 0 {
panic("List is empty, cannot find the maximum.")
}

max := numbers[0]
for _, num := range numbers {
if num > max {
max = num
}
}
return max
}

func main() {
var n int
fmt.Println("Enter the number of elements in the list:")
fmt.Scanln(&n)

// Initialize a slice to store the numbers


numbers := make([]int, n)

17
// Take input for the list
fmt.Println("Enter the numbers:")
for i := 0; i < n; i++ {
fmt.Scanln(&numbers[i])
}

// Find and display the maximum number


max := findMax(numbers)
fmt.Printf("The maximum number in the list is: %d\n", max)
}

Output:

18
Program 8: Factorial Using Recursion
Objective and Problem Statement: Create a recursive function to
calculate the factorial of a number.
package main

import (
"fmt"
)

// Recursive function to calculate factorial


func factorial(n int) int {
if n == 0 || n == 1 {
return 1 // Base case: 0! = 1 and 1! = 1
}
return n * factorial(n-1) // Recursive case
}

func main() {
var num int

// Taking user input


fmt.Println("Enter a number to calculate its factorial:")
fmt.Scanln(&num)

if num < 0 {
fmt.Println("Factorial is not defined for negative numbers.")
} else {
// Calculate factorial using recursion
result := factorial(num)
fmt.Printf("The factorial of %d is: %d\n", num, result)

19
}
}

Output:

20
Program 9: Pattern Matching Example
Objective and Problem Statement: Determine if a given input is
positive, negative, or zero using pattern matching
package main

import (
"fmt"
)

func main() {
var num int

// Taking user input


fmt.Println("Enter a number:")
fmt.Scanln(&num)

// Pattern matching using switch


switch {
case num > 0:
fmt.Println("The number is positive.")
case num < 0:
fmt.Println("The number is negative.")
default:
fmt.Println("The number is zero.")
}
}

Output:

21
Program 10: Asynchronous Greeting
Objective and Problem Statement: Display a greeting message after a
delay using asynchronous programming.
package main

import (
"fmt"
"time"
)

// Function to display a greeting message


func displayGreeting() {
// Introduce a delay of 3 seconds
time.Sleep(3 * time.Second)
fmt.Println("Hello! This is your greeting message after a delay.")
}

func main() {
// Launch the displayGreeting function asynchronously using a goroutine
go displayGreeting()

// Main function continues executing other code


fmt.Println("Processing... Please wait for the greeting message.")

// Wait for the goroutine to finish before the program exits


// Adding a sleep here to keep the main program running while waiting for the goroutine
time.Sleep(4 * time.Second)
}

Output:

22
Program 11: Square of Numbers in a List
Objective and Problem Statement: Use sequences and functions to
compute squares.
package main

import (
"fmt"
)

// Function to compute the square of a number


func square(num int) int {
return num * num
}

func main() {
// Define a list of numbers
numbers := []int{1, 2, 3, 4, 5, 6}

// Compute and display the square of each number using the square function
fmt.Println("Squares of numbers in the list:")
for _, num := range numbers {
fmt.Printf("The square of %d is %d\n", num, square(num))
}
}

Output:

23
24
Program 12: Simple Map Example
Objective and Problem Statement: Store and display information
using a map.
package main

import (
"fmt"
)

func main() {
// Creating a map to store employee details
employees := make(map[int]map[string]string)

// Adding employee details to the map


employees[101] = map[string]string{
"Name": "Alice",
"Position": "Developer",
}
employees[102] = map[string]string{
"Name": "Bob",
"Position": "Manager",
}
employees[103] = map[string]string{
"Name": "Charlie",
"Position": "Designer",
}

// Displaying employee details


fmt.Println("Employee Details:")
for id, details := range employees {
fmt.Printf("Employee ID: %d\n", id)

25
for key, value := range details {
fmt.Printf("%s: %s\n", key, value)
}
fmt.Println() // Add a blank line for separation
}
}

Output:

26
Program 13: Even Numbers Filter
Objective and Problem Statement: Filter out even numbers from a
given list.
package main

import (
"fmt"
)

// Function to filter out even numbers and return only odd numbers
func filterEvenNumbers(numbers []int) []int {
var oddNumbers []int
for _, num := range numbers {
if num%2 != 0 {
oddNumbers = append(oddNumbers, num)
}
}
return oddNumbers
}

func main() {
// Define a list of numbers
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

// Filter out even numbers and get the odd numbers


oddNumbers := filterEvenNumbers(numbers)

// Display the odd numbers


fmt.Println("Odd numbers (even numbers filtered out):")
for _, num := range oddNumbers {
fmt.Println(num)

27
}
}

Output:

28
Program 14: Handle Division by Zero
Objective and Problem Statement: Handle division by zero using
exception handling.
package main

import (
"fmt"
"errors"
)

// Function to divide two numbers with error handling for division by zero
func divide(a, b float64) (float64, error) {
if b == 0 {
// Return an error if the divisor is zero
return 0, errors.New("division by zero is not allowed")
}
return a / b, nil
}

func main() {
var num1, num2 float64

// Taking user input


fmt.Println("Enter the first number (dividend):")
fmt.Scanln(&num1)

fmt.Println("Enter the second number (divisor):")


fmt.Scanln(&num2)

// Call the divide function


result, err := divide(num1, num2)

29
if err != nil {
// If there was an error (i.e., division by zero), print the error
fmt.Println("Error:", err)
} else {
// Otherwise, print the result
fmt.Printf("The result of %.2f / %.2f is %.2f\n", num1, num2, result)
}
}

Output:

30
Program 15: Combine Two Lists
Objective and Problem Statement: Merge two lists into one and
display the result
package main

import (
"fmt"
)

// Function to merge two lists (slices) into one


func mergeLists(list1, list2 []int) []int {
return append(list1, list2...) // Merge lists using append
}

func main() {
// Define two lists (slices)
list1 := []int{1, 2, 3, 4}
list2 := []int{5, 6, 7, 8}

// Merge the lists


mergedList := mergeLists(list1, list2)

// Display the merged list


fmt.Println("Merged list:", mergedList)
}

Output:

31
Program 16: Check Palindrome String
Objective and Problem Statement: c
package main

import (
"fmt"
"strings"
)

// Function to check if a string is a palindrome


func isPalindrome(str string) bool {
// Remove spaces and convert to lowercase for case-insensitive comparison
str = strings.ReplaceAll(str, " ", "")
str = strings.ToLower(str)

// Compare characters from start to end


start, end := 0, len(str)-1
for start < end {
if str[start] != str[end] {
return false
}
start++
end--
}
return true
}

func main() {
var input string

// Taking user input

32
fmt.Println("Enter a string to check if it's a palindrome:")
fmt.Scanln(&input)

// Check if the string is a palindrome


if isPalindrome(input) {
fmt.Println("The string is a palindrome.")
} else {
fmt.Println("The string is not a palindrome.")
}
}

Output:

33
Program 17: Sum of List Elements
Objective and Problem Statement: Use loops and lists to calculate the
sum of elements.
package main

import (
"fmt"
)

// Function to calculate the sum of elements in a list


func sumOfElements(numbers []int) int {
sum := 0
for _, num := range numbers {
sum += num // Add each number to sum
}
return sum
}

func main() {
// Define a list of numbers
numbers := []int{1, 2, 3, 4, 5, 6}

// Calculate the sum of elements using the sumOfElements function


result := sumOfElements(numbers)

// Display the result


fmt.Println("The sum of elements in the list is:", result)
}

Output:

34
Program 18: Create and Use Classes
Objective and Problem Statement: Design a `Student` class with
properties and display student details.
package main

import "fmt"

// Define the Student struct


type Student struct {
Name string
Age int
Grade string
RollNo int
}

// Method to display student details


func (s Student) DisplayDetails() {
fmt.Println("Student Details:")
fmt.Println("Name:", s.Name)
fmt.Println("Age:", s.Age)
fmt.Println("Grade:", s.Grade)
fmt.Println("Roll Number:", s.RollNo)
}

func main() {
// Creating an instance of Student
student1 := Student{
Name: "Alice",
Age: 22,
Grade: "A",
RollNo: 22,

35
}

// Displaying student details


student1.DisplayDetails()
}

Output:

36
Program 19: Safe Call Example
Objective and Problem Statement: Demonstrate the use of safe calls
and the Elvis operator.
package main

import "fmt"

// Define the Student struct


type Student struct {
Name string
Grade *string // Grade is a pointer to simulate a possible nil value
}

// Safe call to retrieve the student's grade or default value if nil


func GetGrade(s *Student) string {
if s == nil || s.Grade == nil {
// Elvis-like operator, return default value if nil
return "N/A"
}
return *s.Grade
}

func main() {
// Create a student with a grade
grade := "A"
student1 := Student{
Name: "Bob",
Grade: &grade,
}

// Create a student with no grade (nil)

37
student2 := Student{
Name: "Ram",
Grade: nil,
}

// Using the safe call approach with Elvis-like behavior


fmt.Printf("Student: %s, Grade: %s\n", student1.Name, GetGrade(&student1)) // Grade:
A
fmt.Printf("Student: %s, Grade: %s\n", student2.Name, GetGrade(&student2)) // Grade:
N/A
}

Output:

38
Program 20: Simple Coroutine Example
Objective and Problem Statement: Display a message after a delay
using coroutines.
package main

import (
"fmt"
"time"
)

// Function to display a message after a delay


func displayMessageAfterDelay(delay time.Duration, message string, done chan bool) {
// Simulate delay
time.Sleep(delay)
// Display the message after the delay
fmt.Println(message)
// Notify that the task is done
done <- true
}

func main() {
// Create a channel to signal when the task is done
done := make(chan bool)

// Start a goroutine to display a message after a 3-second delay


go displayMessageAfterDelay(3*time.Second, "Hello, this message was delayed!", done)

// Wait for the goroutine to finish


<-done

// Main function ends

39
fmt.Println("Main function ends.")
}

Output:

40

You might also like