File tree Expand file tree Collapse file tree 3 files changed +88
-0
lines changed Expand file tree Collapse file tree 3 files changed +88
-0
lines changed Original file line number Diff line number Diff line change
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.
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments