0% found this document useful (0 votes)
43 views

Stdio.h: This Is A Command Printing A Text Ex.

This document provides examples of code formatting, control structures, functions, and common errors in C programming. It includes: 1) Examples of basic C code formatting including printf statements, comments, and function definitions. 2) Examples of common loops (while, for) and conditional statements (if/else) to control program flow. 3) Examples of defining and calling functions, including functions that return values. 4) Descriptions of common errors like integer overflow from limited byte representation of data types, and floating-point imprecision from finite bit representation of real numbers.

Uploaded by

Bryan James Lin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Stdio.h: This Is A Command Printing A Text Ex.

This document provides examples of code formatting, control structures, functions, and common errors in C programming. It includes: 1) Examples of basic C code formatting including printf statements, comments, and function definitions. 2) Examples of common loops (while, for) and conditional statements (if/else) to control program flow. 3) Examples of defining and calling functions, including functions that return values. 4) Descriptions of common errors like integer overflow from limited byte representation of data types, and floating-point imprecision from finite bit representation of real numbers.

Uploaded by

Bryan James Lin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

CODE FORMAT:

printf(“text\n”);
~~this is a command printing a text
#include <program.h>
~~ex. <stdio.h>
Int main(void)
{
<<place command here>> printf(“hello, world\n”); <<this is an example>>
}
~~”main” is the standard name in C that indicate default function in a program
~~”include” is a command that indicates inclusion of other programs such as stdio.h
FOREVER LOOP
while (boolean condition is true)
{
command
}
CERTAIN TIME LOOP
for (int i = 0; i < 50; i++)
{
command
}
~~”int i = 0” an initialization of a variable, “int” (variable type), “i" (variable name), “0” (initial value)
~~”i < 50” is the Boolean expression that for loop checks to determine continuing
~~”i++” is an expression in C that adds 1 to the value of “i”
if (x < y)
{
command
}
else if (x > y)
{
command
}
else
{
command
}
COMPILER
~~”clang “file name” – a command for compiling

- rmdir : removes directories


FUNCTIONS

- get_char
- get_double
- get_float
- get_int
- get_long_long
- get_string

#include <stdio.h>
int main(void)
{
string s = get_string(“Name: “);
printf(“hello, %s\n”, s);
}
o
We can save, compile, and run this file as int.c . We can use another tool in the IDE
called make to compile it. By simply running make int , make will take the file int.c and
use a compiler to compile it into int , which we can run with ./int .
o At first, we get several errors. Usually, we can start by fixing the first error, save, compile
again, and repeat until our program compiles without errors.
o The first error here is telling us that get_int isn’t actually declared. In fact, it’s defined in
another library, or set of code we can include, alongside stdio.h . get_int , along with
other functions, live in cs50.h , a library written by CS50 staff to help make tedious tasks
easier. So we simply need to add #include <cs50.h> at the top of our file. (And the source
code for the library is stored in a common place in the IDE, where the compiler knows to
look for it.)
o Now we can make our file again, and notice that we didn’t provide the
integer i into printf to plug into our string.
o We add it, and our program compiles and runs as we’d expect, with this final code:
o #include <cs50.h>
o #include <stdio.h>
o
o int main(void)
o {
o int i = get_int("Integer: ");
o printf("hello, %i\n", i);

o The get_int function prompts the user over and over, until it receives an integer.
 Let’s take a look at ints.c:
 // Integer arithmetic

 #include <cs50.h>
 #include <stdio.h>

 int main(void)
 {
 // Prompt user for x
 int x = get_int("x: ");

 // Prompt user for y
 int y = get_int("y: ");

 // Perform arithmetic
 printf("%i plus %i is %i\n", x, y, x + y);
 printf("%i minus %i is %i\n", x, y, x - y);
 printf("%i times %i is %i\n", x, y, x * y);
 printf("%i divided by %i is %i\n", x, y, x / y);
 printf("remainder of %i divided by %i is %i\n", x, y, x % y);

 We can fix this in floats.c, where we use variables of the type float , for floating-point
arithmetic:
 // Floating-point arithmetic

 #include <cs50.h>
 #include <stdio.h>

 int main(void)
 {
 // Prompt user for x
 float x = get_float("x: ");

 // Prompt user for y
 float y = get_float("y: ");

 // Perform division
 printf("%f divided by %f is %f\n", x, y, x / y);

oNotice that we use %f instead of %i , to indicate that a float should be substituted in.
o If we wanted to control the number of decimal points printed out, we could
write %.10f where we want the variable to be substituted in.
o If we simply used %f but passed in integers, the compiler would find it to be an error.
 Let’s look at how we can use conditions:

 // Conditions and relational operators



 #include <cs50.h>
 #include <stdio.h>

 int main(void)
 {
 // Prompt user for x
 int x = get_int("x: ");

 // Prompt user for y
 int y = get_int("y: ");

 // Compare x and y
 if (x < y)
 {
 printf("x is less than y\n");
 }
 else if (x > y)
 {
 printf("x is greater than y\n");
 }
 else
 {
 printf("x is equal to y\n");
 }

o All we did is what set up our program to use the example of conditions we say before.
 Let’s look at noswitch.c:
 #include <cs50.h>
 #include <stdio.h>

 int main(void)
 {
 char c = get_char("Answer: ");

 if (c == 'Y' || c == 'y')
 {
 printf("yes\n");
 }
 else if (c == 'N' || c == 'n')
 {
 printf("no\n");
 }
 else
 {
 printf("error\n");
 }

oWe get a character c , and compare it to either Y or y , or N or n . We use == for a


comparison, since a single = assigns a value. And C uses || to represent a logical or, where
only one of the expressions need to be true for that condition to be followed
and && for and, where both expressions must be true.
o We could have had an if for Y and an if for y , but using one condition means that we
don’t need to copy and paste the code that should be run into two places. Correctness is one
aspect of code, but design is another. Style, or the indentation, comments, and variable
naming, is yet another aspect.
o Note that we use single quotes around characters, to distinguish them from strings, which
we use double quotes to indicate.
 Let’s look at another way to implement this program:

 // switch

 #include <cs50.h>
 #include <stdio.h>

 int main(void)
 {
 // Prompt user for answer
 char c = get_char("Answer: ");

 // Check answer
 switch (c)
 {
 case 'Y':
 case 'y':
 printf("yes\n");
 break;
 case 'N':
 case 'n':
 printf("no\n");
 break;
 }

o A switch is another construct in C where the value of a variable is compared to various


cases, and the indented code beneath a matching case will be executed.
o Notice that we use break to indicate that the switch should end. Otherwise, once a
matching case is found, all of the code below it will run.
 Let’s write our own function that returns a value:
 // Return value

 #include <cs50.h>
 #include <stdio.h>

 int square(int n);

 int main(void)
 {
 int x = get_int("x: ");
 printf("%i\n", square(x));
 }

 // Return square of n
 int square(int n)
 {
 return n * n;

o Line 5 declares the prototype, or definition, of a function we will write, called square .
The int before square indicate that square will return an int , and int n inside the
parentheses indicate that square takes in an int that it will refer to as n . We need a
prototype because our compiler for C reads in files from top to bottom, and
the main function calls square before it’s defined unless we have that line above it.
o Line 10 calls square , passing in x , and the return value is not stored but passed directly
to printf , which will substitute it in the string and print it to the screen. We could define a
variable like int squaredvalue above, and then substitute it in, but since we are only
using it once after we create it, it’s considered better design to include it directly where we
use it.
o Finally, in line 14, we write the code for square , and return our desired value with
the return keyword.

Overflow
 In our computers, the number of bytes in our memory is finite. As a result, we can store only so
much data. In C, each type of data has a fixed number of bytes allocated to instances of it. For
example, every int has only 4 bytes in the CS50 IDE.
 As a result, one problem we can run into is integer overflow. Imagine that we have a binary
number with 8 bits:
1 1 1 1 1 1 1 0

 If we added 1 to that, we’ll get 1 1 1 1 1 1 1 1 , but what happens if we add another 1 to


that? We’ll start carrying over all the 0 s to get 0 0 0 0 0 0 0 0 , but we don’t have an extra
bit to the left to actually store that larger value.
 We can see this in a program, overflow.c:
 // Integer overflow

 #include <stdio.h>
 #include <unistd.h>

 int main(void)
 {
 // Iteratively double i
 for (int i = 1; ; i *= 2)
 {
 printf("%i\n", i);
 sleep(1);
 }

 If we compile and run this, we see:


 1
 2
 4
 8
 16
 ...
 1073741824
 overflow.c:9:25: runtime error: signed integer overflow: 1073741824 * 2 cannot be
represented in type 'int'
 -2147483648
 0
 0

...

o We see that our program noticed an error, as we doubled i too many times for its value to
fit into the bytes allocated for it.
 Another bug can arise when we have floating-point imprecision.
 Let’s write a simple program to see this firsthand:
 #include <stdio.h>

 int main(void)
 {
 printf("%.55f\n", 1.0 / 10.0);

o The new part, %.55f , just tells printf to print 55 digits after the decimal point.
 Now when we compile and run this, we get:
0.100000000000000000555111512312578...
 Remember that floats have a finite number of bits. But there are an infinite number of real
numbers, so a computer has to round and represent some numbers inaccurately. So in this
case, the closest approximation a computer can make to 0.1 is that number.
 There are several examples in the real world where these issues create limitations or even
dangerous bugs.
 Next time, we’ll learn how we can deal with these issues!

GUI (Graphical User-interface)


Keyboard Commands:
~~can be used to any UNIX-based system

- ls : lists content of current directory


- cd: changes directory
o “.” – shortcut for current directory
o “cd” – redirects to parent directory
o cd “folder name within directory”
o cd .. – return up to upper directory
- pwd: present directory
- ctrl + L: clear terminal window workspace
- mkdir: create a new directory
o mkdir “new directory name”
- cp: copying a file within the directory
o cp “name of copied file” “new name of copied file”
o cp -r : copy the whole directory
 (r)ecursive
o a
- rm: removing or deleting a file (will confirm if you really want to delete but will permanently delete after
typing “y”/”yes”
o rm -f “file name”: gets rid of the file without confirmation
o rm -r “file name”: gets rid of the whole directory
o rm -rf “file name “: gets rid of whole directory without confirmaton
- mv: move/rename a file
o mv “current file name” “new file name”

Basic Data Types

- int (integers) – always take up 4 bytes (32bits)


o -2^31 – 2^31
- unsigned int
o doubles the positive range values disallows negative values
- NOTE: other types are short, long… not just “unsigned”
- char (characters) – type used for variables
- float (values with decimal point) – take up to 4 bytes (32bits)
- double (double precision) – always take up to 8 bytes (64bits)
- void – type, but not a data type. It returns nothing and has no parameters

CS50 Data Types

- bool – type used only in <cs50.h>


- string – used for variables to store a series of characters

~~Creating variable

- int number;
- char letter;
- int height, width;
- float sqrt2, sqrt3, pi;

<<only use declare a variable when you need it (for design)>>


int number; // declaration
number = 17; // assignment
char letter; // declaration
letter = ‘H’ // assignment
Operators

You might also like