Snippets Collections
// Author : Khadiza Sultana
// Date : 1/4/2025
#include <iostream>
#include <vector>
using namespace std;

int search(vector<int>& nums, int target) {
    int st = 0, end = nums.size() - 1;
    while (st <= end) {
        int mid = st + (end - st) / 2;
        if (nums[mid] == target) {
            return mid;
        }
        if (nums[st] <= nums[mid]) { // Left half is sorted
            if (nums[st] <= target && target <= nums[mid]) {
                end = mid - 1;
            } else {
                st = mid + 1;
            }
        } else { // Right half is sorted
            if (nums[mid] <= target && target <= nums[end]) {
                st = mid + 1;
            } else {
                end = mid - 1;
            }
        }
    }
    return -1;
}

int main() {
    vector<int> nums = {4, 5, 6, 7, 0, 1, 2};
    int target = 0;

    int result = search(nums, target);

    if (result != -1) {
        cout << "Target " << target << " found at index: " << result << endl;
    } else {
        cout << "Target " << target << " not found in the array." << endl;
    }

    return 0;
}
// Author : Khadiza Sultana
// Date : 1/4/2025
#include<iostream>
#include<vector>
using namespace std;

int binarySearch(vector<int>&arr, int tar) { // practical implementation
    int n = arr.size();
    int st = 0, end = n-1;
    while(st <= end) {
        int mid = st + (end-st)/2; // not using (st+end)/2 to avoid integer overflow
        if (tar > arr[mid]) {
            st = mid+1;
        }
        else if (tar < arr[mid]) {
            end = mid-1;
        }
        else {
            return mid;
        }
    }
    return -1;
}

int binarySearch2(vector<int>&arr, int tar, int st, int end) { // recursive implementation
    if (st > end) { // base case
        return -1;
    }
    int mid = st + (end-st)/2;
    if (tar > arr[mid]) {
        binarySearch2(arr, tar, mid+1, end);
    }
    else if (tar < arr[mid]) {
        binarySearch2(arr, tar, st, mid-1);
    }
    else {
        return mid;
    }
}

int main() {
    vector<int>arr1 = {3, 5, 7, 12, 15, 18}; // even no of elements
    int tar1 = 3;
    vector<int>arr2 = {4, 6, 10, 11, 12, 18, 19}; // odd no of elements
    int tar2 = 19;

    cout << "Index at which tar1 is found(even no of elements) : " << binarySearch(arr1, tar1) << endl;
    cout << "Index at which tar2 is found(odd no of elements) : " << binarySearch(arr2, tar2) << endl;
    
    cout << "Using Recusive function index at which tar1 is found : " << binarySearch2(arr1, tar1, 0, 5) << endl;
    cout << "Using Recusive function index at which tar1 is found : " << binarySearch2(arr2, tar2, 0, 6) << endl;

    return 0;
}
// Author : Khadiza Sultana
#include<iostream>
#include<vector>
using namespace std;

int main() {
    int a = 10;
    int* ptr = &a;
    int** parPtr = &ptr;
    cout << ptr << endl;
    cout << parPtr << endl;
    cout << *(&a) << endl;
    cout << *(ptr) << endl;
    cout << *(parPtr) << endl;
    cout << **(parPtr) << endl;
    return 0;
}
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  isEmployed: true,
  hobbies: ["reading", "traveling", "coding"],
  address: {
    street: "123 Main St",
    city: "Anytown",
    country: "USA",
  },
  greet: function () {
    return `Hello, my name is ${this.firstName} ${this.lastName}.`;
  },
};

const newObj = {};

for (let key in person) {
  if (key === "firstName" || key === "lastName") {
    newObj[key] = person[key];
  }
}

console.log({ newObj });
// Author : Khadiza Sultana
#include<iostream>
#include<vector>
using namespace std;
int LinearSearch(vector<int> &vec, int target){
    int i = 0;
    for(int val : vec){
        if(val == target)
           return i;
        i++;
    }
    return -1;
}
int main(){
    vector<int> vec = {1, 2, 5, 8, 5, 7, 8};
    int target = 7;
    cout << LinearSearch(vec, target) << endl;
    return 0;
}
// Khadiza Sultana
#include<iostream>
#include <climits>
using namespace std;
int sum(int arr[], int size){
    int sum = 0;
    for(int i = 0; i < size; i++){
        sum += arr[i];
    }
    return sum;
}
int product(int arr[], int size){
    int product = 1;
    for(int i = 0; i < size; i++){
        product *= arr[i];
    }
    return product;
}
void swap(int &a, int &b){
    a = a + b;
    b = a - b;
    a = a - b;
}
void uniqueElement(int arr[], int size){
    for(int i = 0; i < size; i++){
        bool isUnique = true;
        for(int j = 0; j < size; j++){
            if(i != j && arr[i] == arr[j]){
                isUnique = false;
                break;
            }
        }
        if(isUnique) cout << arr[i] << " ";
    }
    cout << endl;
} 
void reverseMinAndMax(int arr[], int size){
    int largest = INT_MIN, smallest = INT_MAX, largest_index = -1, smallest_index = -1;
    for(int i = 0; i < size; i++){
        if(arr[i] > largest){
            largest = arr[i];
            largest_index = i;
        }
        if(arr[i] < smallest){
            smallest = arr[i];
            smallest_index = i;
        }
    }
    swap(arr[largest_index], arr[smallest_index]);
    for(int i = 0; i < size; i++){
        cout << arr[i] << " ";
    }
    cout << endl;
}
void intersection(int arr1[], int size1, int arr2[], int size2){
    for(int i = 0; i < size1; i++){
        bool repeated = false;
        for(int j = 0; j < size1; j++){
            if(i != j && arr1[i] == arr1[j]){
               repeated = true;
               break;
            }
        }
        if(repeated) arr1[i] = INT_MAX;
        for(int j = 0; j < size2; j++){
            if(arr1[i] == arr2[j]){
               cout << arr1[i] << " ";
               break;
            }
        }

    }
    cout << endl;
}
int main(){
    int arr1[] = {1, 2, 4, 6, 4, 6, 2, 5, 9};
    int size1 = sizeof(arr1) / sizeof(int);
    int arr2[] = {2, 4, 3, 5, 8, 6, 3};
    int size2 = sizeof(arr2) / sizeof(int);
    cout << "Sum of elements : " << sum(arr1, size1) << endl;
    cout << "Product of elements : " << product(arr1, size1) << endl;
    cout << "The elements of the first array after the maximum element and minimum element are reversed : ";
    reverseMinAndMax(arr1, size1);
    cout << "The unique elements in the first array : ";
    uniqueElement(arr1, size1);
    cout << "The intersecting elements between the first and second array : ";
    intersection(arr1, size1, arr2, size2);
    return 0;
}
#include<stdio.h>
//Author : Khadiza Sultana
void dectohex(int n){
    if(n == 0) return;
    dectohex(n / 16);
    int rem = n % 16;
    if(rem < 10) printf("%d", rem);
    else printf("%c", rem - 10 + 'A');
}
int main(){
    printf("Enter a number : ");
    scanf("%d", &num);
    printf("Hexadecimal representation of %d : ", num);
    dectohex(num);
    printf("\n");
    return 0;
}
// Author : Khadiza Sultana
#include<stdbool.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define NUM_SUITS 4
#define NUM_RANKS 13

int main(){
    bool in_hand[NUM_SUITS][NUM_RANKS] = {false};
    int num_cards, rank, suit;
    const char rank_code[] = {'2', '3', '4', '5', '6', '7', '8', '9', 't', 'j', 'q', 'k', 'a'};
    const char suit_code[] = {'c', 'd', 'h', 's'};
    srand((unsigned) time(NULL));
    printf("Enter number of cards in hand : ");
    scanf("%d", &num_cards);
    printf("Your hand : ");
    while(num_cards > 0){
        suit = rand() % NUM_SUITS;
        rank = rand() % NUM_RANKS;
        if(! in_hand[suit][rank]){
            in_hand[suit][rank] = true;
            num_cards--;
            printf("%c%c ", rank_code[rank], suit_code[suit]);
        }
    }
    printf("\n");
    return 0;
}
// Author : Khadiza Sultana
#include<stdio.h>
#include<stdbool.h>
int main(){
    bool digit_seen[10] = {false};
    int digit;
    long n;
    printf("Enter a number : ");
    scanf("%ld", &n);
    while(n > 0){
        digit = n % 10;
        if(digit_seen[digit])
           break;
        digit_seen[digit] = true;
        n /= 10;
    }
    if(n > 0){
        printf("Repeated digit \n");
    }
    else{
        printf("No repeated digit \n");
    }
    return 0;
}
// Author : Khadiza Sultana 
#include<iostream>
 using namespace std;
  int binTodec(int binNum){
    int ans = 0, pow = 1;
    while(binNum > 0){
        int rem = binNum % 10; // accessing the last digit
        ans += rem * pow;
        binNum /= 10; // removing the last digit
        pow *= 2;
    }
    return ans;
  }

  int main(){
    int binNum;
    cin >> binNum;
    cout << binTodec(binNum) << endl;
    return 0;
  }
// Author : Khadiza Sultana
#include<iostream>
using namespace std;

int decimalToBinary(int decNum){
    int ans = 0, pow = 1;
    while(decNum > 0){
        int rem = decNum % 2; // documenting the remainder for example for 3 % 2 = 1
        decNum /= 2; // determining the divisor 3 / 2 = 1
        ans += (rem * pow); // determining the position for the remainder as it goes from down to up
        pow *= 10; // updating the position of the digits
    }
    return ans;
}

int main(){
    int decNum = 50;  
    cout << decimalToBinary(decNum) << endl;
    return 0;
}
// Khadiza Sultana
#include<iostream>
using namespace std;
int primecheck(int n){
    bool isprime = true;
    for(int i = 2; i * i <= n; i++){
        if(n % i == 0){
            isprime = false;
            return false;
        }
    }
    if(isprime)
       return true;
}
void printprime(int num){
    for(int i = 2; i <= num; i++){
        if(primecheck(i))
           cout << i << " ";
    }
}
int primecount(int num){
    int count = 0;
    for(int i = 2; i <= num; i++){
        if(primecheck(i))
           count++;
    }
    return count;
}
int main(){
    int num;
    cin >> num;
    printprime(num);
    cout << endl;
    cout << primecount(num) << endl;
    return 0;
}
#include<stdio.h>
int main(){
    // Author : Khadiza Sultana
    int n = 4;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < (i + 1); j++)
        printf("* ");
        for(int j = 0; j < 2 * (n - i - 1); j++)
        printf("  ");
        for(int j = 0; j < (i + 1); j++)
        printf("* ");
        printf("\n");
    }
    for(int i = 0; i < n; i++){
        for(int j = n; j > i; j--)
        printf("* ");
        for(int j = 0; j < 2 * i; j++)
        printf("  ");
        for(int j = n; j > i; j--)
        printf("* ");
        printf("\n");
    }
    return 0;
}
#include<stdio.h>
// Author- Khadiza Sultana
// Date- 10/8/2024
// Prints the Calendar of a month 
int main()
{
    int n, i, day; // n stores the number of days in the month, i used as a loop counter, day stores the starting day of the week(from 1 to 7, where 1= Sunday, 7= saturday)
    printf("Enter number of days in month:");
    scanf("%d", &n);
    printf("Enter starting day of the week (1=Sun, 7=Sat): ");
    scanf("%d", &day);
    for(i = 1; i < day; ++i) // This loop is responsible for printing spaces before the first day of the month.
    // If day == 1, no spaces are printed before thr month starts on sunday.
    // If day == 4, the loop runs three times and prints three spaces to align the first day under Wednesday
    {
        printf("   "); // three spacesto allign the days even when there's two digit days the days will be aligned 
    }
    for(i = 1; i <= n; i++, day++) // Prints the actual days of the month.
    // the day++ inside the for loop increments the day variable with each iteration, so the program knows when to start a new line after printing Saturday
    {
        printf("%2d ", i);
        if(day == 7)
        {
            day = 0;
            printf("\n");
        }
    }

    return 0;
}
#include<stdio.h>
// Author- Khadiza Sultana
// Date- 10/8/2024
// printing all even squares from 1 to n
#include<math.h> // includin math.h library for the pow function. We can simply write i*i instead

int main() { 
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    
    int i = 1;
    while(pow(i,2)<= n) // checking if i^2 is equal to n or not. If yes then the loop is stoped. If no then continue
    {
        int square = pow(i,2); // storing the squares of the numbers
        if(square % 2 == 0) // checking if the squares are even or not
        {
            printf("%d\n", square);
        }
        i++; // incrementing i
    }
    
    return 0;
}
#include<stdio.h>
// Author- Khadiza Sultana
// 10/8/2024
// Takes a fraction and prints the lowest form of the fraction

int main() {
    int a, b, x, y, gcd; // Take two integers as input
    printf("Enter the fraction (a/b): ");
    scanf("%d/%d", &a, &b);

    x = a;
    y = b;

    // Using Euclidean algorithm to find the GCD of a and b
    while (y != 0) {
        int remainder = x % y;
        x = y;
        y = remainder;
    }

    // x now contains the GCD
    gcd = x;

    // Dividing both numerator and denominator by GCD to get the reduced fraction
    a = a / gcd;
    b = b / gcd;

    printf("In lowest terms: %d/%d\n", a, b);
    
    return 0;
}
#include<stdio.h>
// Author- Khadiza Sultana
// 10/8/2024
//Finding the largest number with the help of loop
int main()
{
    double number = 0, largest = 0; // initialization is done
    for(;;)
    {
        printf("Enter the number:");
        scanf("%lf", &number);
       
        if(number <= 0)
           break; // when zero or negative number then the infinite loop is broke

        if(number > largest)
           largest = number; // storing the largest number after comparing
    }
    printf("\nThe largest number is %g\n", largest);
   
    return 0;
}
$font-sizes: 12px 14px 16px 18px;

@for $i from 1 through length($font-sizes) {
  .text-#{$i} {
    font-size: nth($font-sizes, $i);  // Retrieves the corresponding font size from the list
  }
}


//generates
.text-1 {
  font-size: 12px;
}

.text-2 {
  font-size: 14px;
}

.text-3 {
  font-size: 16px;
}

.text-4 {
  font-size: 18px;
}
$colors: (
  purple: #6a0dad,
  blue: #3498db,
  green: #2ecc71
);

@each $key, $val in $colors {
  @debug 'Key: #{$key}, Value: #{$val}';
}


//preview in the terminal
$colors: (
  "primary": $primary,
  "secondary": $secondary,
  "error": $error,
  "info": $info,
  "blue": #1919e6,
  "red": #e61919,
  "yellow": #e6e619,
  "green": #19e635,
  "orange": #ffa600,
  "purple": #9900ff,
  "gray": #808080,
  "black": black,
  "white": white,
);



.card {
  display: block;
  padding: $base-padding;
  border: $base-border-thickness solid $light-grey;
  border-radius: $base-border-radius;
  box-shadow: $base-box-shadow;

  // Loop over all keys in the colors map and use them for background color variations
  @each $key, $val in $colors {
    &--bgcolor-#{$key} {
      background-color: $val;

        // Change text to white if the color is purple
    	// change the text to yellow if the color is red
    	// else leave it at black
      @if $key == "purple" {
        .card__body p {
          color: map-get($colors, "white" )
        }
      } @else if $key == "red"{
        .card__body p {
          color: map-get($colors, "yellow")
        }
      }@else {
        .card__body p {
          color: #000;
        }
      }
    }
  }

  &__title {
    h3 {
      font-size: $font-size-lg;
      padding-bottom: $base-padding;
      font-weight: bold;
    }
  }

  &__body {
    font-size: $base-font-size;

    a {
      text-decoration: underline;
    }
  }
}
 for (const item of menu.entries()) {
    const [index, ...menuItem] = item;
    const startIndex = index + 1;
    console.log(`${startIndex}: ${menuItem}`);
  }
let score = 85;

let grade = (score >= 90) ? 'A' : 
            (score >= 80) ? 'B' : 
            (score >= 70) ? 'C' : 
            (score >= 60) ? 'D' : 'F';

console.log(`The grade is ${grade}`);
 const players = [...document.querySelectorAll('section.player')];

    for (const [index, item] of players.entries()) {
      console.log(i, v);
    }




// 0 <section class=​"player player--0 player--active">​…​</section>
// 1 <section class=​"player player--1">​…​</section>
// use while loops when the number of items we are looping over are unknown


let items = [
  { id: 1, name: "Item 1", price: 10.99 },
  { id: 2, name: "Item 2", price: 15.49 },
  { id: 3, name: "Item 3", price: 7.99 },
  { id: 4, name: "Item 4", price: 12.0 },
  { id: 5, name: "Item 5", price: 9.5 },
];

let i = 0; // counter variable

let numberOfItems = items.length ?? 0; // if the number of items is not a number give me 0;
console.log(numberOfItems);

while (i < items.length) {
  let { id, name, price } = items[i]; // Destructuring assignment
  console.log(`ID: ${id}, Name: ${name}, Price: $${price}`);
  i++;
}
const myArray = ['rock', 'paper', 'scissors'];

for(item of myArray){
        const index = myArray.indexOf(item);
        console.log(index)
    
}
const repository = {
  id: 1,
  language: "javascript",
  public: true
};

for (const value of Object.values(repository)) {
  console.log(value);
}
const ages = [18, 20, 21, 30];

const agesPlusOne = ages.map(age => age + 1);
const deck = ['clubs','spades', 'hearts', 'diamonds']
for(let [index, item] of deck.entries()){
    console.log(index)
}
# numpy and matplotlib imported, seed set

# Simulate random walk 500 times
all_walks = []
for i in range(500) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)
        if np.random.rand() <= 0.001 :
            step = 0
        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))

# Select last row from np_aw_t: ends
ends = np_aw_t[-1, :]

# Plot histogram of ends, display plot
plt.hist(ends)
plt.show()
# Numpy is imported; seed is set

# Initialize all_walks (don't change this line)
all_walks = []

# Simulate random walk 10 times
for i in range(10):

    # Code from before
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)

        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)
        random_walk.append(step)

    # Append random_walk to all_walks
    all_walks.append(random_walk)

# Print all_walks
print(all_walks)


#####################################################################
# numpy and matplotlib imported, seed set

# Simulate random walk 250 times
all_walks = []
for i in range(250) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)

        # Implement clumsiness
        if np.random.rand() <= 0.001 :
            step = 0

        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
plt.plot(np_aw_t)
plt.show()


# Numpy is imported, seed is set

# Initialization
random_walk = [0]

for x in range(100) :
    step = random_walk[-1]
    dice = np.random.randint(1,7)

    if dice <= 2:
        step = max(0, step - 1)
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    random_walk.append(step)

# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt

# Plot random_walk
plt.plot(random_walk)

# Show the plot
plt.show()
# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

# Complete the ___
for x in range(100) :
    # Set step: last element in random_walk
   
    step = random_walk[-1]

    # Roll the dice
    dice = np.random.randint(1,7)

    # Determine next step
    if dice <= 2:
        step = step - 1
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    # append next_step to random_walk
    random_walk.append(step)

# Print random_walk
print(random_walk)

#Not Going below zero
# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

for x in range(100) :
    step = random_walk[-1]
    dice = np.random.randint(1,7)

    if dice <= 2:
        # Replace below: use max to make sure step can't go below 0
        step = max(0, step - 1)
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    random_walk.append(step)

print(random_walk)
# Numpy is imported, seed is set

# Starting step
step = 50
# Roll the dice
dice = np.random.randint(1,7)
# Finish the control construct
if dice <= 2 :
    step = step - 1
elif dice <= 5 :
    step = step + 1
else:
    step = step + np.random.randint(1,7)

# Print out dice and step
print(dice)
print(step)
# Import numpy as np
import numpy as np

# Set the seed
np.random.seed(123)

# Generate and print random float
print(np.random.rand())

#Roll The Dice
# Import numpy and set seed
import numpy as np
np.random.seed(123)

# Use randint() to simulate a dice
print(np.random.randint(1,7))
# Use randint() again
print(np.random.randint(1,7))


# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Use .apply(str.upper)


cars['COUNTRY'] = cars['country'].apply(str.upper)
print(cars)
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Adapt for loop
for lab, row in cars.iterrows() :
    print(lab + ": " + str(row['cars_per_cap']))

#Something new

# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Code for loop that adds COUNTRY column
for lab, row in cars.iterrows():
    cars.loc[lab,'COUNTRY'] = row['country'].upper()


# Print cars
print(cars)
#Iterating over a Pandas DataFrame is typically done with the iterrows()
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Iterate over rows of cars
for lab,row in cars.iterrows():
    print(lab)
    print(row)
# Import numpy as np

import numpy as np
#for x in my_array : #in 1D Numpy array
#for x in np.nditer(my_array) : #for 2D Numpy array

# For loop over np_height

for x in np_height:
    print(str(x) + " inches")

# For loop over np_baseball
for x in (np.nditer(np_baseball)):
    print(x)
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
          'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
          
# Iterate over europe
for key, value in europe.items() :
    print('the capital of ' + str(key) + ' is ' + str(value))
# house list of lists
house = [["hallway", 11.25], 
         ["kitchen", 18.0], 
         ["living room", 20.0], 
         ["bedroom", 10.75], 
         ["bathroom", 9.50]]
         
# Build a for loop from scratch
for x in house :
    #x[0] to access name of room
    #x[1] to access area in sqm
    print('the ' + x[0] + " is " + str(x[1]) + " sqm")
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
/*
The tax rate is often a function of the income or in other words individuals at different income levels will pay different taxes.

Also, in some countries like the UK, individuals get to keep a certain amount of their income
that's not taxed while the remainder is taxed at the applicable rate. So for example, let's say a person makes 100K and their tax rate is 10% or 0.1 but they are allowed to keep 30K. They will end up paying 7000 or 7K in taxes because:
100K - 30K = 70K. // they keep 30K and have 70K left.
10% of 70K = 7K. // they will pay 10% tax on what's left.

Your challenge is to complete the code below to return the function that will correctly calculate taxes for a person based on the rules below.

Amount                            Tax Rate
--------------------------------------------
<= 100,000                        10% or 0.1
> 100,000 to 500,000 (inclusive)  20% or 0.2
> 500,000                         35% or 0.3
*/

// Should return a function that accepts a number that's the amount to be taxed
// and returns the tax amount after factoring in the income not taxed and the
// applicable tax rate.
function getTaxCalculator(incomeNotTaxed) {
 // your code here (approximately 10 lines)
   function calculateTax(amount){
   let taxAmount = amount - incomeNotTaxed;
    if (amount <= 100000){
        taxAmount * 0.1
    }else if((amount>100000) && (amount<= 500000)){
        taxAmount * 0.2
    }else{
        taxAmount * 0.3 
        }
}
 return calculateTax       
}

// THIS IS FOR YOUR TESTING ONLY.
const calculateTax = getTaxCalculator(30000)
console.log(calculateTax(100000)) // should print 70000
console.log(calculateTax(350000)) // should print 64000
console.log(calculateTax(600000)) // should print 171000
// This array (characters) has a length of 4 i.e characters.length is 4
// characters[0] will return ["a", "b", "c"]
// characters[0][1] will return "b"
// and so on.
const characters = [
  ["a", "b", "c"],
  ["d", "e", "f"],
  ["g", "h", " i"],
  ["x", "y", "z"],
];

function characterExist(letter) {
  // we initialize exists to false because we intend to set it to true only if /// we find the letter in the colors array
  let exist = false;

  // TODO(1): Write code to loop through the characters array, and set exist to
  // true if the value in the variable letter is found in the array.
    for(i=0; i<=characters.length; i++){
        for(j=0; j<=characters[i].length; j++){
            if(characters[i][j] === letter){
                exist = true;
        return true
            } 
        }
    }
    return exist;
}

// THIS IS FOR TESTING ONLY
console.log("a exists = " +  characterExist("a")); // prints true
console.log("p exists = " +  characterExist("p")); // prints false
 #declare two set the range
1.i = 1
2.j = 5
#use while loop for i
3.while i < 4:
#use while loop for j    
4.while j < 8:
        5.print(i, ",", j)
        6.j = j + 1
        7.i = i + 1
Output:
1 , 5
2 , 6
3 , 7                               
                                
star

Fri Jan 03 2025 20:18:56 GMT+0000 (Coordinated Universal Time)

#loop #c++ #vector #pointers #binarysearch #array
star

Fri Jan 03 2025 18:59:47 GMT+0000 (Coordinated Universal Time)

#loop #c++ #vector #pointers #binarysearch
star

Fri Jan 03 2025 10:56:21 GMT+0000 (Coordinated Universal Time)

#loop #c++ #vector #pointers
star

Wed Dec 25 2024 22:47:37 GMT+0000 (Coordinated Universal Time)

#oop #keys #loop
star

Sat Dec 07 2024 11:45:20 GMT+0000 (Coordinated Universal Time)

#loop #c++ #vector
star

Fri Dec 06 2024 12:13:48 GMT+0000 (Coordinated Universal Time)

#loop #array #c++
star

Sun Nov 17 2024 02:09:56 GMT+0000 (Coordinated Universal Time)

#loop #c #array
star

Sat Nov 16 2024 15:03:31 GMT+0000 (Coordinated Universal Time)

#loop #c #array
star

Sat Nov 16 2024 09:35:35 GMT+0000 (Coordinated Universal Time)

#loop #c #array
star

Tue Nov 12 2024 03:11:26 GMT+0000 (Coordinated Universal Time)

#c++ #function #loop
star

Mon Nov 11 2024 16:09:30 GMT+0000 (Coordinated Universal Time)

#c++ #function #loop
star

Mon Nov 11 2024 15:58:45 GMT+0000 (Coordinated Universal Time)

#loop #c++
star

Tue Nov 05 2024 00:50:41 GMT+0000 (Coordinated Universal Time)

#c #loop
star

Wed Sep 11 2024 00:18:40 GMT+0000 (Coordinated Universal Time)

#scss #loop #list #fonts
star

Sun Sep 08 2024 05:32:38 GMT+0000 (Coordinated Universal Time)

#css #map-get #maps #object #loop
star

Sun Sep 08 2024 04:46:36 GMT+0000 (Coordinated Universal Time)

#css #map-get #maps #object #loop #conditionals
star

Fri Jun 21 2024 22:34:10 GMT+0000 (Coordinated Universal Time)

#for #loop #index
star

Mon Jun 17 2024 11:06:30 GMT+0000 (Coordinated Universal Time)

#loop #index #array
star

Sun Jun 16 2024 01:21:28 GMT+0000 (Coordinated Universal Time)

#loop #index #array
star

Mon May 27 2024 08:13:39 GMT+0000 (Coordinated Universal Time)

#while #loop
star

Sun Apr 16 2023 22:18:18 GMT+0000 (Coordinated Universal Time)

#javascript #forof #loop #index
star

Wed Apr 05 2023 22:18:46 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-loop-through-object-in-javascript/

#javascript #loop #object
star

Wed Apr 05 2023 16:01:56 GMT+0000 (Coordinated Universal Time) https://codetogo.io/how-to-apply-function-to-every-array-element-in-javascript/

#javascript #array #every #loop #function
star

Sun Mar 19 2023 07:42:05 GMT+0000 (Coordinated Universal Time)

#loop #index
star

Fri Nov 26 2021 10:49:17 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop #dicegame #matplotlib #[plot #graph
star

Fri Nov 26 2021 10:42:38 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop #dicegame
star

Fri Nov 26 2021 10:06:16 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Fri Nov 26 2021 09:45:49 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 17:01:18 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:48:58 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:42:08 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:28:23 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:16:28 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 15:55:42 GMT+0000 (Coordinated Universal Time)

#numpy #booleans_in_numpy #list #forloop #for #loop
star

Wed Jun 30 2021 07:05:52 GMT+0000 (Coordinated Universal Time)

#python #comprehension #loop
star

Fri Jun 25 2021 15:12:00 GMT+0000 (Coordinated Universal Time) edconnect.com

#loop
star

Wed Jun 23 2021 13:58:24 GMT+0000 (Coordinated Universal Time) edconnect.com

#2-darrays #loop
star

Tue Apr 21 2020 06:12:11 GMT+0000 (Coordinated Universal Time) https://beginnersbook.com/2018/01/python-while-loop/

#python #python #loop #whileloop #nestedwhile loop

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension