Slip Analysis Go Programming _________________________________________________________________________ _________________________________________________________________________ Slip-1 A) Write a program in GO language to accept user choice and print answers using arithmetic operators. package main import "fmt" func main() { var n1, n2, sum, sub, mult, div, rem int var ch int fmt.Print("Enter two numbers: ") fmt.Scanf("%d %d", &n1, &n2) fmt.Print("\n*****ARITHMETIC OPERATIONS*****\n") fmt.Println("1. Addition(+)\n2. Subtraction(-)\n3. Multiplication(*)\n4. Division(/)\n5. Remainder") fmt.Print("\nEnter choice (operation): ") fmt.Scanf("%d", &ch) switch ch { case 1: sum = n1 + n2 fmt.Println("Addition Result:", sum) case 2: sub = n1 - n2 fmt.Println("Subtraction Result:", sub) case 3: mult = n1 * n2 fmt.Println("Multiplication Result:", mult) case 4: if n2 != 0 { div = n1 / n2 fmt.Println("Division Result:", div) } else { fmt.Println("Cannot divide by zero.") } case 5: rem = n1 % n2 fmt.Println("Moduulus/Remainder:", rem) 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 { roll_no int stud_name string mark1 int mark2 int mark3 int total int average float64 } func main() { var n int fmt.Printf("\nEnter number of students : ") fmt.Scanf("%d", &n) s1 := make([]student, n) fmt.Printf("\nEnter the details of students\n") for i := 0; i < n; i++ { fmt.Printf("Enter roll no: ") fmt.Scanf("%d", &s1[i].roll_no) fmt.Printf("Enter name: ") fmt.Scanf("%s", &s1[i].stud_name) fmt.Printf("Enter 3 subject marks: ") fmt.Scanf("%d %d %d", &s1[i].mark1, &s1[i].mark2, &s1[i].mark3) s1[i].total = s1[i].mark1 + s1[i].mark2 + s1[i].mark3 s1[i].average = float64(s1[i].total) / 3.0 } fmt.Printf("\nStudent Details and Results:\n") for i := 0; i < n; i++ { fmt.Printf("\nStudent %d:\n", i+1) fmt.Printf("Roll Number: %d\n", s1[i].roll_no) fmt.Printf("Student Name: %s\n", s1[i].stud_name) fmt.Printf("Mark1: %d\n", s1[i].mark1) fmt.Printf("Mark2: %d\n", s1[i].mark2) fmt.Printf("Mark3: %d\n", s1[i].mark3) fmt.Printf("Total: %d\n", s1[i].total) fmt.Printf("Average: %.2f\n", s1[i].average) } } ------------------------------------------------------------------------- ----------------------------------------------------------------------- Slip-2 A) Write a program in GO language to print Fibonacci series of n terms. package main import "fmt" func main(){ var n,tn int fmt.Printf("Enter a number up to which you want the Fibonacci series:") fmt.Scanf("%d",&n) var t1,t2=0,1 tn=t1+t2 fmt.Printf("%d %d",t1,t2) for i:=3;i<=n;i++{ fmt.Printf(" %d",tn) t1=t2 t2=tn tn=t1+t2 } } OR B) Write a program in GO language to print file information. ------------------------------------------------------------------------- ----------------------------------------------------------------------- Slip-3 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 n, ans int fmt.Print("Enter a number:") fmt.Scanf("%d", &n) ans = palindrome(n) if ans == 1 { fmt.Printf("%d is Palindrome", n) } else { fmt.Printf("%d is not Palindrome", n) } } func palindrome(n int) int { var rem, rev, store int rev = 0 store = n for n > 0 { rem = n % 10 rev = rev*10 + rem n = n / 10 } if rev == store { return 1 } else { return 0 } } 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.(s3,s5) ------------------------------------------------------------------------- ----------------------------------------------------------------------- Slip-4 A) Write a program in GO language to print a recursive sum of digits of a given number. import "fmt" func add(n int) int { if n == 0 { return 0 } return n%10 + add(n/10) } func main() { var n int fmt.Print("Enter a number:") fmt.Scanf("%d", &n) fmt.Printf("Sum of digits of %d is %d", n, add(n)) } OR B) Write a program in GO language to sort array elements in ascending order. package main import ( "fmt" "sort" ) func main() { var n int fmt.Print("Enter the size of the array: ") fmt.Scanf("%d", &n) array := make([]int, n) fmt.Printf("Enter %d array elements:\n", n) for i := 0; i < n; i++ { fmt.Scanf("%d", &array[i]) } sort.Ints(array) fmt.Println("\nSorted array in ascending order:") for i := 0; i < n; i++ { fmt.Printf("%d ", array[i]) } fmt.Println() } ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-5 A) Write a program in GO language program to create Text file. package main import "log" import "os" func main() { emptyFile,err:=os.Create("empty.txt") if err!=nil{ log.Fatal(err) } log.Println(emptyFile) log.Println("Checked your folder for created empty file") emptyFile.Close() } 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. ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-6 A) Write a program in GO language to accept two matrices and display its multiplication B) Write a program in GO language to copy all elements of one array into another using a method. package main import "fmt" type Array []int //method with non-struct type receiver func (a Array) Copy(b Array) { for i := 0; i < len(a); i++ { b[i] = a[i] } } func main() { a:= Array{1, 2, 3, 4, 5} b:= make(Array, len(a)) a.Copy(b) fmt.Println("Original array 'a' is:",a) fmt.Println("New array 'b' after copying:",b) } ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-7 A) Write a program in GO language to accept one matrix and display its transpose. B) Write a program in GO language to create structure student. Write a method show() whose receiver is a pointer of struct student. package main import "fmt" type Student struct { name string roll int marks float64 } func (s *Student) show() { fmt.Printf("Name: %s\n", s.name) fmt.Printf("Age: %d\n", s.roll) fmt.Printf("Grade: %.2f\n", s.marks) } func main() { s1 := Student{ name: "Ram", roll: 20, marks: 85.5, } s1.show() } ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-8 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 Print("Enter the number of books: ") Scanln(&n) books := make([]Book, n) for i := 0; i < n; i++ { Printf("\nEnter details for Book %d:\n", i+1) Print("BookID: ") Scanln(&books[i].BookID) Print("Title: ") Scanln(&books[i].Title) Print("Author: ") Scanln(&books[i].Author) Print("Price: ") Scanln(&books[i].Price) } Println("\nDetails of all books:") for i, book := range books { Printf("\nBook %d:\n", i+1) Println("BookID:", book.BookID) Println("Title:", book.Title) Println("Author:", book.Author) Println("Price:", book.Price) } } 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" ) type Shape interface { area() float64 perimeter() float64 } type Circle struct { radius float64 } func (c Circle) area() float64 { return math.Pi * c.radius * c.radius } func (c Circle) perimeter() float64 { return 2 * math.Pi * c.radius } type Rectangle struct { length float64 width float64 } func (r Rectangle) area() float64 { return r.length * r.width } func (r Rectangle) perimeter() float64 { return 2 * (r.length + r.width) } func main() { var r, l, b float64 Print("Enter radius of the circle: ") Scanln(&r) Print("Enter length & breadth of the rectangle: ") Scanln(&l,&b) c1:= Circle{radius: r} Println("\nArea of circle:", c1.area()) Println("Perimeter of circle:", c1.perimeter()) r1:= Rectangle{length: l, width: b} Println("\nArea of Rectangle:", r1.area()) Println("Perimeter of Rectangle:", r1.perimeter()) } ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-9 A) Write a program in GO language using a function to check whether the accepted number is palindrome or not.(repeadted in slip 3) package main import "fmt" func main() { var n, ans int fmt.Print("Enter a number:") fmt.Scanf("%d", &n) ans = palindrome(n) if ans == 1 { fmt.Printf("%d is Palindrome", n) } else { fmt.Printf("%d is not Palindrome", n) } } func palindrome(n int) int { var rem, rev, store int rev = 0 store = n for n > 0 { rem = n % 10 rev = rev*10 + rem n = n / 10 } if rev == store { return 1 } else { return 0 } } B) Write a program in GO language to create an interface shape thatincludes area and volume. Implements these methods in square and rectangle type. ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-10 A) Write a program in GO language to create an interface and display its values with the help of type assertion. B) Write a program in GO language to read and write Fibonacci series to the using channel. package main import "fmt" // Function to generate Fibonacci series and send it to a channel func fibonacci(ch chan<- int, n int) { t1, t2 := 0, 1 for i := 0; i < n; i++ { ch <- t1 temp := t1 t1 = t2 t2 = temp + t2 } close(ch) } // Function to receive and print Fibonacci series from a channel func receiveFibonacci(ch <-chan int) { fmt.Print("Fibonacci series:") for n := range ch { fmt.Print(n," ") } } func main() { ch := make(chan int) n := 10 go fibonacci(ch, n) receiveFibonacci(ch) } ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-11 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.Print("Enter a number: ") fmt.Scanln(&num) if num >= 10 && num <= 99 { fmt.Println("The number", num, "is a two-digit number.") } else { fmt.Println("The number", num, "is not a two-digit number.") } } 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 ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-12 A) Write a program in GO language to swap two numbers using call by reference concept package main import "fmt" func swap(x *int, y *int) { temp := *x *x = *y *y = temp } func main() { var n1, n2 int fmt.Print("Enter two numbers: ") fmt.Scanln(&n1,&n2) fmt.Println("Before swapping n1=",n1," and n2=",n2) swap(&n1, &n2) fmt.Println("After swapping n1=",n1," and n2=",n2) } 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. ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- 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() { sumEven, sumOdd := 0, 0 for i := 1; i <= 100; i++ { if i%2 == 0 { sumEven += i } else { sumOdd += i } } fmt.Println("Sum of all even numbers between 1 to 100:", sumEven) fmt.Println("Sum of all odd numbers between1 to 100:", sumOdd) } B) Write a function in GO language to find the square of a number and write a benchmark for it. ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-14 A) Write a program in GO language to demonstrate working of slices (like append, remove, copy etc.) package main import "fmt" func main() { s1 := []int{1, 2, 3, 4, 5} fmt.Println("Original slice:",s1) s1 = append(s1, 6) fmt.Println("After appending:", s1) s2 := make([]int, len(s1)) copy(s2, s1) fmt.Println("Copied slice:",s2) r:= 2 s1 = append(s1[:r], s1[r+1:]...) fmt.Println("After removing:", s1) } 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). ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-15 A) Write a program in GO language to demonstrate function return multiple values. package main import. "fmt" func calc(a, b int)(int,int,int){ return a+b, a-b, a*b } func main(){ var a,b,a1,a2,a3 int Printf("Enter two numbers:") Scanf("%d%d",&a,&b) a1,a2,a3=calc(a,b) Printf("\nSum=%d",a1) Printf("\nSubtraction=%d",a2) Printf("\nMultiplication=%d",a3) } B) Write a program in GO language to read XML file into structure and display structure ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-16 A) Write a program in GO language to create a user defined package to find out the area of a rectangle. [ main.go is as follows] package main import ( "fmt" "AniruddhaGo/mycalculator" ) func main() { var num1, num2 float64 var operator rune fmt.Println("Enter first number:") fmt.Scanln(&num1) fmt.Println("Enter second number:") fmt.Scanln(&num2) fmt.Println("Enter operator (+, -, *, /):") fmt.Scanf("%c", &operator) result := mycalculator.Calculate(num1, num2, operator) fmt.Printf("Result: %.2f\n", result) } [ calculator.go is as follows ] package mycalculator func area(l,b float64) float64 { return l*b } B) Write a program in GO language that prints out the numbers from0 to 10, waiting between 0 and 250 ms after each one using the delay function. package main import ( "fmt" "time" ) func main() { for i := 0; i <= 10; i++ { fmt.Println(i) delay(250 * time.Millisecond) // Wait for 250 milliseconds } } func delay(duration time.Duration) { time.Sleep(duration) } ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-17 A) 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 calc(a, b int) (int, int, int, float64) { return a+b, a-b, a*b, float64(a)/float64(b) } func main() { var a, b, sum, sub, mult int var div float64 fmt.Print("Enter two numbers:") fmt.Scanf("%d %d", &a, &b) sum, sub, mult, div = calc(a, b) fmt.Printf("\nSum = %d\n", sum) fmt.Printf("Subtraction = %d\n", sub) fmt.Printf("Multiplication = %d\n", mult) fmt.Printf("Division = %.2f\n", div) } B) Write a program in GO language to add or append content at the end of a text file. ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-18 A) Write a program in GO language to print a multiplication table of number using function. package main import. "fmt" func mult(n int) { Printf("Multiplication table of %d:\n", n) for i:=1; i<=10; i++ { Printf("%d x %d = %d\n", n, i, n*i) } } func main() { var n int Print("Enter the number for multiplication table: ") Scanln(&n) mult(n) } B) Write a program in GO language using a user defined package calculator that performs one calculator operation as per the user's. ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Slip-19 A) Write a program in GO language to illustrate the function returning multiple values(add, subtract). package main import "fmt" func calc(a, b int) (int, int) { return a+b, a-b } func main() { var a, b, sum, sub int fmt.Print("Enter two numbers:") fmt.Scanf("%d %d", &a, &b) sum, sub= calc(a, b) fmt.Printf("\nSum = %d\n", sum) fmt.Printf("Subtraction = %d\n", 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() { filename := "file1.txt" // Specify the name of the file you want to open f, err := os.OpenFile(filename, os.O_RDONLY, 0666) // Opens the file in read-only mode if err != nil { fmt.Println(err) return } defer f.Close() // Reading file content data := make([]byte, 100) n, err := f.Read(data) if err != nil { fmt.Println(err) return } fmt.Printf("Read %d bytes: %s\n", n, data[:n]) } ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- 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() { msg := "India is my country & I have added this content at the end of the file." filename := "file1.txt" f, err := os.OpenFile(filename, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660) if err != nil { fmt.Println(err) os.Exit(1) // Using 1 instead of -1 for exit status } defer f.Close() fmt.Fprintf(f, "%s\n", msg) } 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() { ch := make(chan int) go func() { for i := 1; i <= 5; i++ { ch <- i // Sending integers to the channel } close(ch) }() for num := range ch { fmt.Println("Received:", num) } } ------------------------------------------------------------------------- ------------------------------------------------------------------------- --------- Iot Programs (Slip No: 1,3,5,8,9,16) | ------------------------+ a. Draw block diagram /pin diagram of Raspberry-Pi/Beagle board/Arduino Uno board interfacing with IR Sensor/Temperature Sensor/Camera. (Internal Examiner assign any one option for board and interface device and respective interface programming option) b. WAP in python/C++ language to blink LED. c. Write down the observations on Input and Output d. Write down the Result and Conclusion import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) SWITCH1=21 LED1=15 GPIO.setup(SWITCH1,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.setup(LED1,GPIO.OUT) while True: new_input_state=GPIO.input(SWITCH1) if new_input_state==False: GPIO.output (LED1, True) else: GPIO.output (LED1, False) ------------------------------------------------------------------------- ------------------------------------------------------------------------- ---------- (Slip No: 2,7,10,11,14,18,19)| -----------------------------+ a. Draw block diagram /pin diagram of Raspberry-Pi/Beagle board/Arduino Uno board interfacing with IR Sensor/Temperature Sensor/Camera. (Internal Examiner assign any one option for board and interface device and respective interface programming option) b. WAP in python/C++ language to turn ON/OFF buzzer. c. Write down the observations on Input and Output d. Write down the Result and Conclusion import RPi.GPIO as GPIO import time GPIO.setmode (GPIO.BCM) GPIO.setwarnings (False) PIR_input=21 BUZZ=20 GPIO.setup(PIR_input,GPIO.IN) GPIO.setup(BUZZ,GPIO.OUT) GPIO.output(BUZZ,GPIO.LOW) while True: if(GPIO.input(PIR_input)): GPIO.output(BUZZ,GPIO.HIGH) time.sleep(3) else: GPIO.output(BUZZ,GPIO.LOW) time.sleep(3) ------------------------------------------------------------------------- ------------------------------------------------------------------------- ---------- (Slip No: 4,6,12,13,15,17,20)| -----------------------------+ a. Draw block diagram /pin diagram of Raspberry-Pi Beagle board/Arduino Uno board interfacing with IR Sensor/Temperature Sensor/Camera. (Internal Examiner assign any one option for board and interface device and respective interface programming option) b. WAP in python/C++ language to toggle two LED’s. c. Write down the observations on Input and Output d. Write down the Result and Conclusion import RPi.GPIO as GPIO import time GPIO.setmode (GPIO.BCM) GPIO.setwarnings (False) LED1=14 LED2=15 while True: GPIO.setup(LED1, GPIO.OUT) GPIO.setup(LED2, GPIO.OUT) time.sleep(1) GPIO.output(LED1, True) GPIO.output(LED2, False) time.sleep(1) GPIO.output(LED1, False) GPIO.output(LED2, True) time.sleep(1) GPIO.output(LED1, True) GPIO.output(LED2, False) time.sleep(1)
Write, Run & Share Go code online using OneCompiler's Go online compiler for free. It's one of the robust, feature-rich online compilers for Go language, running on the latest version 1.10.2. Getting started with the OneCompiler's Go compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as GO
and start coding.
OneCompiler's Go online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Go program which takes name as input and prints hello message with your name.
package main
import "fmt"
func main() {
var name string
fmt.Scanf("%s", &name)
fmt.Printf("Hello %s", name)
}
Go language is an open-source, statically typed programming language by Google. Go is highly recommended for creation of highly scalable and available web applications.
Some of the products developed using Go are Kubernetes, Docker, Dropbox, Infoblox etc.
Data type | Description | Size | Range |
---|---|---|---|
uint8 | 8-bit unsigned integer | 1 byte | 0 to 255 |
int8 | 8-bit signed integer | 1 byte | -128 to 127 |
int16 | 16-bit signed integer | 2 bytes | -32768 to 32767 |
unit16 | 16-bit unsigned integer | 2 bytes | 0 to 65,535 |
int32 | 32-bit signed integer | 4 bytes | -2,147,483,648 to 2,147,483,647 |
uint32 | 32-bit unsigned integer | 4 bytes | 0 to 4,294,967,295 |
int64 | 64-bit signed integer | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
uint64 | 64-bit unsigned integer | 8 bytes | 0 to 18,446,744,073,709,551,615 |
float32 | 32-bit signed floating point number | 4 bytes | ±1.5e-45 to ±3.4e38 |
float | 64-bit signed floating point number | 8 bytes | ±5.0e-324 to ±1.7e308 |
string | sequence of immutable text | ||
bool | Stores either true or false | 1 byte | True or false |
Variable is a name given to the storage area in order to manipulate them in our programs.
var varible-names datatype;
When ever you want to perform a set of operations based on a condition or set of conditions then If or IF-ELSE or Nested If-Elif-Else are used.
if(conditional-expression) {
// code
}
if(conditional-expression) {
// code
} else {
// code
}
if(conditional-expression) {
// code
} else if(conditional-expression) {
// code
} else {
// code
}
For loop is used to iterate a set of statements based on a condition.
for Initialization; Condition; Increment/decrement {
// code
}
Switch is an alternative to If-Else-If ladder.
switch conditional-expression {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
// code to be executed when all the above cases are not matched;
}
Go doesn't have while or do-while loops like in C.
Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity.
func functionname(parameter-name type) returntype {
//code
}