CS5 SRC Code
CS5 SRC Code
1 // Logical operators
2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user to agree
9 char c = get_char("Do you agree? ");
10
11 // Check whether agreed
12 if (c == 'Y' || c == 'y')
13 {
14 printf("Agreed.\n");
15 }
16 else if (c == 'N' || c == 'n')
17 {
18 printf("Not agreed.\n");
19 }
20 }
meow0.c
1 // Better design
2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 int i = 3;
8 while (i > 3)
9 {
10 printf("meow\n");
11 i--;
12 }
13 }
meow2.c
1 // Better design
2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 int i = 3;
8 while (i > 3)
9 {
10 printf("%i\n", i);
11 i--;
12 }
13 }
meow3.c
1 // Better design
2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 int i = 0;
8 while (i < 3)
9 {
10 printf("meow\n");
11 i++;
12 }
13 }
meow4.c
1 // Better design
2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 for (int i = 0; i < 3; i++)
8 {
9 printf("meow\n");
10 }
11 }
meow5.c
1 // Abstraction
2
3 #include <stdio.h>
4
5 void meow(void);
6
7 int main(void)
8 {
9 for (int i = 0; i < 3; i++)
10 {
11 meow();
12 }
13 }
14
15 // Meow once
16 void meow(void)
17 {
18 printf("meow\n");
19 }
meow6.c
1 // Scope error
2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int add(void);
7
8 int main(void)
9 {
10 // Prompt user for x
11 int x = get_int("x: ");
12
13 // Prompt user for y
14 int y = get_int("y: ");
15
16 // Perform addition
17 int z = add();
18 printf("%i\n", z);
19 }
20
21 int add(void)
22 {
23 return x + y;
24 }
calculator2.c
1 // Uses %f
2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for x
9 int x = get_int("x: ");
10
11 // Prompt user for y
12 int y = get_int("y: ");
13
14 // Divide x by y
15 printf("%f\n", x / y);
16 }
calculator7.c
1 // Type casting
2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for x
9 int x = get_int("x: ");
10
11 // Prompt user for y
12 int y = get_int("y: ");
13
14 // Divide x by y
15 float z = (float) x / (float) y;
16 printf("%f\n", z);
17 }
calculator9.c
1 // Floating-point imprecision
2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for x
9 int x = get_int("x: ");
10
11 // Prompt user for y
12 int y = get_int("y: ");
13
14 // Divide x by y
15 float z = (float) x / (float) y;
16 printf("%.20f\n", z);
17 }
calculator10.c