The 0x02-functions_nested_loops module teaches you to write modular, reusable code. You’ll create custom functions, work with header files, implement nested loops, and build practical programs like times tables and character validators.
#include "main.h"/** * print_alphabet - Entry point *Description: This program prints the alphabet in lowercase *followed by a new line. *Return: nothing*/void print_alphabet(void){char alphabet;for (alphabet = 'a'; alphabet <= 'z'; alphabet++)_putchar(alphabet);_putchar('\n');}
#include <unistd.h>#include "main.h"/** * main - Entry point *Description: This program prints prints _putchar, *followed by a new line *Return: 0 on success*/int main(void){char word[8] = "_putchar";int i;for (i = 0; i < 8; i++)_putchar(word[i]);_putchar('\n');return (0);}
The _putchar() function is a custom implementation of putchar. The underscore prefix distinguishes it from the standard library version.
#include "main.h"/** * _islower - Entry point * @c: The character to check *Description: checks for lowercase character *Return: 1 if c is lowercase and 0 otherwise*/int _islower(int c){return (c >= 97 && c <= 122);}
#include "main.h"/** * _isalpha - Entry point * @c: The character to check *Description: if c is alphabet or not *Return: 1 if c is uppercase or lowercase and 0 otherwise*/int _isalpha(int c){return ((c >= 65 && c <= 90) || (c >= 97 && c <= 122));}
The || operator means “OR”. The function returns true if the character is either uppercase (65-90) or lowercase (97-122).
#include "main.h"/** * add - function that adds two integers * @n: first integer * @k: second integer * Description: function that adds two integers * Return: sum of n and k */int add(int n, int k){return (n + k);}
Nested loops allow you to work with multidimensional patterns:
9-times_table.c
#include "main.h"/** * times_table - function that prints the 9 times table, starting with 0 * Description: function that prints the 9 times table, starting with 0 * Return: void */void times_table(void){int i, j, k;for (i = 0; i <= 9; i++){for (j = 0; j <= 9; j++){k = i * j;if ((k / 10) == 0){if (j != 0)_putchar(' ');_putchar(k + '0');if (j == 9)continue;_putchar(',');_putchar(' ');}else{_putchar((k / 10) + '0');_putchar((k % 10) + '0');if (j == 9)continue;_putchar(',');_putchar(' ');}}_putchar('\n');}}
Breaking down the logic:
Outer Loop
Inner Loop
Calculation
Formatting
for (i = 0; i <= 9; i++)
Controls the rows (0 through 9)
for (j = 0; j <= 9; j++)
Controls the columns (0 through 9)
k = i * j;
Computes the product for current row and column
if ((k / 10) == 0) /* Single digit */else /* Two digits */
void print_rectangle(int width, int height){ int i, j; for (i = 0; i < height; i++) /* Rows */ { for (j = 0; j < width; j++) /* Columns */ _putchar('#'); _putchar('\n'); }}
void print_triangle(int size){ int i, j; for (i = 1; i <= size; i++) /* Row number */ { for (j = 0; j < i; j++) /* Print i characters */ _putchar('#'); _putchar('\n'); }}