1. forदर्ज की गई पंक्तियों की संख्या की गणना करने के लिए लूप का उपयोग करना

चलो एक प्रोग्राम लिखते हैं जो 10कीबोर्ड से लाइनें पढ़ता है और उन पंक्तियों की संख्या प्रदर्शित करता है जो संख्याएं थीं। उदाहरण:

कोड व्याख्या
Scanner console = new Scanner(System.in);
int count = 0;
for (int i = 0; i < 10; i++)
{
   if (console.hasNextInt())
      count++;
   console.nextLine();
}
System.out.println(count);
Create a Scanner object to read data from the console.
Store the number of numbers in the count variable.
Loop from 0 to 10 (not including 10).

If a number is entered,
then increase count by one.
Read a line from the console and don't save it anywhere.

Display the calculated count on the screen.
टिप्पणी

यदि पंक्ति में रिक्त स्थान द्वारा अलग किए गए कई टोकन हैं, और उनमें से पहला एक संख्या है, तो hasNextInt()विधि वापस आ जाएगी true, भले ही अन्य टोकन संख्याएं न हों। इसका मतलब है कि हमारा प्रोग्राम सही तरीके से तभी काम करेगा जब हर लाइन पर सिर्फ एक टोकन डाला जाएगा।


for2. लूप का उपयोग करके क्रमगुणन की गणना करना

चलिए एक ऐसा प्रोग्राम लिखते हैं जो कुछ भी पढ़ता नहीं है, बल्कि कुछ की गणना करता है। कुछ मुश्किल उदाहरण के लिए, संख्या का भाज्य 10

किसी संख्या का क्रमगुणन n(द्वारा चिह्नित n!) संख्याओं की श्रृंखला का गुणनफल होता है: 1*2*3*4*5*..*n;

कोड व्याख्या
int f = 1;
for (int i = 1; i <= 10; i++)
   f = f * i;
System.out.println(f);
We store the product of numbers in the f variable.
Loop from 1 to 10 (inclusive).
Multiply f by the next number (save the result in f).
Display the calculated amount on the screen.

प्रारंभिक मान है f = 1, क्योंकि हम fसंख्याओं से गुणा कर रहे हैं। यदि fमूल रूप से थे 0, तो सभी संख्याओं का गुणनफल 0होगा 0


3. forस्क्रीन पर चित्र बनाने के लिए लूप का उपयोग करना

आइए एक प्रोग्राम लिखें जो स्क्रीन पर एक त्रिभुज बनाता है। पहली पंक्ति में 10तारांकन होते हैं, दूसरी - 9तारांकन, फिर 8, आदि।

कोड व्याख्या
for (int i = 0; i < 10; i++)
{
   int starCount = 10 - i;
   for (int j = 0; j < starCount; j++)
      System.out.print("*");
   System.out.println();
}
Loop through the lines (there should be 10 lines in total).

Calculate how many asterisks should be in the line.
Loop over the individual asterisks
(display starCount asterisks).
Move the cursor to the next line so the lines are separate.

हमें यहां दो नेस्टेड लूप की आवश्यकता है: इनर लूप किसी दिए गए लाइन पर तारांकन की सही संख्या प्रदर्शित करने के लिए जिम्मेदार है।

और लाइनों के माध्यम से लूप करने के लिए बाहरी पाश की जरूरत है।