Sunday, July 17, 2016

Addition of Two Numbers in Rust

Hello friends in this article I would like to share with you how to write a program to find the sum of two numbers  using Rust Programming language. Yesterday I am attending a lecture in Mozilla Philippines office here in Makati City, Philippines. The talk is given by Sir Bob Reyes a Mozilla representative here in the Philippines he is discussing the Rust programming language I found his lecture interesting because Rust is designed for systems programming and best of all it is open source.

Rust is a programming language that is developed by Mozilla foundation the creator of Mozilla Firefox web browser one of the most popular and secure web browser in the world. I hope you will give a try to learn Rust.

In this program it will ask the user to give to two numbers and then our program will find the sum of the two numbers provided by the user.

Add me at Facebook my address  is jakerpomperada@gmail.com and jakerpomperada@yahoo.com.


My mobile number here in the Philippines is 09173084360.



Sample Program Output



Program Listing

add.rs

// Addition of Two Numbers in Rust Programming language.
// Written By: Mr. Jake R. Pomperada, MAED-IT
// July 17, 2016

use std::io::{self, Write};
use std::fmt::Display;
use std::process;

fn main() {
       println!("\n");
       println!("\tAddition of Two Numbers in Rust");
       println!("\n");

    let value1: i32 = grab_input("Enter First Number ")
        .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)))
        .trim()
        .parse()
        .unwrap_or_else(|e| exit_err(&e, 2));

    let value2: i32 = grab_input("Enter Second Number ")
        .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)))
        .trim()
        .parse()
        .unwrap_or_else(|e| exit_err(&e, 2));


    let sum = value1 + value2;
     
    println!("\n"); 
    println!("The sum of {} and {} is {}. ",value1,value2,sum);
    println!("\n"); 
    println!("End of Program");
}

fn grab_input(msg: &str) -> io::Result<String> {
    let mut buf = String::new();
    print!("{}: ", msg);
    try!(io::stdout().flush());

    try!(io::stdin().read_line(&mut buf));
    Ok(buf)
}

fn exit_err<T: Display>(msg: T, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "Error: {}", msg);
    process::exit(code)
}




No comments:

Post a Comment