GO - Practical Slips
GO - Practical Slips
package main
import "fmt"
func main() {
var num1, num2 float64
var choice string
fmt.Print("Enter the first number: ")
fmt.Scanln(&num1)
fmt.Print("Enter the second number: ")
fmt.Scanln(&num2)
fmt.Print("Enter the arithmetic operation (+, -, *, /): ")
fmt.Scanln(&choice)
switch choice {
case "+":
fmt.Printf("%.2f + %.2f = %.2f\n", num1, num2,
num1+num2)
case "-":
fmt.Printf("%.2f - %.2f = %.2f\n", num1, num2,
num1-num2)
case "*":
fmt.Printf("%.2f * %.2f = %.2f\n", num1, num2,
num1*num2)
case "/":
if num2 != 0 {
fmt.Printf("%.2f / %.2f = %.2f\n", num1, num2,
num1/num2)
} else {
fmt.Println("Error: Division by zero is not
allowed.")
}
default:
fmt.Println("Invalid arithmetic operation.")
}
}
OR
B) Write a program in GO language to accept n student details like
roll_no, stud_name, mark1,mark2, mark3. Calculate the total
and average of marks using structure.
Solution:-
package main
import "fmt"
import "fmt"
OR
B) Write a program in GO language to print file information.
Solution:-
package main
import (
"fmt"
"os"
)
func main() {
// Specify the file path
filePath := "example.txt"
// Get file information
fileInfo, err := os.Stat(filePath)
if err != nil {
fmt.Println("Error:", err)
return
}
// Print file information
fmt.Println("File Name:", fileInfo.Name())
fmt.Println("Size (bytes):", fileInfo.Size())
fmt.Println("Mode:", fileInfo.Mode())
fmt.Println("Last Modified:", fileInfo.ModTime())
fmt.Println("Is Directory:", fileInfo.IsDir())
}
****************************************************************
*******************
Slip 3
Q1. A) Write a program in the GO language using function to check
whether accepts number is palindrome or not.
Solution:
package main
import (
"fmt"
)
func main() {
var num int
fmt.Print("Enter a number: ")
fmt.Scan(&num)
if isPalindrome(num) {
fmt.Println(num, "is a palindrome.")
} else {
fmt.Println(num, "is not a palindrome.")
}
}
OR
B) Write a Program in GO language to accept n records of employee
information (eno,ename,salary) and display record of employees
having maximum salary.
Solution:-
package main
import "fmt"
Solution:
package main
import (
"fmt"
)
func main() {
// Input number from user
var num int
fmt.Print("Enter a number: ")
fmt.Scan(&num)
import (
"fmt"
"sort"
)
func main() {
var s int
fmt.Println("Enter the size of the array to sort:")
fmt.Scanln(&s)
var a = make([]int, s)
fmt.Println("Enter the array:")
for i := 0; i < s; i++ {
fmt.Printf("Enter element %d", i)
fmt.Scanln(&a[i])
}
sort.Ints(a)
fmt.Println(a)
}
**************************************************************
*********************
Slip 5
Q1. A) Write a program in GO language program to create Text file
Solution:-
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Specify the file name
fileName := "output.txt"
// Create the file
file, err := os.Create(fileName)
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
// Write content to the file
content := "Hello, this is a text file created using Go programming
language."
writer := bufio.NewWriter(file)
_, err = writer.WriteString(content)
if err != nil {
fmt.Println("Error:", err)
return
}
writer.Flush()
fmt.Println("Text file", fileName, "has been created successfully.")
}
OR
B) Write a program in GO language to accept n records of employee
information (eno,ename,salary) and display records of employees
having minimum salary.
Solution:
package main
import "fmt"
import (
"fmt"
)
func main() {
var rows1, cols1 int
fmt.Println("Enter the dimensions of the first matrix:")
fmt.Print("Number of rows: ")
fmt.Scanln(&rows1)
fmt.Print("Number of columns: ")
fmt.Scanln(&cols1)
matrix1 := make([][]int, rows1)
fmt.Println("Enter the elements of the first matrix:")
for i := range matrix1 {
matrix1[i] = make([]int, cols1)
for j := range matrix1[i] {
fmt.Printf("Enter element [%d][%d]: ", i, j)
fmt.Scanln(&matrix1[i][j])
}
}
var rows2, cols2 int
fmt.Println("\nEnter the dimensions of the second matrix:")
fmt.Print("Number of rows: ")
fmt.Scanln(&rows2)
fmt.Print("Number of columns: ")
fmt.Scanln(&cols2)
if cols1 != rows2 {
fmt.Println("Error: Number of columns in the first matrix must be
equal to the number of rows in the second matrix for multiplication.")
return
}
matrix2 := make([][]int, rows2)
fmt.Println("Enter the elements of the second matrix:")
for i := range matrix2 {
matrix2[i] = make([]int, cols2)
for j := range matrix2[i] {
fmt.Printf("Enter element [%d][%d]: ", i, j)
fmt.Scanln(&matrix2[i][j])
}
}
result := multiplyMatrices(matrix1, matrix2)
fmt.Println("\nResult of matrix multiplication:")
displayMatrix(result)
}
func multiplyMatrices(matrix1, matrix2 [][]int) [][]int {
rows1, cols1 := len(matrix1), len(matrix1[0])
_, cols2 := len(matrix2), len(matrix2[0])
result := make([][]int, rows1)
for i := range result {
result[i] = make([]int, cols2)
}
for i := 0; i < rows1; i++ {
for j := 0; j < cols2; j++ {
for k := 0; k < cols1; k++ {
result[i][j] += matrix1[i][k] * matrix2[k][j]
}
}
}
return result
}
func displayMatrix(matrix [][]int) {
for _, row := range matrix {
for _, element := range row {
fmt.Printf("%d\t", element)
}
fmt.Println()
}
}
OR
B) Write a program in GO language to copy all elements of one array
into another using a method.
Solution:
package main
import "fmt"
func main() {
// Source array
source := []int{1, 2, 3, 4, 5}
// Destination array
destination := make([]int, len(source))
package main
import (
"fmt"
)
return transposed
}
func main() {
var rows, cols int
import "fmt"
package main
import (
"fmt"
)
func main() {
var n int
fmt.Println("Enter n:- ")
fmt.Scanln(&n)
books := make([]book, n)
for i := 0; i < n; i++ {
fmt.Println("Enter book id:= ")
fmt.Scanln(&books[i].bookId)
fmt.Println("Enter Title:- ")
fmt.Scanln(&books[i].title)
fmt.Println("Enter author:- ")
fmt.Scanln(&books[i].author)
fmt.Println("Enter Price:- ")
fmt.Scanln(&books[i].price)
}
for i := 0; i < n; i++ {
fmt.Println("book id:= ", books[i].bookId)
fmt.Println("Title:- ", books[i].title)
fmt.Println("author:- ", books[i].author)
fmt.Println("Price:- ", books[i].price)
}
}
OR
B) Write a program in GO language to create an interface shape that
includes area and perimeter. Implements these methods in circle
and rectangle type.
Solution:
package main
import (
"fmt"
"math"
)
**************************************************************
*********************
Slip 9
Q1. A) Write a program in GO language using a function to check whether
the accepted number is palindrome or not.
Solution:
package main
import (
"fmt"
"strconv"
)
func main() {
// Input number from user
var num int
fmt.Print("Enter a number: ")
fmt.Scan(&num)
OR
B) Write a program in GO language to create an interface shape that
includes area and volume. Implements these methods in square
and rectangle type.
Solution:-
package main
import (
"fmt"
"math"
)
package main
import "fmt"
// Define an interface
type Shape interface {
Area() float64
}
package main
import (
"fmt"
)
**************************************************************
*********************
Slip 11
Q1. A) Write a program in GO language to check whether the accepted
number is two digit or not.
Solution:
package main
import "fmt"
func main() {
var x int
fmt.Println("Enter number:== ")
fmt.Scanln(&x)
if x >= 10 && x <= 99 {
fmt.Println("Number is double digit")
} else {
fmt.Print("Number is not a double digit")
}
}
OR
.
B) Write a program in GO language to create a buffered
channel, store few values in it and find channel
capacity and length. Read values from channel and
find modified length of a channel
Solution:
package main
import (
"fmt"
)
func main() {
// Creating a buffered channel with capacity 3
ch := make(chan int, 3)
// Storing values in the channel
ch <- 1
ch <- 2
ch <- 3
// Finding channel capacity
capacity := cap(ch)
fmt.Println("Channel capacity:", capacity)
// Finding channel length
length := len(ch)
fmt.Println("Channel length before reading:", length)
// Reading from channel
for i := 0; i < length; i++ {
fmt.Println("Value read from channel:", <-ch)
}
// Finding modified channel length
length = len(ch)
fmt.Println("Channel length after reading:", length)
}
**************************************************************
*********************
Slip 12
Q1. A) Write a program in GO language to swap two numbers using call
by reference concept
Solution:
package main
import "fmt"
func main() {
var num1, num2 int
OR
B) Write a program in GO language that creates a slice of integers,
checks numbers from the slice are even or odd and further sent to
respective go routines through channel and display values
received by goroutines.
Solution:
package main
import (
"fmt"
)
import "fmt"
func main() {
var sumEven, sumOdd int
package main
import (
"fmt"
"testing"
)
**************************************************************
*********************
Slip 14
Q1. A) Write a program in GO language to demonstrate working of slices
(like append, remove, copy etc.)
Solution:
package main
import (
"fmt"
)
func main() {
slice := []int{1, 2, 3, 4, 5}
fmt.Println("Original Slice:", slice)
slice = append(slice, 6)
fmt.Println("Slice after appending 6:", slice)
indexToRemove := 2
if indexToRemove >= 0 && indexToRemove < len(slice) {
slice = append(slice[:indexToRemove],
slice[indexToRemove+1:]...)
fmt.Println("Slice after removing element at index 2:", slice)
} else {
fmt.Println("Index out of range. Cannot remove element.")
}
copySlice := make([]int, len(slice))
copy(copySlice, slice)
fmt.Println("Copied Slice:", copySlice)
}
OR
B) Write a program in GO language using go routine and channel that
will print the sum of the squares and cubes of the individual digits
of a number. Example if number is 123 then squares = (1 * 1) + (2
* 2) + (3 * 3)
cubes = (1 * 1 * 1) + (2 * 2 * 2) + (3 * 3 * 3).
Solution:
package main
import (
"fmt"
)
package main
import "fmt"
func main() {
// Call the function and capture the returned values
sum, product := sumAndProduct(3, 4)
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
func main() {
// Open the XML file
xmlFile, err := os.Open("example.xml")
if err != nil {
fmt.Println("Error opening XML file:", err)
return
}
defer xmlFile.Close()
// Read the XML file content
byteValue, err := ioutil.ReadAll(xmlFile)
if err != nil {
fmt.Println("Error reading XML file:", err)
return
}
// Define a variable to store the decoded XML data
var person Person
// Unmarshal the XML data into the structure
err = xml.Unmarshal(byteValue, &person)
if err != nil {
fmt.Println("Error unmarshalling XML:", err)
return
}
// Print the structure
fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
fmt.Println("City:", person.City)
}
Slip 16
Q1. A) Write a program in GO language to create a user defined package to
find out the area of a rectangle.
Solution:
// rectangle.go
package geometry
// Area returns the area of a rectangle given its length and width
func Area(length, width float64) float64 {
return length * width
}
// main.go
package main
import (
"fmt"
"geometry" // Import the user-defined package
)
func main() {
length := 5.0
width := 3.0
// Calculate the area of the rectangle using the user-defined package
area := geometry.Area(length, width)
fmt.Printf("Area of the rectangle with length %.2f and width %.2f: %.2f\n",
length, width, area)
}
OR
B) Write a program in GO language that prints out the numbers from 0
to 10, waiting between 0 and 250 ms after each one using the delay
function.
Solution:
package main
import (
"fmt"
"math/rand"
"time"
)
****************************************************************
*******************
Slip 17
Q1. A) Write a program in GO language to illustrate the
concept of returning multiple values from a
function. (Add, Subtract,
Multiply, Divide)
Solution:
package main
import "fmt"
func main() {
var num1, num2 float64
import (
"fmt"
"os"
)
import "fmt"
func main() {
var number, times int
OR
B) Write a program in GO language using a user defined package
calculator that performs one calculator operation as per the
user'schoice.
Solution:
// calculator.go
package calculator
import "errors"
// Operation represents a calculator operation
type Operation int
const (
Addition Operation = iota
Subtraction
Multiplication
Division
)
// Calculate performs the specified operation on two numbers
func Calculate(operation Operation, num1, num2 float64) (float64, error) {
switch operation {
case Addition:
return num1 + num2, nil
case Subtraction:
return num1 - num2, nil
case Multiplication:
return num1 * num2, nil
case Division:
if num2 == 0 {
return 0, errors.New("division by zero")
}
return num1 / num2, nil
default:
return 0, errors.New("unsupported operation")
}
}
// main.go
package main
import (
"fmt"
"calculator" // Import the user-defined package
)
func main() {
num1 := 10.0
num2 := 5.0
operation := calculator.Addition // Change this to the desired operation
result, err := calculator.Calculate(operation, num1, num2)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Result of %.2f %s %.2f: %.2f\n", num1,
getOperationSymbol(operation), num2, result)
}
func getOperationSymbol(operation calculator.Operation) string {
switch operation {
case calculator.Addition:
return "+"
case calculator.Subtraction:
return "-"
case calculator.Multiplication:
return "*"
case calculator.Division:
return "/"
default:
return "?"
}
}
***************************************************************
*******************
Slip 19
Q1 A) Write a program in GO language to illustrate the function returning
multiple values(add, subtract).
Solution:
package main
import "fmt"
func main() {
var num1, num2 int
OR
B) Write a program in the GO language program to open a file in
READ only mode.
Solution:
package main
import (
"fmt"
"os"
)
func main() {
// Specify the file path
filePath := "example.txt"
// Open the file in read-only mode
file, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
fmt.Println("File", filePath, "opened successfully in read-only mode.")
}
*************************************************************
*********************
Slip 20
Q1. A) Write a program in Go language to add or append content at the end
of a text file.
Solution:
package main
import (
"fmt"
"os"
)
OR
B) Write a program in Go language how to create a channel and illustrate
how to close a channel using for range loop and close function.
Solution:
package main
import (
"fmt"
)