100 likes | 211 Vues
This guide covers the essential concepts of repetitive programming in C, focusing on while, do-while, and for loops. It explains how to use each loop structure effectively, with code examples illustrating the process of condition checking and executing statements within loops. You'll learn how to create interactive programs that ask users for input, calculate sums, and validate entries. The document also includes assignments that challenge your understanding, such as implementing multiplication tables and creating number guessing games, enhancing your programming skills in C.
E N D
PROGRMMING with C Repetitive Or Iterative
Repetitive Programming • while statement • do – while statement • for statement
while statement while (condition) { statement ; . . . . . . . . . . } • ตรวจสอบเงื่อนไขก่อน • หากถูกต้อง ทำงานตาม statement และกลับไปตรวจสอบเงื่อนไขอีกครั้ง • หากไม่ถูกต้อง ออกจากการทำงานในคำสั่ง while Condition Yes No Statement
Example of while loop int score , sum = 0; while (score != 0) { printf(“Enter score : “); scanf(“%d”,&score); sum = sum + score; } printf(“Sumation of score : %d”,sum);
do – while statement do { statement ; . . . . . . . . . . } while (condition) ; • ทำงานตาม statement ที่กำหนด • ตรวจสอบเงื่อนไข • ถ้าถูกต้อง ให้กลับไปทำงานตาม statement ที่กำหนดไว้อีกครั้ง • ถ้าไม่ถูกต้อง ให้ออกจากการทำงานของคำสั่ง do-while Statement Condition Yes No
Example of do – while loop int num , sum = 0 ; do { printf(“Enter a number : ”); scanf(“%d”&num); sum = sum + num; } while(num != 0) ; printf(“Summation : %d\n”,sum);
for statement for ( initialization ; condition ; increment or decrement ) { statement ; . . . . . . . . . . } • กำหนดค่าเริ่มต้นตัวควบคุมลูป • ตรวจสอบเงื่อนไข • ถ้าถูกต้อง ให้ทำงานตาม statement ที่กำหนด • ทำการเพิ่มค่า หรือลดค่าตัวควบคุมลูป และกลับไปตรวจสอบเงื่อนไขอีกครั้ง Initialization ++ / - - Statement Condition No Yes
Example of for loop int i , beg, end; printf(“Enter the beginning number : “); scanf(“%d”,&beg); printf(“Enter the ending number : “); scanf(“%d”,&end); for ( i=beg ; i<=end ; i++ ) printf(“%d\n“,i);
Assignments • เขียนโปรแกรมเพื่อแสดงตารางสูตรคูณ (1–12) โดยให้ผู้ใช้เป็นผู้กำหนดค่าตัวเลขที่ต้องการ • เขียนโปรแกรมเพื่อคำนวณหาค่าเฉลี่ยของคะแนนสอบประจำวิชา programming โดยให้รับค่าคะแนนเข้ามา (ตรวจสอบค่าจะต้องอยู่ในช่วง 0-100 เท่านั้น หากป้อนค่าผิด ให้ย้อนกลับไปรับใหม่)
Assignments 3. เขียนโปรแกรมเกมทายค่าตัวเลข โดยมีรูปแบบการทำงานดังนี้ 1. สุ่มค่าตัวเลขขึ้นมา 1 ตัว (ขนาด 4 หลัก) 2. ให้ผู้ใช้ทายค่าตัวเลข 3. ตรวจสอบค่าตัวเลขของผู้ใช้ - หากมากกว่าตัวเลขที่สุ่มขึ้น ให้แสดงผลว่า “It’s Greater” - หากน้อยกว่าตัวเลขที่สุ่มขึ้น ให้แสดงผลว่า “It’s Less” - หากค่าเท่ากัน ให้แสดงผลว่า “You are the Winner”และข้ามไปทำงานในข้อที่ 5 4. ย้อนกลับไปให้ผู้ใช้ทายค่าตัวเลขอีกครั้ง 5. แสดงจำนวนครั้งของการทาย และถามว่าต้องการเล่นต่ออีกหรือไม่ - ถ้าใช่ ให้ย้อนกลับเริ่มต้นทำงานที่ข้อ 1 อีกครั้ง - ถ้าไม่ใช่ ให้จบโปรแกรม