Examples of iteration and branching implementations in various languages

Artificial Intelligence Machine Learning Digital Transformation Clojure Python PHP R language C/C++ Java Javascript Programming Overviews Navigation of this blog
summary

Among programming languages, the basic functionality is one element of the three functions of structured languages (1) sequential progression, (2) conditional branching, and (3) repetition, as described in the “History of Programming Languages” section. Here, we show implementations of repetition and branching in various languages.

Implementation in Python

Below is an example code for implementing iteration and branching in Python.

Example implementation of repetition (using a for loop):.

# Example of displaying numbers from 1 to 10
for i in range(1, 11):
    print(i)

Example implementation of repetition (using a while loop):.

# Example of displaying numbers from 1 to 10
i = 1
while i <= 10:
    print(i)
    i += 1

Example of branch implementation (with if statement):.

# Example of determining whether a number is even or odd
num = 7

if num % 2 == 0:
    print(num, "is an even number.")
else:
    print(num, "is an odd number.")

Example of branch implementation (with elif):.

# Example of displaying evaluations according to grades
score = 75

if score >= 90:
    print("Grade is A.")
elif score >= 80:
    print("Grade is B.")
elif score >= 70:
    print("Grade is C.")
elif score >= 60:
    print("Grade is D.")
else:
    print("Grade is F.")

In these examples, the for loop and while loop are used to perform iterative processing, and the if statement is used to perform branching processing according to conditions.

Implementation in Java

The following is an example of implementation code for iteration and branching in Java.

Example of repetition implementation (using a for loop):: (1)

// Example of displaying numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}

Example implementation of repetition (using a while loop):.

// Example of displaying numbers from 1 to 10
int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}

Example of branch implementation (with if statement):.

// Example of determining whether a number is even or odd
int num = 7;

if (num % 2 == 0) {
    System.out.println(num + "is an even number.");
} else {
    System.out.println(num + "is an odd number.");
}

Example of branch implementation (using else if):.

// Example of displaying evaluations according to grades
int score = 75;

if (score >= 90) {
    System.out.println("Grade is A.");
} else if (score >= 80) {
    System.out.println("Grade is B.");
} else if (score >= 70) {
    System.out.println("Grade is C.");
} else if (score >= 60) {
    System.out.println("Grade is D.");
} else {
    System.out.println("Grade is F.");
}

In these examples, the Java control syntax of for and while loops are used to perform iterative processing, and if statements are used to perform branching processing according to conditions.

Javascript implementation

The following is an example code implementation of iteration and branching in JavaScript.

  1. Example of for loop
for (let i = 0; i < 10; i++) {
  console.log(i);
}

In this example, numbers from 0 to 9 are output in sequence.

  1. Example of a while loop: While loop
let i = 0;
while (i < 10) {
  console.log(i);
  i++;
}

This example also outputs the numbers 0 through 9 in sequence, but is written differently than a for loop.

  1. Example of an if statement: If
let num = 5;
if (num > 0) {
  console.log("Positive numbers.");
} else if (num === 0) {
  console.log("Zero.");
} else {
  console.log("Negative numbers.");
}

In this example, the system branches according to the value of the variable num and outputs a message that matches the condition.

  1. Example of a switch statement: .
let dayOfWeek = "Saturday";
switch (dayOfWeek) {
  case "Monday":
    console.log("It's time to get to work.");
    break;
  case "Saturday":
  case "Sunday":
    console.log("It's day off");
    break;
  default:
    console.log("It's a weekday.");
}

In this example, the variable dayOfWeek is branched according to its value to output a message that matches the condition.

Implementation in C

The following is an example of code implementation of iteration and branching in C language.

  1. Example of a for loop: for
#include 

int main() {
    for (int i = 0; i < 10; i++) {
        printf("%dn", i);
    }
    return 0;
}

In this example, numbers from 0 to 9 are output in sequence.

  1. Example of a while loop: While loop
#include 

int main() {
    int i = 0;
    while (i < 10) {
        printf("%dn", i);
        i++;
    }
    return 0;
}

This example also outputs the numbers 0 through 9 in sequence, but is written differently than a for loop.

  1. Example of an if statement: If
#include 

int main() {
    int num = 5;
    if (num > 0) {
        printf("Positive numbers.\n");
    } else if (num == 0) {
        printf("Zero. \n");
    } else {
        printf("Negative numbers.\n");
    }
    return 0;
}
  1. Example of an if statement: If
#include 

int main() {
    int num = 5;
    if (num > 0) {
        printf("Positive numbers.\n");
    } else if (num == 0) {
        printf("Zero.\n");
    } else {
        printf("Negative numbers.\n");
    }
    return 0;
}

In this example, the system branches according to the value of the variable num and outputs a message that matches the condition.

  1. Example of a switch statement: .
#include 

int main() {
    char dayOfWeek[] = "Saturday";
    if (strcmp(dayOfWeek, "Monday") == 0) {
        printf("It's time to get to work.\n");
    } else if (strcmp(dayOfWeek, "Saturday") == 0 || strcmp(dayOfWeek, "Sunday") == 0) {
        printf("It's day off.\n");
    } else {
        printf("It's a weekday.\n");
    }
    return 0;
}

In this example, the strcmp function is used to compare strings, branching according to the value of the variable dayOfWeek and outputting a message that matches the condition.

Implementation in R

The following is an example code implementation of iteration and branching in the R language.

  1. Example of a for loop: for
for (i in 1:10) {
  print(i)
}

In this example, numbers 1 through 10 are output in sequence.

  1. Example of a while loop: While loop
i <- 1
while (i <= 10) {
  print(i)
  i <- i + 1
}

This example also outputs the numbers 1 through 10 in sequence, but is written differently than a for loop.

  1. Example of an if statement: If
num <- 5 if (num > 0) {
  print("Positive numbers.")
} else if (num == 0) {
  print("Zero.")
} else {
  print("Negative numbers.")
}

In this example, the system branches according to the value of the variable num and outputs a message that matches the condition.

  1. Example of a switch statement: .
dayOfWeek <- "Saturday"
switch (dayOfWeek,
        "月曜日" = print("It's time to get to work."),
        "土曜日" = { print("It's day off.") },
        "日曜日" = { print("It's day off.") },
        print("It's a weekday."))

In this example, the system branches according to the value of the variable dayOfWeek and outputs a message that matches the condition. switch function is used to process multiple conditions at once.

Implementation in Laravel

Below is an example of code implementation of iteration and branching in Laravel (PHP framework).

  1. Example of foreach loop: foreach loop
@foreach ($users as $user)
<p>{{ $user->name }}</p>
@endforeach

In this example, elements in an array or collection called $users are taken out in order and assigned to a variable called $user to be displayed.

  1. Example of a for loop: for
@for ($i = 0; $i < 10; $i++)
<p>{{ $i }}</p>
@endfor

In this example, the numbers from 0 to 9 are taken out in order and assigned to the variable $i for display.

  1. Example of an if statement: If
@if ($num > 0)
<p>Positive numbers.</p>
@elseif ($num == 0)
<p>Zero.</p>
@else
<p>Negative numbers.</p>
@endif

In this example, the system branches according to the value of the variable $num and displays a message that matches the condition.

  1. Example of a switch statement: .
@switch($dayOfWeek)
@case("Monday")
<p>It's time to get to work.</p>
@break
@case("Saturday")
<p>It's day off.</p>
@break
@case("Sunday")
<p>It's day off</p>
@break
@default
<p>It's a weekday.</p>
@endswitch

In this example, the system branches according to the value of the variable $dayOfWeek and displays a message that matches the condition. Laravel directives such as @switch, @case, and @default are used to implement the branching process.

Example implementation in Clojure

Below is an example code implementation of iteration and branching in the Clojure language.

  1. Example of iteration with the doseq function:.
(doseq [x (range 1 11)]
  (println x))

In this example, the range function is used to generate a range of numbers from 1 to 10, and the doseq function is used to retrieve and display each number in turn.

  1. Example of iteration with loop/recur:.
(loop [i 1]
  (when (<= i 10)
    (println i)
    (recur (inc i))))

In this example, loop and recur are combined to retrieve and display the numbers 1 through 10 in sequence.

  1. Example of an if statement: If
(def num 5)
(if (> num 0)
  (println "Positive numbers.")
  (if (= num 0)
    (println "Zero.")
    (println "Negative numbers.")))

In this example, if is used to branch according to the value of the variable num, and a message that matches the condition is displayed.

  1. Example of branching by cond function:
(def day-of-week "Saturday")
(cond
  (= day-of-week "Monday") (println "It's time to get to work.")
  (or (= day-of-week "Saturday") (= day-of-week "Sunday")) (println "It's day off.")
  :else (println "It's a weekday."))

In this example, the cond function is used to branch according to the value of the variable day-of-week and display a message that matches the condition. = is used to compare values, and or returns true if any of the multiple conditions are true. :else represents the default condition.

Example Implementation in Go

Below is an example of iteration and branching implementation code in the Go language.

  1. Example of a for loop: for
for i := 1; i <= 10; i++ {
    fmt.Println(i)
}

In this example, the numbers 1 through 10 are retrieved and displayed in sequence using a for statement.

  1. Example of repetition by range: range
nums := []int{1, 2, 3, 4, 5}
for _, num := range nums {
    fmt.Println(num)
}

In this example, the elements of the slice (array) nums are retrieved and displayed in order using range. The _ is a blank identifier to ignore the index, and the elements of the slice are assigned to nums.

  1. Example of an if statement: If
num := -5
if num > 0 {
    fmt.Println("Positive numbers.")
} else if num == 0 {
    fmt.Println("Zero.")
} else {
    fmt.Println("Negative numbers.")
}

In this example, the if statement is used to branch according to the value of the variable num and display a message that matches the condition.

  1. Example of a switch statement: .
dayOfWeek := "Saturday"
switch dayOfWeek {
case "Monday":
    fmt.Println("It's time to get to work.")
case "Saturday", "Sunday":
    fmt.Println("It's day off.")
default:
    fmt.Println("It's a weekday.")
}

In this example, a switch statement is used to branch according to the value of the variable dayOfWeek and display a message that matches the condition. Multiple conditions can be combined into the same process, with default representing the default condition.

コメント

タイトルとURLをコピーしました