Skip to content

Commit 29ba9f7

Browse files
committed
Add Day 8: Intro to pointers
1 parent 2c6a75f commit 29ba9f7

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed

Day 8/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
## Programs for Day 8
2+
1. [Nested Loop: Pattern printing](nestedLoopPattern.c)
3+
2. [Two functions to swap numbers](swap.c)
4+
5+
The first function doesn't work. We try to understand why that doesn't work.
6+
An introduction to pointers and memory is provided.
7+
Referencing and Dereferencing operators are discussed.

Day 8/nestedLoopPattern.c

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
* A program to print the pattern:
3+
*
4+
* *
5+
* * *
6+
....
7+
*/
8+
9+
#include <stdio.h>
10+
11+
int main () {
12+
13+
int n;
14+
scanf("%d", &n);
15+
16+
/* Using nested loops:
17+
* // outer loop: number of rows
18+
* for (int i = 1; i <= n; i ++) {
19+
* // inner loop: print i character
20+
* for (int j = 1; j <= i; j ++) {
21+
* printf("* ");
22+
* }
23+
* // after i-th row is printed entirely, we need to print '\n'
24+
* printf("\n");
25+
* }
26+
*/
27+
28+
// Using just one loop
29+
30+
int lineNo = 1;
31+
int count = 0;
32+
while (lineNo <= n) {
33+
if (count < lineNo) {
34+
printf("* ");
35+
count ++;
36+
} else {
37+
printf("\n");
38+
count = 0;
39+
lineNo ++;
40+
}
41+
}
42+
43+
return 0;
44+
}

Day 8/swap.c

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
* A program to swap two numbers
3+
*/
4+
5+
#include <stdio.h>
6+
7+
// Incorrect
8+
void swap1 (int x, int y) {
9+
int temp;
10+
// to save the original value of x
11+
temp = x;
12+
// to get value of y in x
13+
x = y;
14+
// to get original x's value in y
15+
y = temp;
16+
}
17+
18+
// Correct
19+
void swap2(int *x, int *y) {
20+
int temp = *x; // c = a
21+
*x = *y; // a = b
22+
*y = temp; // b = c
23+
}
24+
25+
int main () {
26+
27+
int x, y;
28+
scanf("%d %d", &x, &y);
29+
30+
// call function => function's name and the arguments to it
31+
// swap1(x, y);
32+
33+
swap2(&x, &y);
34+
printf("x = %d, y = %d", x, y);
35+
36+
return 0;
37+
}

0 commit comments

Comments
 (0)