0% found this document useful (0 votes)
31 views21 pages

Full Slip

The document contains multiple Go language programming exercises, including programs for arithmetic operations, student details management, Fibonacci series, file information retrieval, palindrome checking, employee records management, recursive digit sum, array sorting, matrix multiplication, and structure creation. Each exercise provides a complete code example and outlines specific tasks such as accepting user input, performing calculations, and displaying results. Additionally, there are exercises on implementing interfaces for shapes and using type assertions.

Uploaded by

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

Full Slip

The document contains multiple Go language programming exercises, including programs for arithmetic operations, student details management, Fibonacci series, file information retrieval, palindrome checking, employee records management, recursive digit sum, array sorting, matrix multiplication, and structure creation. Each exercise provides a complete code example and outlines specific tasks such as accepting user input, performing calculations, and displaying results. Additionally, there are exercises on implementing interfaces for shapes and using type assertions.

Uploaded by

AKNaved Shaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 21

//Slip1

A)Write a program in GO language to


accept user choice and print answers
using arithmetic operators.

package main

import (
"fmt"
)

func main() {
var choice string

fmt.Print("Enter your choice (+/-/*): ")


fmt.Scanln(&choice)

var num1, num2 float64


fmt.Print("Enter first number: ")
fmt.Scanln(&num1)
fmt.Print("Enter second number: ")
fmt.Scanln(&num2)

switch choice {
case "+":
fmt.Printf("Result of addition: %.2f\n", num1+num2)
case "-":
fmt.Printf("Result of subtraction: %.2f\n", num1-num2)
case "*":
fmt.Printf("Result of multiplication: %.2f\n", num1*num2)
case "/":
fmt.Printf("Result Of Division : %.2f\n",num1/num2)
default:
fmt.Println("Invalid choice!")
}
}

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.

package main

import (
"fmt"
)

type student struct {


rollNo int
studName string
mark1 float64
mark2 float64
mark3 float64
}

func (s *student) calculateTotal() float64 {


return s.mark1 + s.mark2 + s.mark3
}

func (s *student) calculateAverage() float64 {


return s.calculateTotal() / 3
}

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

students := make([]student, n)

for i := 0; i < n; i++ {


fmt.Printf("Enter details for student %d:\n", i+1)
fmt.Print("Roll No: ")
fmt.Scanln(&students[i].rollNo)
fmt.Print("Name: ")
fmt.Scanln(&students[i].studName)
fmt.Print("Mark 1: ")
fmt.Scanln(&students[i].mark1)
fmt.Print("Mark 2: ")
fmt.Scanln(&students[i].mark2)
fmt.Print("Mark 3: ")
fmt.Scanln(&students[i].mark3)
}

fmt.Println("\nStudent Details:")
for i, s := range students {
fmt.Printf("Student %d\n", i+1)
fmt.Printf("Roll No: %d\n", s.rollNo)
fmt.Printf("Name: %s\n", s.studName)
fmt.Printf("Mark 1: %.2f\n", s.mark1)
fmt.Printf("Mark 2: %.2f\n", s.mark2)
fmt.Printf("Mark 3: %.2f\n", s.mark3)
fmt.Printf("Total Marks: %.2f\n", s.calculateTotal())
fmt.Printf("Average Marks: %.2f\n\n", s.calculateAverage())
}
}

//slip2

A)Write a program in GO language to


print Fibonacci series of n terms.

package main

// import "fmt"

// func main() {
// var a, b, c, i int
// a = 0
// b = 1
// fmt.Println("Fibonacci Series:")
// fmt.Print(a, " ", b, " ")
// for i = 1; i <= 8; i++ {
// c = a + b
// a = b
// b = c
// fmt.Print(c, " ")
// }
// }

B)Write a program in GO language to print file information.

package main

import (
"fmt"
"os"
)

func main() {
// Prompt the user to enter the file path
fmt.Print("Enter the file path: ")
var filePath string
fmt.Scanln(&filePath)

// Open the file


file, err := os.Open(filePath)
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()

// Get file information


fileInfo, err := file.Stat()
if err != nil {
fmt.Println("Error:", err)
return
}

// Print file information


fmt.Println("File Name:", fileInfo.Name())
fmt.Println("Size (in bytes):", fileInfo.Size())
fmt.Println("Permissions:", fileInfo.Mode())
fmt.Println("Is Directory?", fileInfo.IsDir())
fmt.Println("Last Modified:", fileInfo.ModTime())
}

//slip3

A)Write a program in the GO language


using function to check whether
accepts number is palindrome or
not.

package main

// import "fmt"
// func main() {
// var num, res, sum, originalNum int
// fmt.Println("Enter The Number:")
// fmt.Scanln(&num)

// originalNum = num

// for num > 0 {


// res = num % 10
// sum = sum*10 + res
// num = num / 10
// }

// if originalNum == sum {
// fmt.Println("Number Is Palindrome")
// } else {
// fmt.Println("Number Is Not Palindrome")
// }
// }

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.

package main

import (
"fmt"
)

type employee struct {


eno int
ename string
salary float64
}

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

employees := make([]employee, n)

// Accept employee records


for i := 0; i < n; i++ {
fmt.Printf("Enter details for employee %d:\n", i+1)
fmt.Print("Employee Number: ")
fmt.Scanln(&employees[i].eno)
fmt.Print("Employee Name: ")
fmt.Scanln(&employees[i].ename)
fmt.Print("Salary: ")
fmt.Scanln(&employees[i].salary)
}
// Find maximum salary
maxSalary := employees[0].salary
for _, emp := range employees {
if emp.salary > maxSalary {
maxSalary = emp.salary
}
}

// Display employees with maximum salary


fmt.Println("\nEmployees with Maximum Salary:")
for _, emp := range employees {
if emp.salary == maxSalary {
fmt.Printf("Employee Number: %d\n", emp.eno)
fmt.Printf("Employee Name: %s\n", emp.ename)
fmt.Printf("Salary: %.2f\n\n", emp.salary)
}
}
}

slip4

A)Write a program in GO language to


print a recursive sum of digits of a
given number.

package main

import (
"fmt"
)

// Function to calculate the sum of digits recursively


func sumOfDigitsRecursive(number int) int {
// Base case: if the number is less than 10, return the number itself
if number < 10 {
return number
}
// Recursive case: sum the last digit with the sum of digits of the remaining
number
return number%10 + sumOfDigitsRecursive(number/10)
}

func main() {
// Prompt the user to enter the number
fmt.Print("Enter a number: ")
var num int
fmt.Scanln(&num)

// Calculate the recursive sum of digits


sum := sumOfDigitsRecursive(num)

// Print the result


fmt.Printf("Recursive Sum of Digits of %d is %d\n", num, sum)
}
B)Write a program in GO language
to sort array elements in
ascending order.

package main

// import (
// "fmt"
// "sort"
// )

// func main(){
// num :=[]int{22,33,4,1,60,56,78,8}

// sort.Ints(num)

// fmt.Println("After The Sorting Array",num)

// }

slip 5

A)Write a program in GO language program to create Text file

package main

import (
"fmt"
"os"
)

func main() {
// Create a file
file, err := os.Create("employees.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()

// Write some data to the file


data := []byte("Employee Number, Employee Name, Salary\n")
_, err = file.Write(data)
if err != nil {
fmt.Println("Error writing to file:", err)
return
}

fmt.Println("File 'employees.txt' created successfully.")


}

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.

package main

import (
"fmt"
"os"
)

type employee struct {


eno int
ename string
salary float64
}

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

employees := make([]employee, n)
var minSalary float64

// Accept employee records


for i := 0; i < n; i++ {
fmt.Printf("Enter details for employee %d:\n", i+1)
fmt.Print("Employee Number: ")
fmt.Scanln(&employees[i].eno)
fmt.Print("Employee Name: ")
fmt.Scanln(&employees[i].ename)
fmt.Print("Salary: ")
fmt.Scanln(&employees[i].salary)

// Initialize minSalary with the salary of the first employee


if i == 0 || employees[i].salary < minSalary {
minSalary = employees[i].salary
}
}

// Display employees with minimum salary


fmt.Println("\nEmployees with Minimum Salary:")
for _, emp := range employees {
if emp.salary == minSalary {
fmt.Printf("Employee Number: %d\n", emp.eno)
fmt.Printf("Employee Name: %s\n", emp.ename)
fmt.Printf("Salary: %.2f\n\n", emp.salary)
}
}
}

slip 6
A)Write a program in GO language to
accept two matrices and display its
multiplication

package main
import "fmt"

func multiplyMatrices(matrix1 [][]int, matrix2 [][]int) [][]int {


rows1 := len(matrix1)
cols1 := len(matrix1[0])
cols2 := 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 {
fmt.Println(row)
}
}

func main() {
var rows1, cols1, rows2, cols2 int

fmt.Println("Enter the number of rows and columns of first matrix:")


fmt.Scanln(&rows1, &cols1)
fmt.Println("Enter the number of rows and columns of second matrix:")
fmt.Scanln(&rows2, &cols2)

if cols1 != rows2 {
fmt.Println("Matrices cannot be multiplied. Number of columns of first
matrix must be equal to number of rows of second matrix.")
return
}

matrix1 := make([][]int, rows1)


matrix2 := make([][]int, rows2)

fmt.Println("Enter elements of first matrix:")


for i := 0; i < rows1; i++ {
matrix1[i] = make([]int, cols1)
for j := 0; j < cols1; j++ {
fmt.Printf("Enter element [%d][%d]: ", i, j)
fmt.Scanln(&matrix1[i][j])
}
}

fmt.Println("Enter elements of second matrix:")


for i := 0; i < rows2; i++ {
matrix2[i] = make([]int, cols2)
for j := 0; j < cols2; j++ {
fmt.Printf("Enter element [%d][%d]: ", i, j)
fmt.Scanln(&matrix2[i][j])
}
}

result := multiplyMatrices(matrix1, matrix2)

fmt.Println("Result of matrix multiplication:")


displayMatrix(result)
}

B)Write a program in GO language to


copy all elements of one array into
another using a method.

package main

import "fmt"

func copyArray(source []int, destination []int) {


for i, val := range source {
destination[i] = val
}
}

func main() {
source := []int{1, 2, 3, 4, 5}
destination := make([]int, len(source))

copyArray(source, destination)

fmt.Println("Source Array:", source)


fmt.Println("Destination Array:", destination)
}

slip7

Write a program in GO language to


create structure student. Writea
method show() whose receiver is a
pointer of struct student.

package main

// import (
// "fmt"
// )

// type student struct {


// Name string
// Age int
// Gender string
// }
// func (s *student) show() {
// fmt.Println("Name:", s.Name)
// fmt.Println("Age:", s.Age)
// fmt.Println("Gender:", s.Gender)
// }

// func main() {

// s := student{
// Name: "Sahid Shaikh",
// Age: 20,
// Gender: "Male",
// }

// s.show()
// }

slip8

A) Write a program in GO language to


accept the book details such as
BookID, Title, Author, Price. Read
and display the details of ‘n’ number
of books

package main

// import (
// "fmt"
// )

// type book struct {


// BookID int
// Title string
// Author string
// Price float64
// }

// func main() {
// var n int
// fmt.Println("Enter the number of books:")
// fmt.Scan(&n)

// books := make([]book, n)

// for i := 0; i < n; i++ {


// fmt.Printf("Enter details for book %d:\n", i+1)
// fmt.Print("BookID: ")
// fmt.Scan(&books[i].BookID)
// fmt.Print("Title: ")
// fmt.Scan(&books[i].Title)
// fmt.Print("Author: ")
// fmt.Scan(&books[i].Author)
// fmt.Print("Price: ")
// fmt.Scan(&books[i].Price)
// }
// fmt.Println("Book Details:")
// for i, b := range books {
// fmt.Printf("Book %d:\n", i+1)
// fmt.Println("BookID:", b.BookID)
// fmt.Println("Title:", b.Title)
// fmt.Println("Author:", b.Author)
// fmt.Println("Price:", b.Price)
// fmt.Println()
// }
// }

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.

package main

import (
"fmt"
"math"
)

// Shape interface
type Shape interface {
Area() float64
Perimeter() float64
}

// Circle type
type Circle struct {
Radius float64
}

// Rectangle type
type Rectangle struct {
Length float64
Width float64
}

// Method to calculate area of circle


func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}

// Method to calculate perimeter of circle


func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}

// Method to calculate area of rectangle


func (r Rectangle) Area() float64 {
return r.Length * r.Width
}

// Method to calculate perimeter of rectangle


func (r Rectangle) Perimeter() float64 {
return 2 * (r.Length + r.Width)
}

func main() {
// Create a circle with radius 5
circle := Circle{Radius: 5}
fmt.Println("Circle - Area:", circle.Area())
fmt.Println("Circle - Perimeter:", circle.Perimeter())

// Create a rectangle with length 4 and width 3


rectangle := Rectangle{Length: 4, Width: 3}
fmt.Println("Rectangle - Area:", rectangle.Area())
fmt.Println("Rectangle - Perimeter:", rectangle.Perimeter())
}

slip9
A) Write a program in GO language to
create an interface and display its
values with the help of type
assertion.

package main

import "fmt"

// Shape interface
type Shape interface {
Area() float64
}

// Circle type
type Circle struct {
Radius float64
}

// Rectangle type
type Rectangle struct {
Length float64
Width float64
}

// Method to calculate area of circle


func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}

// Method to calculate area of rectangle


func (r Rectangle) Area() float64 {
return r.Length * r.Width
}

func main() {
// Define a slice of shapes
shapes := []Shape{
Circle{Radius: 5},
Rectangle{Length: 4, Width: 3},
}
// Display areas of shapes using type assertion
for _, shape := range shapes {
switch s := shape.(type) {
case Circle:
fmt.Printf("Circle - Area: %.2f\n", s.Area())
case Rectangle:
fmt.Printf("Rectangle - Area: %.2f\n", s.Area())
}
}
}

B) Write a program in GO language


to read and write Fibonacci series
to the using channel.
package main

// import "fmt"

// func fibonacci(c chan<- int, n int) {


// a, b := 0, 1
// for i := 0; i < n; i++ {
// c <- a
// a, b = b, a+b
// }
// close(c)
// }

// func main() {
// ch := make(chan int)

// go fibonacci(ch, 10)

// for num := range ch {


// fmt.Print(num, " ")
// }
// }

slip 10

A) Write a program in GO language to


check whether the accepted number
is two digit or not.

package main

// import "fmt"

// func main(){
// var num int

// fmt.Println("Enter The Number")


// fmt.Scan(&num)

// if num>=10 && num<100{


// fmt.Println("Number Is Two Digit")
// } else {
// fmt.Println("Number Is Not Two Digit")
// }
// }

slip 12

A) Write a program in GO language to print


sum of all even and odd numbers
separately between 1 to 100.

// package main

// import "fmt"

// func swap(x *int, y *int) {


// var temp int
// temp = *x
// *x = *y
// *y = temp
// }

// func main() {
// var a, b int

// a = 10
// b = 20
// swap(&a, &b)

// fmt.Println("Swapping of 10 and 20 Is :",a,b)


// }

slip 13
A) Write a program in GO language to print
sum of all even and odd numbers
separately between 1 to 100.

package main

// import "fmt"

// func main(){
// var evensum,oddsum,i int

// for i=0;i<=100;i++{
// if i%2==0 {
// evensum+=i
// }else {
// oddsum+=i
// }
// }

// fmt.Println("Even Sum Is :",evensum)


// fmt.Println("ODD Sum Is :",oddsum)
// }

B) Write a function in GO language to


find the square of a number and
write a benchmark for it.

package main

import (
"testing"
)

// Function to find the square of a number


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

// Benchmark for Square function


func BenchmarkSquare(b *testing.B) {
// Run the Square function b.N times
for i := 0; i < b.N; i++ {
Square(10) // You can change the input number as needed
}
}

go test -bench=.

slip14

Write a program in GO language to


demonstrate working of slices (like
append, remove, copy etc.)

package main

// import "fmt"

// func main() {

// slice := []int{1, 2, 3, 4, 5}

// fmt.Println("After Appending", append(slice, 6, 7, 8))

// copySlice := make([]int, len(slice))


// copy(copySlice, slice)

// fmt.Println("After Copy", copySlice)


// removeIndex := 2
// slice = append(slice[:removeIndex], slice[removeIndex+1:]...)

// fmt.Println("After Remove",slice)

// }
slip15

package main

// import (
// "fmt"
// "time"
// )

// func main() {
// for i := 0; i <= 10; i++ {
// fmt.Println(i)
// delay(250 * time.Millisecond)
// }
// }

// func delay(duration time.Duration) {


// time.Sleep(duration)
// }

slip16

AA) Write a program in GO language to


illustrate the concept of returning
multiple values from a function. (
Add, Subtract, Multiply, Divide)
package main

// import "fmt"

// func multiple(a,b int)(int , int , int , int){

// sum:=a+b
// sub:=a-b
// mul:=a*b
// div:=a/b

// return sum,sub,mul,div

// }

// func main(){

// sum,sub,mul,div:=multiple(50,25)

// fmt.Println("Sum IS :",sum)
// fmt.Println("Sub IS :",sub)
// fmt.Println("Mul IS :",mul)
// fmt.Println("Division IS :",div)
// }
B) Write a program in GO language to
read XML file into structure and
display structure

package main

import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)

// Employee structure to represent employee information


type Employee struct {
XMLName xml.Name `xml:"employee"`
ID int `xml:"id"`
FirstName string `xml:"firstname"`
LastName string `xml:"lastname"`
Department string `xml:"department"`
}

func main() {
// Open the XML file
file, err := os.Open("employees.xml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()

// Read the XML content


xmlData, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println("Error reading file:", err)
return
}

// Create a variable to hold the decoded XML data


var employees []Employee

// Unmarshal the XML data into the employees variable


err = xml.Unmarshal(xmlData, &employees)
if err != nil {
fmt.Println("Error decoding XML:", err)
return
}

// Display the employee information


for _, emp := range employees {
fmt.Println("Employee ID:", emp.ID)
fmt.Println("First Name:", emp.FirstName)
fmt.Println("Last Name:", emp.LastName)
fmt.Println("Department:", emp.Department)
fmt.Println()
}
}
slip 18

A) Write a program in GO language to print a


multiplication table of number using
function.

package main

// import "fmt"

// func multiplication(num int){


// var i int
// for i=1;i<=10;i++{
// fmt.Println(num*i)
// }
// }

// func main(){
// multiplication(12)
// }

B) Write a program in GO language using


a user defined package calculator
that performs one calculator
operation as per the user&#39;s choice.

// calculator.go

package calculator

// Add returns the sum of two numbers


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

// Subtract returns the difference between two numbers


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

// Multiply returns the product of two numbers


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

// Divide returns the division of two numbers


func Divide(a, b float64) float64 {
if b == 0 {
panic("division by zero")
}
return a / b
}

// main.go

package main
import (
"fmt"
"calculator"
)

func main() {
var choice int
var a, b float64

fmt.Println("Choose operation:")
fmt.Println("1. Add")
fmt.Println("2. Subtract")
fmt.Println("3. Multiply")
fmt.Println("4. Divide")

fmt.Print("Enter your choice (1-4): ")


fmt.Scanln(&choice)

fmt.Print("Enter first number: ")


fmt.Scanln(&a)

fmt.Print("Enter second number: ")


fmt.Scanln(&b)

var result float64

switch choice {
case 1:
result = calculator.Add(a, b)
case 2:
result = calculator.Subtract(a, b)
case 3:
result = calculator.Multiply(a, b)
case 4:
result = calculator.Divide(a, b)
default:
fmt.Println("Invalid choice")
return
}

fmt.Println("Result:", result)
}

slip19

A) Write a program in GO language


to illustrate the function returning
multiple values(add, subtract).

package main

// import "fmt"

// func multiple(a, b int) (int, int) {


// sum := a + b
// sub := a - b
// return sum, sub
// }

// func main() {
// num1,num2:=50,20

// sum,sub:=multiple(num1,num2)

// fmt.Println("Sum Is : ",sum)
// fmt.Println("Sub Is :",sub)
// }

B) Write a program in the GO


language program to open a file in
READ only mode.

package main

import (
"fmt"
"os"
)

func main() {
// Open the file in read-only mode
file, err := os.Open("example.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()

fmt.Println("File opened successfully.")


}

slip 20
A) Write a program in Go language to
add or append content at the end of a
text file.

package main

import (
"fmt"
"os"
)

func main() {
// Open the file in append mode, create it if it doesn't exist
file, err := os.OpenFile("example.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE,
0644)
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
// Write content to the file
content := "This is new content to be added."
_, err = file.WriteString(content + "\n")
if err != nil {
fmt.Println("Error:", err)
return
}

fmt.Println("Content appended successfully.")


}

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.

package main

import (
"fmt"
)

func main() {
// Create a channel of type int
ch := make(chan int)

// Producer: send values to the channel


go func() {
defer close(ch)
for i := 1; i <= 5; i++ {
ch <- i
}
}()

// Consumer: receive values from the channel


for num := range ch {
fmt.Println("Received:", num)
}

fmt.Println("Channel closed.")
}

You might also like