Лекция 02 - Масиви

Качена е презентацията от лекцията за масиви в С.

Линк към презентацията

Задачи от час

// chars.c
#include<stdio.h>

int main() {

    char ch = 260; // Overflow, ch is [0;255]
    char ch1 = "z"; // Invalid, "" is for arrays
    char ch2 = 'az'; // Invalid, '' can hold only single char

    printf("260 is %c char\n", ch);

    return 0;
}
// vowels.c
#include<stdio.h>

int is_vowel(char);
int is_consonant(char);

int main() {

    printf("%d\n", is_vowel(42)); // Points to some character in ASCII
    printf("%d\n", is_vowel('a'));
    printf("%d\n", is_vowel('b'));
    printf(" is consonant b = %d\n", is_consonant('b'));

    return 0;
}

int is_vowel(char ch) {
   if (ch == 'a'
        || ch == 'o'
        || ch == 'e'
        || ch == 'u'
        || ch == 'i') { // same as ch == 97
        return 1;
   }

   return 0;

   // Short version
   // return ch == 'a' || ch == 'o' ...
}

int is_consonant(char ch) {
    return !is_vowel(ch);
}
// consonants.c
#include<stdio.h>

int is_vowel(char);
int is_consonant(char);
int how_many_consonants(char[10]);

int main() {

    int i = 5;
    printf("%d %d\n", i++, ++i); // 5 7

    char arr[] = {'H', 'e', 'l', 'l', 'o', '\0'};
    char hello[] = "Hello world!";
    printf("Hello contains %d consonants\n", how_many_consonants(arr));
    printf("Hello World! contains %d consonants\n", how_many_consonants(hello));

    return 0;
}

int how_many_consonants(char arr[10]) {

    int consonants = 0;

    for (int i = 0; arr[i] != '\0'; ++i) {
        if (is_consonant(arr[i])) {
            consonants++;
        }

        // Short version
        // consonants += is_consonant(arr[i]);
    }

    return consonants;
}

int is_vowel(char ch) {
   if (ch == 'a'
        || ch == 'o'
        || ch == 'e'
        || ch == 'u'
        || ch == 'i') { // same as ch == 97
        return 1;
   }

   return 0;

   // Short version
   // return ch == 'a' || ch == 'o' ...
}

int is_consonant(char ch) {
    return !is_vowel(ch);
}
// task 4) and 5) from the presentation
#include<stdio.h>

int is_divisior(int num, int div);
int divide_all(int arr[], int);

int main() {

    int i = 5;
    printf("%d %d\n", ++i, i++);

    printf("3 div 5 = %d\n", is_divisior(3, 5));
    printf("0 div 2 = %d\n", is_divisior(0, 2));

    int arr[] = {3, 6, 9, 12};

    printf("%d devide all = %d\n", 3, divide_all(arr, 3));

    return 0;
}

int divide_all(int arr[10], int div) {
    for (int i = 0; i < 10; ++i) {
        if (!is_divisior(arr[i], div)) {
            return 0;
        }
    }

    return 1;
}

int is_divisior(int num, int div) {
    if (num % div == 0) {
        return 1;
    }

    return 0;

    // Short version
    // return !(num % div);
}

Категории:

Обновена: