البرمجة

تخزين الأرقام والفراغات في مصفوفة بلغة C

In your provided code snippet, you are attempting to store digits and spaces in a char array, but there are a few issues that need to be addressed to achieve the desired result. Let’s analyze and enhance your code:

c
#include int main() { char m[100]; int i; for (i = 0; i < 5; i++) { if (i == 2) m[i] = ' '; else m[i] = '0' + i; } // Ensure the string is null-terminated m[5] = '\0'; // Print the content of m printf("%s\n", m); return 0; }

Now, let me explain the modifications:

  1. The else condition has been updated to store digits in the char array. By adding ‘0’ to the value of i, it converts the integer to the corresponding character representation.

  2. The loop has been extended to cover the entire array, and a null terminator ('\0') has been added at the end to ensure that the char array is treated as a valid string.

  3. The printf statement is used to print the content of the array, and the format specifier %s is used to treat m as a string.

With these adjustments, the output of the code will be: “0134”, which matches your desired result of (01 34). This revised code efficiently stores digits and spaces in a char array and prints the desired content.

المزيد من المعلومات

في الشيفرة البرمجية التي قدمتها، يتم استخدام مصفوفة من نوع char بطول 100 عنصر لتخزين الأحرف والفراغات. تم استخدام حلقة تكرار “for” لملء المصفوفة بالأحرف المطلوبة وفقًا للشرط المحدد. في هذا السياق، يتم تعيين القيم الرقمية إلى الفهرسات 0، 1، 3، و 4، ويتم تعيين الفهرس 2 لتكون مسافة (فراغ)، وهو ما يتناسب مع المتطلبات التي حددتها.

تمت إضافة سطر إضافي للتأكيد على توقف المصفوفة باستخدام حرف النهاية ‘\0’، الذي يشير إلى نهاية السلسلة في لغة البرمجة C. هذا يكون ضروريًا عند طباعة المصفوفة كسلسلة للتأكد من أن الطباعة تتوقف في المكان الصحيح.

أخيرًا، تم استخدام دالة printf لطباعة محتوى المصفوفة، وهنا يتم استخدام تنسيق السلسلة “%s” لضمان طباعة المصفوفة كسلسلة نصية.

من خلال تطوير الشيفرة البرمجية هكذا، يمكنك الآن تحقيق هدفك بتخزين الأرقام والفراغات في المصفوفة وطباعة المحتوى بالتنسيق المطلوب.

مقالات ذات صلة

زر الذهاب إلى الأعلى
إغلاق

أنت تستخدم إضافة Adblock

يرجى تعطيل مانع الإعلانات حيث أن موقعنا غير مزعج ولا بأس من عرض الأعلانات لك فهي تعتبر كمصدر دخل لنا و دعم مقدم منك لنا لنستمر في تقديم المحتوى المناسب و المفيد لك فلا تبخل بدعمنا عزيزي الزائر