الدرس العاشر 10: while loop في c++ وتمثيلها على function
while loop
الwhile loop : احد جمل التكرار الموجوده في لغات البرمجه
الفرق بين ال while loop وال foor loop :
ال foor : تتكون من عداد وشرط ومقدار الزياده والنقصان في العداد
اما ال while loop فهي تتكون من شرط فقط اذا كان جوابه صحيح يبقى داخل الدوره واذا كان جوابه خاطيئ يتوقف عن دوره التكرار
اذا لم يصبح جواب الشرط false فانه سوف يتكرر الى مالا نهايه
الشكل العام لجمله while loop :
while (الشرط){}
مثال::
while (x!=0)
while (x!=0)
{
cout<<"hi";
}
في المثال السابق جمله التكرار مستمره الى ان يصبح قيمه x تساوي 0صفر
امثله :
مثال يطبع كلمه hi
الى ان يدخل المستخدم رقم 0
#include <iostream>
#include <string>
using namespace std ;
void main ()
{int x=50;
while (x!=0)
{
cin>>x;
cout<<"hi"<<endl;
}
cout<<"The End"<<endl;
system("pause"); }
مثال لحساب مجموع قيم مدخله بحيث كل مره يسال المستخدم هل انتهيت ؟
اذا كانت الاجابه نعم يتوقف ثم يطبع المجموع
اذا كانت الاجابه نعم يتوقف ثم يطبع المجموع
#include <iostream>
#include <string>
using namespace std ;
void main ()
{double x=0,sum=0;
char sto='n';
while (sto!='y' && sto != 'Y')
{
cout<<"\n enter the salary to add:\t ";
cin>>x;
sum=sum+x;
cout<<"you are fenished ? (N\\Y) \t";
cin >>sto;
}
cout<<"THANK YOU \n THE SUM = \t"<<sum <<endl;
system("pause"); }
مثال يطبع كلمه hello
10 مرات كما هو الحال باستخدام for لكن بال while
#include <iostream>
#include <string>
using namespace std ;
void main ()
{int i=0;
while (i<10)
{i++;
cout<<"hello"<<endl;
}
system("pause"); }
مثال على جمله while متداخله اي 2 منها احدهما داخل الاخرى
يدخل المستخدم 5 ارقام اذا كان مجموعهم اقل من 50 يعيد الادخال :
#include <iostream>
#include <string>
using namespace std ;
void main ()
{double x=0,sum=0;
while (sum<50)
{int i=0;
sum=0;
while (i<5)
{cin>>x;
sum=sum+x;
i++;
}
cout<<"\n SUM ="<<sum<<"\t AGEN PLEASE ";
}
cout<<"THANK YOU \n THE SUM = \t"<<sum <<endl;
system("pause"); }
المثال الاخير مرفوعاً الى فنكشن :
#include <iostream>
#include <string>
using namespace std ;
void ds(double x, double sum)
{
while (sum<50)
{int i=0;sum=0;
while (i<5)
{cin>>x;
sum=sum+x;
i++;
}
cout<<"\n SUM ="<<sum<<"\t AGEN PLEASE ";
}
cout<<"THANK YOU \n THE SUM = \t"<<sum <<endl;
}
void main ()
{double x=0,sum=0;
ds(x,sum);
system("pause"); }
Comments
Post a Comment