Anasayfa » C / C++

C / C++ Courses ? 9 (While Loops)

18 Aralık 2010 1.647 views Yorum Yok Kii

While Loops

*Counter Controlled Loops:

Steps that we should follow:

1- Declare and initialize a counter

?  2-Use the counter in the condition part of while

?  3-Change the value of the counter inside the loop (increment or decrement)

¤ These 3 steps must be used in our program, else it means there is something wrong.

Ex:

Find the average of 10 quiz grades which are entered by the user.

#include <stdio.h>

int main(){

int grade, sum = 0;

float average;

int counter = 1;   //1.step

while (counter <= 10){   //2.step

printf( ?Enter a grade \n? );

scanf( ?%d?, &grade);

sum += grade;

counter ++;    //3.step

}

average = (float) sum / 10;

printf(?%f is average \n?, average);

return 0;

}

Ex:

Write a program that finds and prints the integers that are a multiple of 3 in the range 25 and 97.

#include <stdio.h>

int main(){

int number=25;   //1.step

while (number <= 97){   //2.step

if(number % 3== 0)

printf( ?%d is a multiple of 3 \n?, number);

number ++;    //3.step

}

return 0;

}

Ex:

Write a program that inputs an integer. The program will find and print the factorial of this number.

#include <stdio.h>

int main(){

int number;

int fact=1;

printf( ?Enter a number \n? );

scanf( ?%d?, &number);

while (number >= 1){

fact *= number;

number –;

}

return 0;

}

Ex:

Write a program that inputs 2 integers and the program will swap the values of these integers and prints them.

#include <stdio.h>

int main(){

int num1, num2;

printf( ?Enter 2 numbers \n? );

scanf( ?%d%d?, &num1, &num2);

int temp = num1;

num1 = num2;

num2 = temp;

printf( ?Number 1 is %d. Number 2 is %d. ?, num1, num2);

return 0;

}

Ex:
Write a program that inputs an integer and prints a square of stars with the size of that integer. For example, if the user enters 3 it will print:      ***
***
***

#include <stdio.h>

int main(){

int x;

int counter = 1;

printf( ?Enter a number \n? );

scanf( ?%d?, &x);

while (counter <= x*x){

printf( ?*? );

if(counter % x == 0)

printf( ?\n?);

counter ++;

}

return 0;

}

This was my solution at the first time. But there is a better solution for that. Here it comes =))

#include <stdio.h>

int main(){

int x;

int row = 1, column=1;  // there is 2 counters. First one is for row, other is for column

printf( ?Enter a number \n? );

scanf( ?%d?, &x);

while (row <=  x){

while (column <=  x){

printf( ?*? );

column ++;

}

column = 1; //it resets the column, if we don?t, it prints stars just for one row.

printf(?\n?);

row ++;

}

return 0;

}

See you soon. Take care!

Yoruma Açığız! :)

Be nice. İçeriği çirkin olmadığı sürece her yoruma, öneriye ve soruya "evet" :)

Etiketler: , , , , , ,