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

โปรแกรม C/C++ แบบท้าทาย (Tricky Programs) 10 ข้อ

1. พิมพ์เครื่องหมายคำพูด " ใน C++

ใช้ escape sequence \" เพื่อพิมพ์เครื่องหมายคำพูด

#include <iostream>
using namespace std;
int main() {
    cout << "\"Tutorials Point \"";
    return 0;
}
"Tutorials Point "

2. พิมพ์ตัวเลข 1-10 โดยไม่ใช้ลูปหรือ goto

ใช้ฟังก์ชันเรียกซ้ำ (Recursion)

#include <stdio.h>
void printNumber(int count) {
    printf("%d\n", count);
    count += 1;
    if (count <= 10)
        printNumber(count);
}
int main() {
    printNumber(1);
    return 0;
}
1 2 3 4 5 6 7 8 9 10

3. ตรวจสอบความเท่ากันของสองตัวเลขโดยไม่ใช้ตัวดำเนินการเปรียบเทียบหรือคณิตศาสตร์

ใช้ XOR (^) ถ้าผลลัพธ์เป็น 0 แสดงว่าเท่ากัน

#include <iostream>
using namespace std;
int main() {
    int a = 132, b = 132;
    if ((a ^ b))
        cout << "a is not equal to b";
    else
        cout << "a is equal to b";
    return 0;
}
a is equal to b

4. พิมพ์ "Hello" โดยไม่ใช้ semicolon (;)

ใช้ค่าคืนของ printf() ในเงื่อนไข if

#include <stdio.h>
int main() {
    if (printf("Hello "))
        return 0;
}
Hello

5. หาค่าสูงสุดและต่ำสุดของสองตัวเลขโดยไม่ใช้ตัวดำเนินการเปรียบเทียบ

ใช้ abs() และสูตรคณิตศาสตร์

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
    int x = 15, y = 20;
    cout << "Max: " << ((x + y) + abs(x - y)) / 2 << endl;
    cout << "Min: " << ((x + y) - abs(x - y)) / 2 << endl;
    return 0;
}
Max: 20
Min: 15

6. พิมพ์ซอร์สโค้ดของตัวเอง (Quine)

ใช้ file handling เปิดไฟล์ตัวเอง (__FILE__) แล้วอ่านพิมพ์

#include <stdio.h>
int main(void) {
    FILE *program;
    char ch;
    program = fopen(__FILE__, "r");
    do {
        ch = fgetc(program);
        printf("%c", ch);
    } while (ch != EOF);
    fclose(program);
    return 0;
}

7. บวกสองตัวเลขโดยไม่ใช้ +

ใช้ - กับลบลบ: x - (-y) = x + y

#include <iostream>
using namespace std;
int main() {
    int x = 5, y = 5;
    int sum = x - (-y);
    cout << "Sum = " << sum;
    return 0;
}
Sum = 10

8. ตรวจสอบเลขคู่โดยไม่ใช้ตัวดำเนินการคณิตศาสตร์หรือเปรียบเทียบ

ใช้ bitwise AND กับ 0x01 ตรวจสอบบิต LSB

#include <iostream>
using namespace std;
int main() {
    int a = 154;
    if (a & 0x01)
        cout << a << " is an odd number";
    else
        cout << a << " is an even number";
    return 0;
}
154 is an even number

9. หารตัวเลขด้วย 4 โดยไม่ใช้ /

ใช้ right shift operator >> 2 บิต

#include <iostream>
using namespace std;
int main() {
    int n = 128;
    cout << n << " divided by 4 = ";
    n = n >> 2;
    cout << n;
    return 0;
}
128 divided by 4 = 32

10. หาผลรวมหลักตัวเลขซ้ำจนได้หลักเดียว (Digital Root)

ใช้คุณสมบัติ modulo 9

#include <iostream>
using namespace std;
int main() {
    int a = 534;
    int sum = a ? (a % 9 == 0 ? 9 : a % 9) : 0;
    cout << "The final sum is " << sum;
    return 0;
}
The final sum is 3