Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

พิมพ์ 1 ถึง 100 ใน C++ โดยไม่ใช้ Loop และ Recursion


พิมพ์ตัวเลข 1 ถึง 100 โดยไม่ใช้ Loop และ Recursion

มีหลายวิธีพิมพ์ตัวเลขโดยไม่ใช้ loop เช่น recursive function, goto statement, สร้างฟังก์ชันนอก main()

ตัวอย่างใช้ Goto Statement

#include <bits/stdc++.h>
using namespace std;

int main() {
    int count = 1;
    int x;
    cout << "Enter the max value of x: ";
    cin >> x;
    PRINT:
    cout << " " << count;
    count++;
    if(count <= x) goto PRINT;
    return 0;
}

ผลลัพธ์

Enter the max value of x: 1

ใช้ GOTO statement พิมพ์ตัวเลข 1 ถึง 100 โดยไม่ใช้ loop และ recursion label PRINT: แสดงค่า count เพิ่ม count ถ้ายัง <= x ก็ goto PRINT