0% found this document useful (0 votes)
45 views9 pages

DART Programs

Dart Programs UI design and flutter

Uploaded by

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

DART Programs

Dart Programs UI design and flutter

Uploaded by

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

DART Programs

Running the code


1. Download the Dart SDK from here and install it on your machine.
2. Write your code in .dart extension files or clone the git repository
3. Run your code from the terminal
PowerShell 6.2.4
Copyright (c) Microsoft Corporation. All rights reserved.

PS C:\Users\Desktop dart code-file.dart


or
You can run the code on DartPad or Repl.it (choose Dart from the options).
However, keep in mind that DartPad does not allow I/O operations, while Repl.it does
:wink: Go for Repl.it

Program 1:
Create a program that asks the user to enter their name and their age. Print out a message that tells
how many years they have to be 100 years old.
Solution:
import 'dart:io';
void main()
{
stdout.write("What's your name? ");
String name = stdin.readLineSync();
print("Hi, $name! What is your age?");
int age = int.parse(stdin.readLineSync());
int yearsToHunderd = 100 - age;
print("$name, You have $yearsToHunderd years to be 100");
}

Program 2:
Ask the user for a number. Depending on whether the number is even or odd, print out an
appropriate message to the user.
Solution:
import 'dart:io';

void main() {
stdout.write("Hi, please choose a number: ");
int number = int.parse(stdin.readLineSync());

if (number % 2 == 0) {
print("Chosen number is even");
}
else {
print("Chosen number is odd");
}
}

Program 3:
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Solution:
void main()
{
List<int> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89];
for (var i in a)
{
if (i < 5)
{
print(i);
}
}
// One liner
print([for (var i in a) if (i < 5) i]);
}

Program 4:
Create a program that asks the user for a number and then prints out a list of all the divisors
of that number.
If you don’t know what a divisor is, it is a number that divides evenly into another number.
For example, 13 is a divisor of 26 because 26 / 13 has no remainder.
Solution:
import 'dart:io';
void main()
{
stdout.write("Please choose a number: ");
int number = int.parse(stdin.readLineSync());
for (var i = 1; i <= number; i++)
{
if (number % i == 0)
{
print(i);
}
}
}

Program 5:
Take two lists, for example:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]


and write a program that returns a list that contains only the elements that are common
between them (without duplicates). Make sure your program works on two lists of different
sizes.
Solution:
void main() {
List<int> a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89];
List<int> b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 89];
Set<int> c = {};

for (var i in a) {
for (var j in b) {
if (i == j) {
c.add(i);
}
}
}
print(c.toList());

// One liner using set intersections


print(Set.from(a).intersection(Set.from(b)).toList());
}
Program 6:
Ask the user for a string and print out whether this string is a palindrome or not.
A palindrome is a string that reads the same forwards and backwards.
Solution:
import 'dart:io';
void main()
{
stdout.write("Please give a word: ");
String input = stdin.readLineSync().toLowerCase();
String revInput = input.split('').reversed.join('');
// Ternary operator
input == revInput
? print("The word is palindrome")
: print("The word is not a palindrome");
}

Program 7:
Let’s say you are given a list saved in a variable:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
Write a Dart code that takes this list and makes a new list that has only the even elements of
this list in it.
Solution:
void main()
{
List<int> a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100];
int i = 0;
List<int> l = [];
for (var e in a)
{
if (++i % 2 == 0)
{
l.add(e);
}
}
print(l);
// One liner
print([for (var e in a) if (++i % 2 == 0) e]);
}

Program 8:
Make a two-player Rock-Paper-Scissors game against computer.
Ask for player's input, compare them, print out a message to the winner.
Solution:
import 'dart:io';
import 'dart:math';
void main()
{
print("Welcome to Rock, Paper, Scissors\nType 'exit' to stop the game");
final random = Random();
// Rules of the game
Map<String, String> rules = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock" };
// Initial score
int user = 0;
int comp = 0;
// Options for computer to choose
List<String> options = ["rock", "paper", "scissors"];
// Actual game
while (true)
{
String compChoice = options[random.nextInt(options.length)];
stdout.write("\nPlease choose Rock, Paper or Scissors: ");
String userChoice = stdin.readLineSync().toLowerCase();
if (userChoice == "exit")
{
print("\nYou: $user Computer: $comp\nBye Bye!");
break;
}
if (!options.contains(userChoice))
{
print("Incorrect choice");
continue;
}
else if (compChoice == userChoice)
{
print("We have a tie!");
}
else if (rules[compChoice] == userChoice)
{
print("Computer wins: $compChoice vs $userChoice");
comp += 1;
}
else if (rules[userChoice] == compChoice)
{
print("You win: $userChoice vs $compChoice");
user += 1;
}
}
}

Program 9:

Generate a random number between 1 and 100. Ask the user to guess the number, then tell
them whether they guessed too low, too high, or exactly right.

Keep track of how many guesses the user has taken, and when the game ends, print this out.

Solution:
import 'dart:io';
import 'dart:math';
void main()
{
print("Type exit to quit the game");
guessingGame();
}
guessingGame()
{
final random = Random();
int randNumber = random.nextInt(100);
int attempt = 0;
while (true)
{
attempt += 1;
stdout.write("Please choose a number between 0 and 100: ");
String chosenNumber = stdin.readLineSync();
// Make sure user does not go out of limits
if (chosenNumber.toLowerCase() == "exit")
{
print("\nBye");
break;
}
else if (int.parse(chosenNumber) > 100)
{
print("Please do not go over 100");
continue;
}
// Main logic
if (int.parse(chosenNumber) == randNumber)
{
print("Bingo! You tried $attempt times\n");
continue;
}
else if (int.parse(chosenNumber) > randNumber)
{
print("You are higher");
continue;
}
Else
{
print("You are lower");
continue;
}
}
}

Program 10:

Ask the user for a number and determine whether the number is prime or not.

Do it using a function

Solution:
import 'dart:io';
void main()
{
stdout.write("Please give us a number: ");
int chosenNumber = int.parse(stdin.readLineSync());
checkPrime(chosenNumber);
}
void checkPrime(int number)
{
// List comprehensions
List<int> a = [
for (var i = 1; i <= number; i++)
if (number % i == 0) i
];
// Check for prime
a.length == 2
? print("The chosen number is a prime")
: print("The chosen number is not a prime");
}

Program 11:

Write a program that asks the user how many Fibonnaci numbers to generate and then
generates them. Take this opportunity to think about how you can use functions.

Make sure to ask the user to enter the number of numbers in the sequence to generate.

Solution:

import 'dart:io';
void main()
{
stdout.write("How many Fibonacci numbers do you want? ");
int chosenNumber = int.parse(stdin.readLineSync());
List<int> result = fibonacciNumbers(chosenNumber);
print(result);
}
// Function to calulcate the Fibonacci numbers
List<int> fibonacciNumbers(int chosenNumber)
{
List<int> fibList = [1, 1];
for (var i = 0; i < chosenNumber; i++)
{
fibList.add(fibList[i] + fibList[i + 1]);
}
return fibList;
}

Program 12:
Write a program (function) that takes a list and returns a new list that contains all the elements of
the first list minus all the duplicates.
Solution:
import 'dart:math';
void main()
{
final random = Random();
List<int> randList = List.generate(10, (_) => random.nextInt(10));
print("Initial list is $randList\n");
print("Cleaned list is ${removeDuplicates(randList)}");
}
List<int> removeDuplicates(List<int> initialList)
{
return initialList.toSet().toList();
}

Program13:
Create a program that will play the “cows and bulls” game with the user. The game works
like this:

● Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For
every digit the user guessed correctly in the correct place, they have a “cow”. For
every digit the user guessed correctly in the wrong place is a “bull.”
● Every time the user makes a guess, tell them how many “cows” and “bulls” they have.
Once the user guesses the correct number, the game is over. Keep track of the number
of guesses the user makes throughout the game and tell the user at the end.

Solution:
import 'dart:io';
import 'dart:math';
void main()
{
/* Generate random number Range is between 1000 and 9999 */
final random = Random();
String randomNumber = (1000 + random.nextInt(9999 - 1000)).toString();
print(randomNumber);
stdout.write("Welcome to Cows and Bulls\nType 'exit' to stop the game\n");
int attempts = 0;
// Actual game
while (true)
{
int cows = 0;
int bulls = 0;
attempts += 1;
stdout.write("\nPlease choose a four digit number: ");
String chosenNumber = stdin.readLineSync();
// Conditions to check if the game is over
if (chosenNumber == randomNumber)
{
print("Bullseye! You took $attempts attempts");
break;
}
else if (chosenNumber == "exit")
{
print("Bye bye!");
break;
}
else if (chosenNumber.length != randomNumber.length)
{
print("Incorrect number. Make sure to give 4 digit number");
continue;
}
/* If a digit is in the same index increase the cow If it is somewhere else increase the bull*/
for (var i = 0; i < randomNumber.length; i++)
{
if (chosenNumber[i] == randomNumber[i])
{
cows += 1;
}
else if (randomNumber.contains(chosenNumber[i]))
{
bulls += 1;
}
}
print("\nAttempts: $attempts \nCows: $cows, Bulls: $bulls");
}
}

Program 14:

Time for some fake graphics! Let’s say we want to draw game boards that look like this:

--- --- ---


| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---

This one is 3x3 (like in tic tac toe).

Ask the user what size game board they want to draw, and draw it for them to the screen
using Dart’s print statement.

Solution:
import 'dart:io';
void main()
{
stdout.write("What square size do you want: ");
int userChoice = int.parse(stdin.readLineSync());
print("Here is a $userChoice by $userChoice board: \n");
drawBoard(userChoice);
}
void drawBoard(int squareSize)
{
// Basic building blocks
String rowLines = " ---";
String colLines = "| ";
// For loop for drawing the board
for (var i = 0; i < squareSize; i++)
{
print(rowLines * squareSize);
print(colLines * (squareSize + 1));
}
// Add the last line to the board
print("${rowLines * squareSize}\n");
}

Program 15:

In a previous exercise we explored the idea of using a list of lists as a “data structure” to
store information about a tic tac toe game. In a tic tac toe game, the “game server” needs to
know where the Xs and Os are in the board, to know whether player 1 or player 2 (or
whoever is X and O) won.
There has also been an exercise (17) about drawing the actual tic tac toe gameboard using
text characters.

The next logical step is to deal with handling user input. When a player (say player 1, who is
X) wants to place an X on the screen, they can’t just click on a terminal. So you are going to
approximate this clicking simply by asking the user for a coordinate of where they want to
place their piece.

Solution:
import 'dart:io';
void main()
{
// Empty board
List<List<String>> initialBoard = List.generate(3, (_) => List.generate(3, (_) => ' '));
drawBoard(initialBoard, 2);
}
void drawBoard(List<List<String>> board, int currentUser)
{
/* Takes an initial board and populates it either with X or with O depending on the currentUser */
var move;
currentUser == 1
? move = 'X'
: move = 'O';
stdout.write("Please choose a coordinate: ");
List choice = stdin.readLineSync().split(" ");
board[int.parse(choice[0])][int.parse(choice[1])] = move; print(board);
}

You might also like