0% found this document useful (0 votes)
7 views36 pages

C Programming Basics: Hello World & Conditions

The document contains code snippets demonstrating basic C programming concepts like input/output, conditionals, loops, functions, and nested loops. The snippets show incrementally more complex examples of each concept, from simple examples to those with abstraction and parameterization.

Uploaded by

Binay Adhikari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views36 pages

C Programming Basics: Hello World & Conditions

The document contains code snippets demonstrating basic C programming concepts like input/output, conditionals, loops, functions, and nested loops. The snippets show incrementally more complex examples of each concept, from simple examples to those with abstraction and parameterization.

Uploaded by

Binay Adhikari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

hello0.

1 // A program that says hello to the world


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 printf("hello, world\n");
8 }
hello1.c

1 // get_string and printf with incorrect placeholder


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 string answer = get_string("What's your name? ");
9 printf("hello, answer\n");
10 }
hello2.c

1 // get_string and printf with %s


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 string answer = get_string("What's your name? ");
9 printf("hello, %s\n", answer);
10 }
compare0.c

1 // Conditional, Boolean expression, relational operator


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for integers
9 int x = get_int("What's x? ");
10 int y = get_int("What's y? ");
11
12 // Compare integers
13 if (x < y)
14 {
15 printf("x is less than y\n");
16 }
17 }
compare1.c

1 // Conditionals that are mutually exclusive


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for integers
9 int x = get_int("What's x? ");
10 int y = get_int("What's y? ");
11
12 // Compare integers
13 if (x < y)
14 {
15 printf("x is less than y\n");
16 }
17 else
18 {
19 printf("x is not less than y\n");
20 }
21 }
compare2.c

1 // Conditionals that aren't mutually exclusive


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for integers
9 int x = get_int("What's x? ");
10 int y = get_int("What's y? ");
11
12 // Compare integers
13 if (x < y)
14 {
15 printf("x is less than y\n");
16 }
17 if (x > y)
18 {
19 printf("x is greater than y\n");
20 }
21 if (x == y)
22 {
23 printf("x is equal to y\n");
24 }
25 }
compare3.c

1 // Conditional that isn't necessary


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for integers
9 int x = get_int("What's x? ");
10 int y = get_int("What's y? ");
11
12 // Compare integers
13 if (x < y)
14 {
15 printf("x is less than y\n");
16 }
17 else if (x > y)
18 {
19 printf("x is greater than y\n");
20 }
21 else if (x == y)
22 {
23 printf("x is equal to y\n");
24 }
25 }
agree0.c

1 // Comparing against lowercase char


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')
13 {
14 printf("Agreed.\n");
15 }
16 else if (c == 'n')
17 {
18 printf("Not agreed.\n");
19 }
20 }
agree1.c

1 // Comparing against lowercase and uppercase char


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')
13 {
14 printf("Agreed.\n");
15 }
16 else if (c == 'Y')
17 {
18 printf("Agreed.\n");
19 }
20 else if (c == 'n')
21 {
22 printf("Not agreed.\n");
23 }
24 else if (c == 'N')
25 {
26 printf("Not agreed.\n");
27 }
28 }
agree2.c

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 // Opportunity for better design


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 printf("meow\n");
8 printf("meow\n");
9 printf("meow\n");
10 }
meow1.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 // Abstraction with parameterization


2
3 #include <stdio.h>
4
5 void meow(int n);
6
7 int main(void)
8 {
9 meow(3);
10 }
11
12 // Meow some number of times
13 void meow(int n)
14 {
15 for (int i = 0; i < n; i++)
16 {
17 printf("meow\n");
18 }
19 }
calculator0.c

1 // Addition with int


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 // Perform addition
15 printf("%i\n", x + y);
16 }
calculator1.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 // Helper function with arguments and return value


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int add(int a, int b);
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(x, y);
18 printf("%i\n", z);
19 }
20
21 int add(int a, int b)
22 {
23 int c = a + b;
24 return c;
25 }
calculator3.c

1 // Eliminates unnecessary variables


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int add(int a, int b);
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 printf("%i\n", add(x, y));
18 }
19
20 int add(int a, int b)
21 {
22 return a + b;
23 }
calculator4.c

1 // Addition with long


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for x
9 long x = get_long("x: ");
10
11 // Prompt user for y
12 long y = get_long("y: ");
13
14 // Perform addition
15 printf("%li\n", x + y);
16 }
mario0.c

1 // Prints a row of 4 question marks


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 printf("????\n");
8 }
mario1.c

1 // Prints a row of 4 question marks with a loop


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 for (int i = 0; i < 4; i++)
8 {
9 printf("?");
10 }
11 printf("\n");
12 }
mario2.c

1 // Prints a column of 3 bricks with a loop


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 for (int i = 0; i < 3; i++)
8 {
9 printf("#\n");
10 }
11 }
mario3.c

1 // Prints a 3-by-3 grid of bricks with nested loops


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 for (int i = 0; i < 3; i++)
8 {
9 for (int j = 0; j < 3; j++)
10 {
11 printf("#");
12 }
13 printf("\n");
14 }
15 }
mario4.c

1 // Prints a 3-by-3 grid of bricks with nested loops using a constant


2
3 #include <stdio.h>
4
5 int main(void)
6 {
7 const int n = 3;
8 for (int i = 0; i < n; i++)
9 {
10 for (int j = 0; j < n; j++)
11 {
12 printf("#");
13 }
14 printf("\n");
15 }
16 }
mario5.c

1 // Prints an n-by-n grid of bricks with nested loops


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 int n = get_int("Size: ");
9
10 for (int i = 0; i < n; i++)
11 {
12 for (int j = 0; j < n; j++)
13 {
14 printf("#");
15 }
16 printf("\n");
17 }
18 }
mario6.c

1 // Prints an n-by-n grid of bricks, re-prompting user for positive integer


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 int n = get_int("Size: ");
9 while (n < 1)
10 {
11 n = get_int("Size: ");
12 }
13
14 for (int i = 0; i < n; i++)
15 {
16 for (int j = 0; j < n; j++)
17 {
18 printf("#");
19 }
20 printf("\n");
21 }
22 }
mario7.c

1 // Prints an n-by-n grid of bricks, re-prompting user for positive integer


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Get size of grid
9 int n;
10 do
11 {
12 n = get_int("Size: ");
13 }
14 while (n < 1);
15
16 // Print grid of bricks
17 for (int i = 0; i < n; i++)
18 {
19 for (int j = 0; j < n; j++)
20 {
21 printf("#");
22 }
23 printf("\n");
24 }
25 }
calculator5.c

1 // Division with ints, demonstrating truncation


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("%i\n", x / y);
16 }
calculator6.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 // Uses float variable


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 = x / y;
16 printf("%f\n", z);
17 }
calculator8.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

1 // Division with longs, demonstrating double


2
3 #include <cs50.h>
4 #include <stdio.h>
5
6 int main(void)
7 {
8 // Prompt user for x
9 long x = get_long("x: ");
10
11 // Prompt user for y
12 long y = get_long("y: ");
13
14 // Divide x by y
15 double z = (double) x / (double) y;
16 printf("%.20f\n", z);
17 }

Common questions

Powered by AI

The structure of `agree2.c` combines logical operators within the same condition to efficiently check for acceptable user responses. It uses the '||' operator to account for uppercase and lowercase 'Y' and 'N', which simplifies the conditions and reduces redundancy since all acceptance conditions for 'Agreed' and 'Not agreed' are handled in one conditional block each rather than separate ones for each case .

Type casting in calculator8.c improves floating-point arithmetic by ensuring the division operation uses floats rather than defaulting to integer division, which truncates results to the nearest integer. Casting integers to floats before division allows for the full precision of a floating-point number, maintaining the integrity of fractional results. It highlights the importance of deliberate type conversion in programming to ensure accuracy, especially when precision is crucial, such as in scientific calculations or when dealing with currency .

Nested loops offer significant conceptual advantages in producing a grid of characters by effectively managing repetitive patterns through iteration. Unlike sequential print statements which demand individual attention for each line's format, nested loops inherently capture the structure of a grid by iterating two dimensions – rows and columns. This not only reduces code duplication and potential errors but also enables scalability, as grid dimensions can be easily adjusted by modifying loop parameters instead of altering multiple print statements .

Floating-point imprecision arises due to the way computers approximate real numbers with finite binary representations. In calculator9.c, it is shown how dividing integers implicitly converted to floats demonstrates potential unexpected results, because the binary representation might not exactly match the mathematical result. By printing results to a high precision, the inaccuracies in representation become noticeable, evidencing that operations on floats can lead to small errors, particularly significant in iterative calculations or financial computing .

The `do-while` loop in mario7.c serves to ensure that the user is prompted at least once for input, maintaining a mandatory initial execution which other loops like `while` without a guaranteed initial execution would not achieve. It is particularly beneficial when user input validation is required, as it guarantees the continuation of prompts until valid data (e.g., a positive integer) is received. This makes `do-while` particularly intuitive and useful for user interaction scenarios where an input must be obtained before any continuation .

Using nested loops and abstraction in teaching programming underscores core concepts such as iteration, modularity, and problem decomposition—vital for developing a programmer's mindset. The grid-printing exercises provide a concrete visual outcome, reinforcing loop execution order and the relationship between inner and outer loops. Meanwhile, abstraction demonstrates how complex tasks can be broken down into simpler, manageable units, promoting understanding of reusability and interface design. These exercises, therefore, transition students from syntax familiarity to mastering systemic problem-solving approaches, critical in advanced programming tasks .

In calculator1.c, the scope error arises because variables `x` and `y`, declared within the main function, are used in the `add` function without being passed as arguments. The `add` function references these variables outside their defined scope, leading to errors. Generally in programming, scope dictates the visibility and lifetime of a variable. Proper scoping ensures that functions do not inadvertently modify external states or rely on global variables, promoting better encapsulation and reducing the risk of unpredictable behavior in larger software systems .

Different implementations of the meowing functions demonstrate evolving design efficiency from repetitive code (as in meow0.c, which repeats `printf` statements) to more abstracted and reusable structures (as in meow6.c which uses a function with a parameter to determine the number of meows). This progression highlights the importance of abstraction and parameterization in programming to reduce repetition, enhance code readability, and facilitate future modifications. Using functions not only avoids duplication of logic but also makes the code cleaner and provides clearer documentation of what the code aims to accomplish .

Parameterization of functions greatly enhances the modularity and scalability of programs by allowing functions to be reused with varying inputs, instead of being hard-coded for specific tasks. For instance, in meow6.c, instead of iterating a fixed number of times within the function, passing a parameter `n` allows the `meow` function to be used flexibly for different numbers of repetitions. This modular approach invites scalable applications where changes in one module, such as the desirable count, don't necessitate extensive rewriting of other portions of the code .

Using `else if` to check for equality in integer comparisons can potentially lead to logical errors if not correctly structured. In the given example from compare3.c, after checking if `x < y` or `x > y`, the last condition `else if (x == y)` is logically equivalent to simply using `else` since the only remaining possibility is that `x` equals `y` if it is neither less than nor greater than y. This might not cause functional issues, but it reflects redundancy and inefficiency in logic design .

You might also like