Menu
CoddyTech

حلقات for ذات الفهارس

الدرس 14 من 48 في دورة C# لمطوري C++ على Coddy.

صياغة الحلقة المفهرسة مألوفة في C++، لكن فهرسة المصفوفات في C# تؤدي إلى استثناء عند تجاوز حدودها. وقد يؤدي الخلط بين الفهارس ذات الإشارة والفهارس غير ذات الإشارة في C++ إلى أخطاء إضافية؛ لذا استخدم حدودًا محددة بعناية، وحوّل size() إلى الخاصية المناسبة Length أو Count في C#.

تجمع حلقة for بين التهيئة وشرط منطقي وتحديث. استخدم مقارنة أقل من صارمة مع Length للبقاء ضمن الحدود. يوجد متغير الحلقة ضمن النطاق الذي أُعلن فيه. اجمع القيم في متغير أُعلن عنه قبل الحلقة.

مرجع C++

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
int total=0;
for(int i=0;i<3;i++) total+=i;
cout << total << "\n";
}

تعليمات C# داخل Main

int total = 0;
for (int i = 0; i < 3; i++) total += i;
Console.WriteLine(total);

هذه مقتطفات تعليمية مركّزة. تتضمن ملفات التحدي أغلفة تنفيذية كاملة؛ وتعرض المقاطع أعلاه التصريحات والتعليمات ذات الصلة.

المخرجات المرجعية:

3

مخرجات C#:

3
challenge icon

التحدي

سهل

أعِد مجموعًا مرجحًا، بحيث يُضرب الفهرس في القيمة لكل عنصر في مصفوفة أعداد صحيحة مفصولة بفواصل. تبدأ الفهارس من الصفر. يُعيد الإدخال الفارغ صفرًا.

عدّل ملفات C# غير المقفلة. يقرأ الملف المقفول الظاهر Main.cs الأسطر الموضحة، ويستدعي Exercise.Solve، ويتحقق من عدم تعديل الإدخال، ثم يطبع النتيجة متبوعة بسطر جديد أخير. التزم بواجهات API المُعلنة. لا تُضف Main ثانيًا ولا تطبع مخرجات تشخيصية.

جرّب بنفسك

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);

var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس C# لمطوري C++

تدرّب بنفسك: مترجم C# عبر الإنترنت