fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@@ -0,0 +1,97 @@
---
title: Dynamic Memory Management
---
# Dynamic Memory Management
Sometimes you will need to allocate memory spaces in the heap also known as the dinamic memory. This is particulary usefull when you do not know during compile time how large a data structure (like an array) will be.
## An Example
Here's a simple example where we allocate an array asking the user to choose the dimension
```C
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int arrayDimension,i;
int* arrayPointer;
scanf("Please insert the array dimension:%d",arrayDimension);
arrayPointer = (int*)malloc(sizeof(int)*arrayDimension);
if(arrayPointer == NULL){
printf("Error allocating memory!");
return -1;
}
for(i=0;i<arrayDimension;i++){
printf("Insert the %d value of the array:",i+1);
scanf("%d\n",arrayPointer[i]);
}
free(arrayPointer);
return 0;
}
```
As you can see in order to allocate a space in the dinamic memory you need to know how pointers work in C.
The magic function here is the `malloc` which will return as output a void pointer (it is a pointer to a region of unknown data type) to the new memory space we've just allocated.
Let's see how to use this function step by step:
## Allocating an array during runtime
```C
sizeof(int)
```
Let's start from `sizeof`. The `malloc` needs to know how much space allocate for your data. In fact a `int` variable will use less storage space then a `double` one.
It is generally not safe to assume the size of any datatype. For example, even though most implementations of C and C++ on 32-bit systems define type int to be four octets, this size may change when code is ported to a different system, breaking the code.
`sizeof` as it's name suggests generates the size of a variable or datatype.
```C
arrayPointer = (int*) malloc(sizeof(int) * arrayDimension);
```
In this example, malloc allocates memory and returns a pointer to the memory block. The size of the block allocated is equal to the number of bytes for a single object of type int multiplied by `arrayDimension`, providing the system has enough space available.
But what if you do not have enough space or `malloc` can not allocate it for some other reasons?
## Checking the malloc output
This do not happens commonly but it is a very good practice to check the value of your pointer variable after allocating a new space of memory.
```C
if(arrayPointer == NULL)
printf("Error allocating memory!");
```
This will also be very usefull during your debug phase and will prevent some possible errors using the last function used in the example.
## A word on free()
Usually variables are automatically de-allocated when their scope is destroyed, freeing the memory they were using.
This simple does not happen when you manually allocate memory using the `malloc`.
To prevent memory leaks in more complex programs and in order to not create garbage in the system you have to free the memory area recently used before terminating your code execution.
```C
free(arrayPointer);
```
In the end you will understand for sure that checking `arrayPointer` value was necessary to prevent an error using the `free` function.
If `arrayPointer` value was equal to `NULL` you could have expirencied some kind of bug.
## Other functions similar to malloc
Sometimes you need to not only reserve a new area of memory for your operations, you might also need to initialize all bytes to zero.
This is what `calloc` is used for.
In other cases you wish to resize the amount of memory a pointer points to. For example, if you have a pointer acting as an array of size `n` and you want to change it to an array of size `m`, you can use `realloc`.
```C
int *arr = malloc(2 * sizeof(int));
arr[0] = 1;
arr[1] = 2;
arr = realloc(arr, 3 * sizeof(int));
arr[2] = 3;
```
## Common errors
The improper use of dynamic memory allocation can frequently be a source of bugs as you have seen before.
Most common errors are:
* Not checking for allocation failures
Memory allocation is not guaranteed to succeed, and may instead return a null pointer.
Using the returned value, without checking if the allocation is successful, invokes undefined behavior. This usually leads to crash (due to the resulting segmentation fault on the null pointer dereference), but there is no guarantee that a crash will happen so relying on that can also lead to problems.
* Memory leaks
Failure to deallocate memory using `free` leads to buildup of non-reusable memory, which is no longer used by the program.
* Logical errors
All allocations must follow the same pattern: allocation using `malloc`, usage to store data, deallocation using `free`. If you not follow this pattern usually segmentation fault errore will be given and the program will crash. These errors can be transient and hard to debug for example, freed memory is usually not immediately reclaimed by the system, and dangling pointers may persist for a while and appear to work.

View File

@@ -0,0 +1,88 @@
---
title: Structured data types
---
# Structured data types in C
During your programming experience you may feel the need to define your own type of data. In C this is done using two keywords: `struct` and `typedef`.
Structures and unions will give you the chance to store non-homogenous data types into a single collection.
## Declaring a new data type
```C
typedef struct student_structure{
char* name;
char* surname;
int year_of_birth;
}student;
```
After this little code `student` will be a new reserved keyword and you will be able to create variables of type `student`.
Please mind that this new kind of variable is going to be structured which means that defines a physically grouped list of variables to be placed under one name in a block of memory.
## New data type usage
Let's now create a new `student` variable and initialize its attributes:
```C
student stu;
strcpy( stu.name, "John");
strcpy( stu.surname, "Snow");
stu.year_of_birth = 1990;
printf( "Student name : %s\n", stu.name);
printf( "Student surname : %s\n", stu.surname);
printf( "Student year of birth : %d\n", stu.year_of_birth);
```
As you can see in this example you are required to assign a value to all variables contained in your new data type.
To access a structure variable you can use the point like in `stu.name`.
There is also a shorter way to assign values to a structure:
```C
typedef struct{
int x;
int y;
}point;
point image_dimension = {640,480};
```
Or if you prefer to set it's values following a different order:
```C
point img_dim = { .y = 480, .x = 640 };
```
## Unions vs Structures
Unions are declared in the same was as structs, but are different because only one item within the union can be used at any time.
```C
typedef union{
int circle;
int triangle;
int ovel;
}shape;
```
You should use `union` in such case where only one condition will be applied and only one variable will be used.
Please do not forget that we can use our brand new data type too:
```C
typedef struct{
char* model;
int year;
}car_type;
typedef struct{
char* owner;
int weight;
}truck_type;
typedef union{
car_type car;
truck_type truck;
}vehicle;
```
## A few more tricks
* When you create a pointer to a structure using the `&` operator you can use the special `->` infix operator to deference it. This is very used for example when working with linked lists in C
* The new defined type can be used just as other basic types for almost everything. Try for example to create an array of type `student` and see how it works.
* Structs can be copied or assigned but you can not compare them!

View File

@@ -0,0 +1,56 @@
---
title: Appendix
---
# C: An Appendix
Because C is such a low-level language, there are a lot of terms that come up that aren't found in a lot of other languages. Here's an appendix to making understanding them easier.
## Compilation
The compilation is the process of taking the human-readable code and turning it into machine-readable code. This process is performed by a compiler.
## Compiler
A compiler is a program that compiles code, meaning it changes it from something human-readable into something machine-readable.
## Debugging/Debugger
Debugging is the process of removing errors ("bugs") from your code. A debugger is a helpful tool that makes that easier.
## GNU+Linux
GNU+Linux is the technically accurate term for what is commonly referred to as "Linux". Linux is a kernel- it's a set of programs that allow software to interact with hardware. When combined with GNU, it becomes an operating system, which allows a person to interact with it.
## GUI
Graphical User Interface. A GUI will allow you to interact with a program by pointing and clicking rather than having to type in commands.
## Header Files
Header files are files containing function declarations that are defined in other source files. These are typically 'included' at the top of a source file.
## IDE
Integrated Development Environment. This is mostly an editor but includes tools to check syntax, format code style, compile, and debug a program, which makes writing code easier.
## Human-readable
The human-readable code is code that can be read by a person- it's not in binary or machine code.
## Libraries
Libraries are useful sets of code that give more functions and features in the language.
## Linker
A piece of Software that combines multiple Object files (usually compiled source code of libraries) into one executable file.
## Low-Level language
A low-level programming language contains binary or assembly code which has little or no abstraction from machine level instructions.
## Machine Code
Machine code is the code that the machine can understand. Remember that computers use numbers, not English, to run.
## Newline
A newline is what gets printed when you hit Enter, and is an example of a whitespace character. You can also add a newline to the output of your program by including '\n' in your print statement.
## Object File
A file that contains Object Code (Machine Code). The file contains output some compilation, meaning it will contain machine code/assembly code.
## Linker
A utility program that has the ability to take object files and creating an executable file, library file or another object file. Another name for the Linker is a 'Loader'.
## Pointer
A pointer is a variable that contains the memory address of another variable. Arrays, Structures and Functions explicitly use pointers which can help produce efficient and easy-to-read code.
## Whitespace
Whitespace is the characters that you don't see when you type but are there anyway. For example, you can't see spaces, but there is a lot here. Newlines are also whitespace characters, as are tabs.

View File

@@ -0,0 +1,170 @@
---
title: Arrays and Strings
---
# Arrays in C
Arrays allow for a set of variables to be grouped together as one variable. This is useful in its own right, but also because strings fall into this category. Strings, which are how we represent words and sentences in computer languages, are just collections of character variables. Therefore, we represent strings using arrays in C.
## Making an Array
A normal integer variable would be declared like so:
```C
int my_variable;
```
To declare this as an array, and make it an array of 5 integers, it can be declared like this:
```C
int my_array[5];
```
This will produce an array called `my_array` that can hold 5 integers. However, none of the positions in the array have been set (yet). You could declare the array, and have the values be set at the beginning:
```C
int my_array[] = {1, 5, 3, 6, 2};
```
Notice that in this example, we didn't bother specifying a number in the square brackets. This is because the curly brackets have values in them that will be assigned to each position in the array. You could put a number in the brackets anyway, as long as you made sure to create enough memory locations to store the values you've passing in.
When initializing an array, you can provide fewer values than array elements. For example, the
following statement initializes only the first two elements of my_array:
float my_array[5] = {5.0, 2.5};
If you partially initialize an array, the compiler sets the remaining elements to zero.
Now that the array has been declared with 5 values, it has 5 memory locations. Consider this table for a visual example of that:
| Position | 0 | 1 | 2 | 3 | 4 |
|----------|---|---|---|---|---|
| Value | 1 | 5 | 3 | 6 | 2 |
Notice that even though there are 5 memory locations, the array positions only go up to 4. This is because arrays in C (and most other languages) start at 0, because arrays are implemented using pointers. When you call a position in an array, you're really calling that memory location plus a certain number. To get the beginning of the array, move 0 places in memory, to get the position after that, move one place in memory, and so on.
Here's an example of setting the array to 9 at position 1:
```C
my_array[1] = 9;
```
So it's just like any other variable, except it has multiple values to access using the number within the square brackets. Values can be returned that way, too:
```C
int variable = my_array[4];
```
This will declare `variable` to be an integer equal to the value at position 4 of `my_array`. However, because `variable` is a single `int`, and not an array, this is **not** code that will have the right outcome:
```C
// This code will NOT work properly!
int variable = my_array;
```
Any integer can be placed in the square brackets to get a position in the array. Those integers can be variables, too. Take a look at this example, which prints the contents of an array:
```C
#include <stdio.h>
int main(void) {
int my_array[] = {1, 1, 2, 3, 5, 7, 12};
for(int count = 0; count < 7; count++) {
printf("%i, \n", my_array[count]);
}
return 0;
}
```
## Strings
Arrays are sets of variables, and strings are sets of characters. As a result, we can represent strings with an array. You _can_ declare something in the same way as before, but you'll need to place '\0' as one of your values (more on that in a minute!):
```C
char hello_world[] = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0'};
```
Yikes. That's not really a great solution. Thankfully, C provides a better way with strings in mind:
```C
char hello_world[] = "Hello world!";
```
That's much nicer. It doesn't even require you to place the '\0' at the end, either. So what was that?
### Null Termination
Strings in C are null terminated, meaning that they end with the null character. This way, the compiler (and your and everyone else's) code will know where the string ends: once the character is null, the string is over.
Of course, there is no 'null' button on your keyboard, but you still need to type it out somehow. That's what \0 does. Whenever the C compiler sees \0, it will insert a null character. It's just like how \n prints a newline.
### Printing Strings
Another thing C makes easier for us is the printing of strings. Rather than forcing you to print out every character in the array, you can just use the %s format specifier, and treat the string like you would any `int` or `double` value. Here's an example of the hello, world program from the very beginning, made slightly more complicated with strings:
```C
#include <stdio.h>
int main(void) {
char hello_world[] = "Hello, World!\n";
printf("%s", hello_world);
return 0;
}
```
### Playing with Strings
Printing strings is easy, but other operations are slightly more complex. Thankfully, the `string.h` library has some helpful functions to use for a number of situations.
#### Copying: `strcpy`
`strcpy` (from 'string copy') copies a string. For example, this code snippet will copy the contents of the string `second` into the string `first`:
```C
strpy(first, second);
```
Here is an example of how manual implementation of the strcpy function looks like:
void copy_string(char [] first_string, char [] second_string)
{
int i;
for(i = 0; first_string[i] != '\0'; i++)
{
first_string[i] = second_string[i];
}
}
#### Concatenate: `strcat`
`strcat` (from 'string concatenate') will concatenate a string, meaning it will take the contents of one string and place it on the end of another string. In this example, the contents of `second` will be concatenated onto `first`:
```C
strcat(first, second);
```
Here is an example of manual implementation of fuction strcat:
void string_concatenate(char [] s1, char [] s2)
{
int i = strlen(s1), j;
for(int j = 0; s2[j]; j++, i += 1)
{
s1[i] = s2[j];
}
}
#### Get length: `strlen`
`strlen` (from 'string length') will return an integer value corresponding to the length of the string. In this example, an integer called `string_length` will be assigned the length of `my_string`:
```C
string_length = strlen(my_string);
```
Here is an manual implementation of fuction strlen:
int string_length(char [] string)
{
int i;
for(int i = 0; string[i]; i++);
return i;
}
#### Compare: `strcmp`
`strcmp` (from 'string compare') compares two strings. The integer value it returns is 0 if they are the same, but it will also return negative if the value of the first (by adding up characters) is less than the value of the second, and positive if the first is greater than the second. Take a look at an example of how this might be used:
```C
if(!strcmp(first, second)){
printf("These strings are the same!\n");
} else {
printf("These strings are not the same!\n");
}
```
Notice the `!`, which is needed because this function returns 0 if they are the same. Placing the exclamation point here will make that comparison return true.
#### Split a string: `strtok`
`strtok` (from 'string token') breaks a string into a series of tokens using a delimiter. In this example, strtok breaks string str into a series of tokens using the delimiter delim:
```C
char *strtok(char *str, const char *delim);
```
# Before you go on...
## A Review
* Arrays are collections of variables.
* Arrays have separate positions that can be declared with brackets, and accessed with square brackets.
* Strings are arrays too, but we can treat them a little differently: they can be declared using double quotes, and printed using %s.
* Strings have their own library, `string.h`, which has some handy functions to use.

View File

@@ -0,0 +1,170 @@
---
title: Arrays
---
# Arrays in C
## Problems
Before trying to explain what arrays are, let's look at the code where we want to print 10 numbers given by the user in reverse order.
```C
#include <stdio.h>
int main(void) {
int a, b, c, d, e, f, g, i, j, k;
scanf("%d", &a);
scanf("%d", &b);
...
printf("%d", k);
printf("%d", j);
printf("%d", i);
... //and so on..
return 0;
}
```
So, this looks a bit tedious.<br>Up until now every variable created had some special role. But right now, it would be great if we could just store multiple values in one place and get access to the values with their place in the line maybe (first value, second etc.). Another way to look at this is, suppose you want to store a set of names, you need not create different variables for each name, instead you can create an array of names where each name has its unique identity or *index*. Also, we could use loops on them, which are things you will learn about later, but basically they do the same thing over and over again.
eg. reading from the user, or printing out values.
## Arrays in C
Arrays are containers with a given size. They contain variables of the **same type**. You can access a variable stored in the array with its *index*.
Let's look at some code:
```C
#include <stdio.h>
int main(void) {
int arr[4] = {1, 2, 3, 88};
int brr[] = {78, 65};
int crr[100] = {3};
int var = arr[0];
return 0;
}
```
And now let's break the syntax down a bit:
```C
int arr[4] = {1, 2, 3, 88};
```
Here you have created an `array` of `ints`(Integers), called `arr`. This array has 4 elements: `1`, `2`, `3`, `88`. Note the syntax!
```C
datatype name[number of elements]
```
The first element of this array is `1`, the second is `2` etc.
```C
int brr[] = {78, 65};
```
You do not have to tell the dimension beforehand. Here an array of two will be created with the elements between the curly brackets.
```C
int crr[100] = {3};
```
If you do this, then the first element is going to be `3`, but the rest of them is going to be `0`.
```C
int var = arr[0];
```
Here an int is created called `var`, and it is initialized to the 0th element of arr. **Very importart to note** that in C, indexes start at zero as opposed to 1. This means that to access the first element, the index (between the brackets) is 0, to access the second element, the index is 1 etc.
In this example `var` is going to store the value `1`.
## Overview
* A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may.
* Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.
## Multi-dimensional Arrays in C
C also supports multi-dimensional arrays.
```C
datatype name[size1][size2]...[sizeN]
```
Two-dimensional arrays are common and can be initialized using the following syntax. One can logically think of the first index as rows and the second index as columns. This example has 2 rows and 5 columns.
```C
int arr[2][5] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
```
It can be difficult to visualize a 2-dimensional array using the above syntax so developers often use optional, nested brackets to clarify the structure of the array. This is also a valid way to initialize a 2-dimensional array.
```C
int arr[2][5] = {
{0, 1, 2, 3, 4},
{5, 6, 7, 8, 9}
};
```
Two nested for loops can be used to print the contents of a 2-dimensional array in tabular format.
```C
#include <stdio.h>
int main() {
const int rows = 2, cols = 5;
int arr[rows][cols] = {
{0, 1, 2, 3, 4},
{5, 6, 7, 8, 9}
};
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
printf("%5d", arr[row][col]);
}
puts("");
}
return 0;
}
```
```C
0 1 2 3 4
5 6 7 8 9
```
## Strings
To store strings/multiple characters, we use `char arrays` in C, because the language has no special type built in. One thing to be aware of, is that a terminating null is automatically added to the end, signaling that it is the end of the string. However, you may also initialze a string with curly braces `{}` as well, but you have to manually add the terminating null.
Like so:
```C
char string[6] = "Hello"; //here you get Hello\0, which is why we need an array with the length of 6
```
Just like with the int arrays in the example above, there are several ways to assign values to char arrays:
```C
char string[] = "I do not want to count the chars in this.";
char string2[] = {'C','h','a','r',' ','b','y',' ','c','h','a','r','\0'};
char string3[] = "This is a string"
"with two lines";
```
Equivalent to the approach above, you can also create a pointer to a char array:
```C
char* string = "I do not want to count the chars in this.";
```
## Typical mistakes, tips
- When you have an array filled with values and you want to make an another array that is exactly the same as the first, never ever do this:
```C
double first[] = {2,3,7};
double second[] = first;
//Or this:
double a[5], b[5]
a = b;
```
You can **only** deal with the values in an array one by one. You **cannot assign all at once**, when you learn about pointers later, the reasons will be clear.
>(Basically, the first element of an array points to a memory address, and the elements after that are the "houses" next to that first one. So technically an array is just it's first element's memory address. When you want to assign the second array the first array, you run into error due to differing types, or you are trying to change the second memory address of the first element in the second array.)
- When you want to create an array, you have to either tell its size, or assign values to it. Do not do this:
```C
int arr[];
```
The computer has to know how big of a storage to create for the array. Later on, you will learn about ways to create containers whose size are defined later. (Again, pointers.)
- When you index out of the array, the compiler is not always going to give you an error. This is called undefined behaviour, we just do not know what is going to happen. It could lead to your program crashing, simply slowing down, anything.
```C
int test[6];
int a = test[-2];
int b = test[89];
```
The reason for C not checking the indexing bound is simple: C is an efficient language. It was made, so your program is the fastest: communicates nicely with hardware etc. A nicely written C code does not contain indexing errors, so why would C want to check while running?
- When you try to access the last element of the array. Suppose the length of the array A be 4 and while accessing the last element as
A[4] will return an error, as the the indexing starts from 0.

View File

@@ -0,0 +1,17 @@
---
title: Basic Networking
---
## Basic Networking
Basic Networking in C mainly involves opening sockets and communicating through them. This begs the question, what is a Socket?
## What is a Socket
A socket is one endpoint of a two-way communication link between two programs running on a network. An endpoint is a combination of an IP address and a port number. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.
When a program is running on a network it is available to access from different locations other than the local location. By different locations I mean all the computers on the same network can access it. But, how will they? Hence every program registers itself with a port number. Think of port number as an apartment number in a huge apartment. If a letter is sent to an apartment, the apartment number tells the post office the specific apartment he should go to.
But, how will it arrive at the apartment? Every apartment has there own unique address, the post office looks at those unique address(which is infact a string) and decides the destination of the letter. In this case, every computer connected to a network will have an IP address which is like an address used when sending a letter through the post office. Likewise, a computer connected to a network needs to know the IP addresses of the other computers on the same network to communicate with them. To communicate with a specific program on a specific computer the port number for that program is needed. (Think of the apartment number from our apartment analogy.)
## Basics of Socket Programming
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. Server forms the listener socket while client reaches out to the server.

View File

@@ -0,0 +1,231 @@
---
title: Conditional Statements
---
# Conditional Statements in C
Conditional Statements are also known as Branching Statements. They are so called because the program chooses to follow one branch or another.
## 1. if statement
This is the most simple form of the conditional statements. It consists of a Boolean expression followed by one or more statements. If the Boolean expression evaluates to **true**, then the block of code inside the 'if' statement will be executed. If the Boolean expression evaluates to **false**, then the first set of code after the end of the 'if' statement (after the closing curly brace) will be executed.
C programming language **_assumes any non-zero and non-null values as true_** and if it is **_either zero or null, then it is assumed as false_** value.
#### Syntax
```C
if(boolean_expression)
{
//Block of Statements executed when boolean_expression is true
}
```
#### Example
```C
int a = 100;
if(a < 200)
{
printf("a is less than 200\n" );
}
```
#### Result
`a is less than 200`
## 2. if...else statement
If the Boolean expression evaluates to **true**, then the if block will be executed, otherwise, the else block will be executed.
#### Syntax
```C
if(boolean_expression)
{
//Block of Statements executed when boolean_expression is true
}
else
{
//Block of Statements executed when boolean_expression is false
}
```
#### Example
```C
int a = 300;
if(a < 200)
{
printf("a is less than 200\n");
}
else
{
printf("a is more than 200\n");
}
```
#### Result
`a is more than 200`
## 3. if...else if...else statement
When using if...else if..else statements, there are few points to keep in mind -
- An **if** can have **zero or one else**'s and it **must come after any else if**'s.
- An **if** can have **zero to many else if**'s and they **must come before the else**.
- Once an **else if** succeeds, none of the remaining else if's or else's will be tested.
#### Syntax
```C
if(boolean_expression_1)
{
//Block of Statements executed when boolean_expression_1 is true
}
else if(boolean_expression_2)
{
//Block of Statements executed when boolean_expression_1 is false and boolean_expression_2 is true
}
else if(boolean_expression_3)
{
//Block of Statements executed when both boolean_expression_1 and boolean_expression_2 are false and boolean_expression_3 is true
}
else
{
//Block of Statements executed when all boolean_expression_1, boolean_expression_2 and boolean_expression_3 are false
}
```
#### Example
```C
int a = 300;
if(a == 100)
{
printf("a is equal to 100\n");
}
else if(a == 200)
{
printf("a is equal to 200\n");
}
else if(a == 300)
{
printf("a is equal to 300\n");
}
else
{
printf("a is more than 300\n");
}
```
#### Result
`a is equal to 300`
## 4. Nested if statement
It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).
#### Syntax
```C
if(boolean_expression_1)
{
//Executed when boolean_expression_1 is true
if(boolean_expression_2)
{
//Executed when both boolean_expression_1 and boolean_expression_2 are true
}
}
```
#### Example
```C
int a = 100;
int b = 200;
if(a == 100)
{
printf("a is equal to 100\n" );
if(b == 200)
{
printf("b is equal to 200\n");
}
}
```
#### Result
```bash
a is equal to 100
b is equal to 200
```
## 5. Switch Case Statement
The switch statement is often faster than nested if...else (not always). Also, the syntax of switch statement is cleaner and easy to understand.
### Syntax of switch case
```
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
```
When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute the block of code associate with the case statement until the end of switch block, or until the break statement is encountered.
The break statement is used to prevent the code running into the next case.
### Example:
```
// Program to create a simple calculator
// Performs addition, subtraction, multiplication or division depending the input from user
# include <stdio.h>
int main()
{
char operator;
double firstNumber,secondNumber;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber+secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/secondNumber);
break;
// operator is doesn't match any case constant (+, -, *, /)
default:
printf("Error! operator is not correct");
}
return 0;
}
```
### Output
```
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
```
The '-' operator entered by the user is stored in operator variable. And, two operands 32.5 and 12.4 are stored in variables firstNumber and secondNumber respectively.
Then, control of the program jumps to
```
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
```
Finally, the break statement ends the switch statement.
If break statement is not used, all cases after the correct case is executed.

View File

@@ -0,0 +1,119 @@
---
title: Data Types in C
---
# Data Types in C
There are several different ways to store data in C, and they are all unique from each other. The types of data that information can be stored as are called data types. C is much less forgiving about data types than other languages. As a result, it's important to make sure that you understand the existing data types, their abilities, and their limitations.
One quirk of C's data types is that they depend entirely on the hardware that you're running your code on. An `int` on your laptop will be smaller than an `int` on a supercomputer, so knowing the limitations of the hardware you're working on is important. This is also why the data types are defined as being minimums- an `int` value, as you will learn, is at minimum -32767 to 32767: on certain machines, it will be able to store even more values that this.
There are two categories that we can break this into: integers, and floating point numbers. Integers are whole numbers. They can be positive, negative, or zero. Numbers like -321, 497, 19345, and -976812 are all perfectly valid integers, but 4.5 is not because 4.5 is not a whole number.
Floating point numbers are numbers with a decimal. Like integers, -321, 497, 19345, and -976812 are all valid, but now 4.5, 0.0004, -324.984, and other non-whole numbers are valid too.
C allows us to choose between several different options with our data types because they are all stored in different ways on the computer. As a result, it is important to be aware of the abilities and limitations of each data type to choose the most appropriate one.
## Integer data types
#### Characters: `char`
`char` holds characters- things like letters, punctuation, and spaces. In a computer, characters are stored as numbers, so `char` holds integer values that represent characters. The actual translation is described by the ASCII standard. <a href='http://www.asciitable.com/' target='_blank' rel='nofollow'>Here's</a> a handy table for looking up that.
The actual size, like all other data types in C, depends on the hardware you're working on. By minimum, it is at least 8 bits, so you will have at least 0 to 127. Alternatively, you can use `signed char` to get at least -128 to 127.
#### Standard Integers: `int`
The amount of memory that a single `int` takes depends on the hardware. However, you can expect an `int` to be at least 16 bits in size. This means that it can store values from -32,768 to 32,767, or more depending on hardware.
Like all of these other data types, there is an `unsigned` variant that can be used. The `unsigned int` can be positive and zero but not negative, so it can store values from 0 to 65,535, or more depending on hardware.
#### Short integers: `short`
This doesn't get used often, but it's good to know that it exists. Like int, it can store -32768 to 32767. Unlike int, however, this is the extent of its ability. Anywhere you can use `short`, you can use `int`.
#### Longer integers: `long`
The `long` data type stores integers like `int`, but gives a wider range of values at the cost of taking more memory. Long stores at least 32 bits, giving it a range of -2,147,483,648 to 2,147,483,647. Alternatively, use `unsigned long` for a range of 0 to 4,294,967,295.
#### Even longer integers: `long long`
The `long long` data type is overkill for just about every application, but C will let you use it anyway. It's capable of storing at least 9,223,372,036,854,775,807 to 9,223,372,036,854,775,807. Alternatively, get even more overkill with `unsigned long long`, which will give you at least 0 to 18,446,744,073,709,551,615.
## Floating point number data types
#### Basic Floating point numbers: `float`
`float` takes at least 32 bits to store, but gives us 6 decimal places from 1.2E-38 to 3.4E+38.
#### Doubles: `double`
`double` takes double the memory of float (so at least 64 bits). In return, double can provide 15 decimal place from 2.3E-308 to 1.7E+308.
#### Getting a wider range of doubles: `long double`
`long double` takes at least 80 bits. As a result, we can get 19 decimal places from 3.4E-4932 to 1.1E+4932.
## Picking the right data type
C makes pick the data type, and makes us be very specific and intentional about the way that we do this. This gives you a lot of power over your code, but it's important to pick the right one.
In general, you should pick the minimum for your task. If you know you'll be counting from integer 1 to 10, you don't need a long and you don't need a double. If you know that you will never have negative values, look into using the `unsigned` variants of the data types. By providing this functionality rather than doing it automatically, C is able to produce very light and efficient code. However, it's up to you as the programmer to understand the abilities and limitations, and choose accordingly.
We can use the sizeof() operator to check the size of a variable. See the following C program for the usage of the various data types:
```c
#include <stdio.h>
int main()
{
int a = 1;
char b ='G';
double c = 3.14;
printf("Hello World!\n");
//printing the variables defined above along with their sizes
printf("Hello! I am a character. My value is %c and "
"my size is %lu byte.\n", b,sizeof(char));
//can use sizeof(b) above as well
printf("Hello! I am an integer. My value is %d and "
"my size is %lu bytes.\n", a,sizeof(int));
//can use sizeof(a) above as well
printf("Hello! I am a double floating point variable."
" My value is %lf and my size is %lu bytes.\n",c,sizeof(double));
//can use sizeof(c) above as well
printf("Bye! See you soon. :)\n");
return 0;
}
```
## Output:
Hello World!
Hello! I am a character. My value is G and my size is 1 byte.
Hello! I am an integer. My value is 1 and my size is 4 bytes.
Hello! I am a double floating point variable. My value is 3.140000 and my size is 8 bytes.
Bye! See you soon. :)
## The Void type
The void type specifies that no value is available. It is used in three kinds of situations:
#### 1. Function returns as void
There are various functions in C which do not return any value or you can say they return void. A function with no return value has the return type as void. For example, ```void exit (int status);```
#### 2. Function arguments as void
There are various functions in C which do not accept any parameter. A function with no parameter can accept a void. For example, ```int rand(void);```
#### 3. Pointers to void
A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function ```void *malloc( size_t size);``` returns a pointer to void which can be casted to any data type.
# Before you go on...
## A review
* The actual abilities of C data types depend on the hardware. As a result, minimum sizes are defined for the data types.
* Floating point numbers will allow you to have decimals, while integer numbers won't.
* We have some options for our integer values:
* char, which is designed for characters but stores numbers
* int, which is the standard integer data type
* short, which is a less commonly used but still available integer data type
* long, which gives a wide range of integer values
* long long, which gives an overkill range of integer values but is still sometimes useful.
* We also have some options for our floating point values:
* float is the basic floating point value, storing 6 decimal places
* double takes double the memory and gives 15 decimal places
* long double takes even more memory and gives 19 decimal places
* Picking the right data type is important and gives the programmer a lot of control over the program at a low level.

View File

@@ -0,0 +1,220 @@
---
title: File Handling
---
## File Handling
### Introduction
If you've written the C `helloworld` program before, you've already done file IO in C! Congratulations! :tada:
```c
/* A simple hello world in C. */
#include <stdlib.h>
// Import IO functions.
#include <stdio.h>
int main() {
// This printf is where all the file IO magic happens!
// How exciting!
printf("Hello, world!\n");
return EXIT_SUCCESS;
}
```
File Handling is most important part of a programmer . In C language we use a structure pointer of a file type to declare a file
```c
FILE *fp;
```
C provides a number of build-in function to perform basic file operation
**fopen()** **-** **create a new file or open a existing file**
**fclose()** **-** **close a file**
**getc()** **-** **reads a character from a file**
**putc()** **-** **writes a character to a file**
**fscanf()** **-** **reads a set of data from a file**
**fprintf()** **-** **writes a set of data to a file**
**getw()** **-** **reads a integer from a file**
**putw()** **-** **writes a integer to a file**
**fseek()** **-** **set the position to desire point**
**ftell()** **-** **gives current position in the file**
**rewind()** **-** **set the position to the begining point**
### Opening a file
The **fopen()** function is used to create a file or open a existing file
```c
fp = fopen(const char filename,const char mode);
```
In C there are many mode for opening a file
**r** **-** **open a file in reading mode**
**w** **-** **opens or create a text file in writing mode**
**a** **-** **opens a file in append mode**
**r+** **-** **opens a file in both reading and writing mode**
**a+** **-** **opens a file in both reading and writing mode**
**w+** **-** **opens a file in both reading and writing mode**
Here's an example of reading and writing data to a file
```c
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("hello.txt", "w");
printf("Enter data");
while( (ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("hello.txt", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
fclose(fp);
}
```
Now you might be thinking, "this justs prints text to my screen. How is this file IO?"
The answer isn't obvious at first, and needs some understanding about the UNIX system.
Under a UNIX system, everything is treated as a file, meaning you can read and write from it.
This means that your printer can be abstracted as a file since all you do with a printer is write with it.
It is also useful to think of these files as streams, since as you'll see later, you can redirect them with the shell.
So how does this relate to `helloworld` and file IO?
When you call `printf`, you are really just writing to a special file called `stdout`, short for __standard output__.
`stdout` represents, well, the standard output as decided by your shell, which is usually the terminal.
This explains why it printed to your screen.
There are two other streams (i.e. files) that are available to you with effort, `stdin` and `stderr`.
`stdin` represents the __standard input__, which your shell usually attaches to the keyboard.
`stderr` represents the __standard error__ output, which your shell usually attaches to the terminal.
### Rudimentary File IO, or How I Learnt to Lay Pipes
Enough theory, let's get down to business by writing some code!
The easist way to write to a file is to redirect the output stream using the output redirect tool, `>`.
If you want to append, you can use `>>`. _N.b. these redirection operators are in_ `bash` _and similar shells._
```bash
# This will output to the screen...
./helloworld
# ...but this will write to a file!
./helloworld > hello.txt
```
The contents of `hello.txt` will, not surprisingly, be
```
Hello, world!
```
Say we have another program called `greet`, similar to `helloworld`, that greets you given your name.
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
// Initialize an array to hold the name.
char name[20];
// Read a string and save it to name.
scanf("%s", name);
// Print the greeting.
printf("Hello, %s!", name);
return EXIT_SUCCESS;
}
```
Instead of reading from the keyboard, we can redirect `stdin` to read from a file using the `<` tool.
```bash
# Write a file containing a name.
echo Kamala > name.txt
# This will read the name from the file and print out the greeting to the screen.
./greet < name.txt
# ==> Hello, Kamala!
# If you wanted to also write the greeting to a file, you could do so using ">".
```
### The Real Deal
The above methods only worked for the most basic of cases. If you wanted to do bigger and better things, you will probably want to work with files from within C instead of through the shell.
To accomplish this, you will use a function called `fopen`. This function takes two string parameters, the first being the file name and the second being the mode.
Mode is basically permissions, so `r` for read, `w` for write, `a` for append. You can also combine them, so `rw` would mean you could read and write to the file. There are more modes, but these are the most used.
After you have a `FILE` pointer, you can use basically the same IO commands you would've used, except that you have to prefix them with `f` and the first argument will be the file pointer.
For example, `printf`'s file version is `fprintf`.
Here's a program called `greetings` that reads a from a file containing a list of names and writes to another file the greetings.
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
// Create file pointers.
FILE *names = fopen("names.txt", "r");
FILE *greet = fopen("greet.txt", "w");
// Check that everything is OK.
if (!names || !greet) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
// Greetings time!
char name[20];
// Basically keep on reading untill there's nothing left.
while (fscanf(names, "%s\n", name) > 0) {
fprintf(greet, "Hello, %s!\n", name);
}
// When reached the end, print a message to the terminal to inform the user.
if (feof(names)) {
printf("Greetings are done!\n");
}
return EXIT_SUCCESS;
}
```
Suppose `names.txt` contains the following:
```
Kamala
Logan
Carol
```
Then after running `greetings` the file `greet.txt` will contain:
```
Hello, Kamala!
Hello, Logan!
Hello, Carol!
```
Super awesome, right! :smile:
### More Information:
- <a href='https://en.wikibooks.org/wiki/C_Programming/File_IO' target='_blank' rel='nofollow'>Wikibooks page on file IO</a>

View File

@@ -0,0 +1,45 @@
---
title: For Loop
---
# For Loop
The `for` loop executes a block of code until a specified condition is false. Use `while` loops when the number of iterations are variable, otherwise use `for` loops. A common use of `for` loops are array iterations.
It is also known as an 'entry-controlled loop' since the condition is checked before the next iteration. Another example of an 'entry-controlled loop' is a while loop.
## Syntax of For Loop
```c
for ( init; condition; increment ) {
statement(s);
}
```
The `for` loop consists of 3 sections, the initialization section, a specific condition and the incremental or decremental operation section. These 3 sections control the `for` loop.
The initialization statement is executed only once. Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), codes inside the body of for loop is executed and the update expression is updated. This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
## Example
```c
#include <stdio.h>
int main () {
int array[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("Item on index %d is %d\n", i, array[i]);
}
}
```
## Output:
```shell
> Item on index 0 is 1
> Item on index 1 is 2
> Item on index 2 is 3
> Item on index 3 is 4
```

View File

@@ -0,0 +1,186 @@
---
title: Format Specifiers
---
# Format Specifiers
Format specifiers defines the type of data to be printed on standard output. Whether to print formatted output or to take formatted input we need format specifiers. Format specifiers are also called as format string.Format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.
Character format specifier : %c
#include <stdio.h>
int main()
{
char ch = 'A';
printf("%c\n", ch);
return 0;
}
Output:
A
Integer format specifier : %d, %i
#include <stdio.h>
int main()
{
int x = 45, y = 90;
printf("%d\n", x);
printf("%i\n", x);
return 0;
}
Output:
45
45
Double format specifier : %f, %e or %E
#include <stdio.h>
int main()
{
float a = 12.67;
printf("%f\n", a);
printf("%e\n", a);
return 0;
}
Output:
12.670000
1.267000e+01
Unsigned Octal number for integer : %o
#include <stdio.h>
int main()
{
int a = 67;
printf("%o\n", a);
return 0;
}
Output:
103
Unsigned Hexadecimal for integer : %x, %X
#include <stdio.h>
int main()
{
int a = 15;
printf("%x\n", a);
return 0;
}
Output:
f
String printing : %s
#include <stdio.h>
int main()
{
char a[] = "nitesh";
printf("%s\n", a);
return 0;
}
Output:
nitesh
----------------------------------------
scanf(char *format, arg1, arg2, …)
decimal integer : %d
#include <stdio.h>
int main()
{
int a = 0;
scanf("%d", &a); // input is 45
printf("%d\n", a);
return 0;
}
output:
45
Integer may be octal or in hexadecimal : %i
#include <stdio.h>
int main()
{
int a = 0;
scanf("%i", &a); // input is 017 (octal of 15 )
printf("%d\n", a);
scanf("%i", &a); // input is 0xf (hexadecimal of 15 )
printf("%d\n", a);
return 0;
}
output:
15
15
Floating data type : %f, %e(double), %lf(long double)
#include <stdio.h>
int main()
{
float a = 0.0;
scanf("%f", &a); // input is 45.65
printf("%f\n", a);
return 0;
}
Output:
0.000000
String input : %s
#include <stdio.h>
int main()
{
char str[20];
scanf("%s", str); // input is nitesh
printf("%s\n", str);
return 0;
}
Output:
nitesh
Character input : %c
#include <stdio.h>
int main()
{
char ch;
scanf("%c", &ch); // input is A
printf("%c\n", ch);
return 0;
}
output:
A
The % specifiers that you can use in ANSI C are:
| Specifier | Used For |
|:-------------:|:-------------:|
| %c | a single character|
| %s | a string |
| %hi| short(signed)|
| %hu| short(unsigned)|
| %Lf| long double |
| %n | prints nothing |
| %d | a decimal integer|
| %o | an octal (base 8) integer|
| %x | a hexadecimal (base 16) integer |
| %p | an address (or pointer) |
| %f | a floating point number for floats |
| %u | int unsigned decimal |
| %e | a floating point number in scientific notation |
| %E | a floating point number in scientific notation |
| %% | The % symbol! |

View File

@@ -0,0 +1,117 @@
---
title: Functions
---
# Functions in C
Sometimes you have a chunk of code that you need to use over and over, but at different times and places in your code. You could copy and paste it over and over, but that's not a great solution- your file size ends up being bigger, your code is harder to debug, and your code is harder to read. Instead, use a function: functions are like mini-programs that exist within your code. You can pass them variables to use, and they can give back data.
## An Example
Here's a simple example of a function that divides two numbers. It's not very useful since we have `/`, but it shows the different parts of a function.
```C
#include <stdio.h>
int divides(int a, int b) {
return a / b;
}
int main(void) {
int first = 5;
int second = 10; //MUST NOT BE ZERO;
int result = divides(first, second);
printf("first divided by second is %i\n", result);
return 0;
}
```
Notice that like `main`, `divides` has a similar format. That's because `main` is also a function- it's just special because C looks for it first. `divides` also comes before `main`. This is important because `main` calls `divides`. Calling a function means that its code is being used. Code must be compiled before it gets used, and C compiles line by line from the top, so in order for a function to be called, it must be written out before it is called like in this example. If `divides` came after `main`, it would fail because the compiler doesn't know that `divides` exists yet. You may also use a function prototype before main to allow you to place `divides` after main. A function prototype is identical to the function with the same variables and return type, except they braces are omitted and replaced with a semicolon like so:
```C
int divides(int a, int b);
```
Also notice that `divides` and `main` are not sharing brackets and are not in each other's brackets. They are meant to be separate, even though one calls the other.
With that in mind, let's go over the first line in a function in our next section, titled:
## Breaking down the function declaration
```C
int divides(int a, int b)
```
The function declaration begins with a data type, which in this case is `int`. Whatever data type you want the function to return, you should place here. You can have the return be any data type, or it can be no data type by placing `void` here.
Next is the name of the function. Whenever you want to call the function, this is the name you'll use. Try to make it be something descriptive, so you can easily identify what it does.
After the name comes a pair of parenthesis. In these parenthesis go our function's parameters, which are the variables that this function will take and use when the code runs. In this case, there are two. Both of them are the `int` data type, and they will be named `a` and `b`. Ideally, there would be better names to use here, but you'll find that for simple and quick methods temporary variable names are often used.
Now let's take a look at what's inside the brackets:
```C
return a / b;
```
This is pretty straightforward, because this is such a simple function. `a` is divided by `b`, and that value is returned. You've seen `return` before in the `main` function, but now instead of ending our program, it ends the method and gives the value to whatever called it.
So to recap what this function does- it gets two integers, divides them, and gives them back to whatever called it.
###Parameters of a function
Parameters are used to pass arguements to the function.
Their are two types of parameters:
Parameter Written In Function Definition is Called “Formal Parameter”.
Parameter Written In Function Call is Called “Actual Parameter”.They are also known as arguments.They are passed to the function definition and a copy is created in the form of formal parameters.
## A more complex example
That one was a single line function. You'll see them when there's a pretty simple operation that needs to be performed over and over, or an operation that ends up being one long line. By making it a function, the code ends up being more readable and manageable.
That being said, most functions will not be a single line of code. Let's take a look at another, slightly more complex example that chooses the greater of two numbers.
```C
int choose_bigger_int(int a, int b) {
if(a > b)
return a;
if(b > a)
return b;
return a;
}
```
Just like before, the function is going to return an integer and takes two integers. Nothing new to see there.
This code starts with an if statement that checks if `a` is greater than `b`. In the event that it is, it will return `a`. If this is done, the function ends here- the rest of the code doesn't get evaluated. If this return statement isn't reached, however, the next if statement will be evaluated. If it is true, `b` will be returned and the function ends here.
With that, the conditions for a being greater than b, and b being greater than a, have been accounted for. However, if a equals b, the function still won't have returned anything. For that reason, we return a (a is equal to b, so we could return either).
## A word on 'scope'
Scope is a thing to be aware of. It refers to the areas in your code where a variable is accessible. When you pass a variable to a function, the function gets its own copy to use. This means that adjusting the variable in the function will not adjust it anywhere else. Similarly, if you haven't passed a variable to a function, it doesn't have it and can't use it.
You may have observed a similar issue with things like if statements and any of the loops. If you declare a variable within brackets, it won't be accessible outside of those brackets. This is true for functions in the same way, but there are some ways to get around it:
* Make a global variable by declaring it outside of any functions
* This makes your code messier and is generally not recommended. It should be avoided whenever possible
* Use pointers, which you'll read about next
* This can make your code harder to read and debug
* Pass into your functions like you're supposed to
* This is the best way to do it, if doing so is an option
Ideally, you'll always pass into your functions as parameters, but you may not always be able to. Picking the best solution is your job as a programmer.
## Recursion in C
When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.
```
int factorial (int n)
{
if ( n < 0)
return -1; /*Wrong value*/
if (n == 0)
return 1; /*Terminating condition*/
return (n * factorial (n -1));
}
```
# Before you go on...
## A review
* Functions are good to use because they make your code cleaner and easier to debug.
* Functions need to be declared before they get called.
* Functions need to have a data type to return- if nothing is getting returned, use `void`.
* Functions take parameters to work with- if they're taking nothing, use `void`.
* `return` ends the function and gives back a value. You can have several in one function, but as soon as you hit one the function ends there.
* When you pass a variable to a function, it has its own copy to use - changing something in a function doesn't change it outside the function.
* Variables declared inside a function are only visible inside that function, unless they are declared static.

View File

@@ -0,0 +1,31 @@
---
title: Hello World C
---
## Hello World
To write on console you can use the function `printf()` contained in the library `include <stdio.h>`
```C
#include <stdio.h>
int main(void)
{
printf("hello, world\n"); //lines starting with this are called comments..
return 0;
}
```
## Explanation
* The #include <stdio.h> is a preprocessor command. This command tells compiler to include the contents of stdio.h (standard input and output) file in the program.
* The stdio.h file contains functions such as scanf() and print() to take input and display output respectively.
* If you use printf() function without writing #include <stdio.h>, the program will not be compiled.
* The execution of a C program starts from the main() function.
* The printf() is a library function to send formatted output to the screen. In this program, the printf() displays Hello, World! text on the screen.
* The return 0; statement is the "Exit status" of the program. In simple terms, program ends with this statement
## Output:
```
>Hello World
```

View File

@@ -0,0 +1,232 @@
---
title: Logical Operators and If Statements
---
# If Statements in C
The ability to change the behavior of a piece of code which is based on certain information in the environment is known as conditional code flow.Sometimes you want your code to run according to certain conditions. In such situation we can use If statements. It is also known as decision making statement as it make the decision on basis of given expression(or on given condition).If the expression evaluates to true, then the block of code inside the 'if' statement will be executed. If the expression evaluates to false, then the first set of code after the end of the 'if' statement (after the closing curly brace) will be executed.A expression is an expression that has relational and/or logical operators operating on boolean variables. A expression evaluates to either true or false.
## Syntax of *if statement*
```
if (testExpression) {
// statements
}
```
## A Simple Example
Let's look at an example of this in action:
```C
#include <stdio.h>
#include <stdbool.h>
int main(void) {
if(true) {
printf("Statement is True!\n");
}
return 0;
}
```
```
output:
Statement is True!
```
Just like helloworld.c, stdio.h has been included. New in this program is stdbool.h, which is the standard boolean library- it contains code that gives us access to 'true' and 'false'.
Also new in the above example is that 'if' statement. If the statement within the parenthesis is true, the code within the brackets of the if statement will be run. In the case of this example, true is true, so the code will run the `printf` function.
## If-else
In the 'If-else' statement, If the statement within the parenthesis is true, the code within the brackets of the 'if' statement will be executed and if the statement within the parenthesis is false, the code within the brackets of the 'else' statement will be executed.
Of course, that example wasn't very useful, because true is always true. Here's another one that's a bit more practical:
```C
#include <stdio.h>
int main(void) {
int n = 2;
if(n == 3) { // comparing n with 3
printf("Statement is True!\n");
}
else { // if first condition is not true, then comes to this block of code.
printf("Statement is False!\n");
}
return 0;
}
```
```
output:
Statement is False!
```
There are a few important things that are different here. First, `stdbool.h` hasn't been included. That's okay, because `true` and `false` aren't being used. In C, we have statements that are treated as true and false even though the words true or false aren't involved in the operation.
Within the parenthesis of the if statement is something new, too: `n == 3`. This is a comparison between `n` and the number 3. `==` is the comparison operator, and is one of several comparison opertations in C.
## Nested if-else
The if-else statement allows a choice to be made between two possible alternatives. Sometimes a choice must be made between more than two possibilities. For example the sign function in mathematics returns -1 if the argument is less than zero, returns +1 if the argument is greater than zero and returns zero if the argument is zero. The following C++ statement implements this function:
```C
if (x < 0)
sign = -1;
else
if (x == 0)
sign = 0;
else
sign = 1;
```
This is an if-else statement in which the statement following the else is itself an if-else statement. If x is less than zero then sign is set to -1, however if it is not less than zero the statement following the else is executed. In that case if x is equal to zero then sign is set to zero and otherwise it is set to 1.
Novice programmers often use a sequence of if statements rather than use a nested if-else statement. That is they write the above in the logically equivalent form:
```C
if (x < 0)
sign = -1;
if (x == 0)
sign = 0;
if (x > 0)
sign = 1;
```
This version is not recommended since it does not make it clear that only one of the assignment statements will be executed for a given value of x. Also it is inefficient since all three conditions are always tested.
## Comparison Operators
Operator Name | Usage | Operator Result
----------------------------|:---------:|-----------------
Equal To | a == b | True if a is equal to b, false otherwise
Not Equal To | a != b | True if a is not equal to b, false otherwise
Greater Than | a > b | True if a is greater than b, false otherwise
Greater Than or Equal To | a >= b | True if a is greater than or equal to b, false otherwise
Less Than | a < b | True if a is less than b, false otherwise
Less Than or Equal To | a <= b | True if a is less than or equal to b, false otherwise
That example also has a new word: `else`. The code within the `else` block runs only if the code within the `if` doesn't run.
There's a lot we can do with all of those operators! Consider the following, where we'll use an if-else statement:
```C
#include <stdio.h>
int main(void) {
int n = 5;
if(n == 5) {
printf("n is equal to 5!\n");
}
else if (n > 5) {
printf("n is greater than 5!\n");
}
return 0;
}
```
```
output:
n is equal to 5!
```
The if-else statement has an 'else if' attached to it. This code runs if the condition within the previous if was false, but adds a condition within its own parenthesis that must be true before the code is run.
## Logical Operators
Of course, we might want something to happen if it is not true, or if it and something else are true. For that, we have logical operators: ! for not, && for and, and || for or. Let's take a look at this in action:
```C
#include <stfio.h>
int main(void) {
int n = 5;
int m = 10;
if(n > m || n == 15) {
printf("Either n is greater than m, or n is equal to 15\n");
}
else if( n == 5 && m == 10 ) {
printf("n is equal to 5 and m is equal to 10!\n");
}
else if ( !(n == 6)) {
printf("It is not true that n is equal to 6!\n");
}
else if (n > 5) {
printf("n is greater than 5!\n");
}
return 0;
}
```
```
output:
n is equal to 5 and m is equal to 10!
```
Here's the first set of parenthesis: `n > m || n == 5`. This will be true if n is greater than m, or if n is equal to 5. n is not greater than m, but n is equal to 5. Because one of these things are true, and they are joined by an or, this statement will be true and the code within will be printed.
Because the previous code was executed, it won't check the other else statements- those only get checked if the ones previous don't get checked. Just for the sake of exercise, though, consider what the rest of the code would be checking. `n == 5 && m == 10` will be true if n is equal to 5 and m is equal to 10. This is true, but if n was 6 it would no longer be true and the code within that else would not be run.
`!(n == 6)` uses parenthesis to make the operation more obvious. Just like in math, parenthesis can be used for order of operations: things within the parenthesis will be performed before things that are not within parenthesis. So in this case, `n == 6` will be evaluated, and is false. The `!`, 'not', flips this from false to true, so this operation returns true. Like before, however, it will not run only because one of the previous statements was true that this is attached to would have already run.
Finally, does `n > 5` evaluate to true? The answer is no, because n *is* 5, and so it is not greater than 5. As a result, this code will not evaluate to true. In order to make this evaluate to true, the `>=` operator should be used.
## A Detail about C Comparisons
Earlier you read that the comparisons are checking if something is true or false, but that's really only half true. Remember that C is about being light and close to the hardware- in hardware, it's easy to check if something is 0, and anything else takes more work. Because of this, what the comparisons are really doing is checking if something is false, which is assigned the value of 0, or checking if it isn't false (any other value).
As a result, this if statement is true and valid:
```C
if(12452) {
printf("This is true!\n")
}
```
By design, 0 is false, and by convention, 1 is true. In fact, here's a look at the `stdbool.h` library described earlier:
```C
#define false 0
#define true 1
```
There's actually a bit more to it, but this is the part that does all the work.
These two lines of code tell the compiler that the word 'false' should be replaced with '0', and the word 'true' should be replaced by '1'. `stdbool.h` also has some documentation and compiler instructions that will be discussed later, but those two lines are all there really is to it.
# Tips and Tricks
Consider the code below:
```C
#include <stdio.h>
int main() {
int i=3;
if(i=4) {
printf("This block is executed");
}
else {
printf("NO! I am boss");
}
}
```
What will be the the Output? "NO! I am boss"? if you are guessing this output then you are wrong.
Why did this happen? because in the if statement you used "=" instead of "==" operator.
"==" is comparator .
It will compare between two variables but "=' is assignment operator
when we said i=4, we simply assigning value 4 to the integer i, and since in "C" every NON-ZERO value is true so
if(i=4) is true statement and instructions under this will executed
# Before you go on...
## A review
* 'if' statements check if expression is true, then it run the code within the curly brackets.
* 'else' can be added to the end of an 'if', and will run only if the previous if(s) statement were false.
* 'else if' can also be added to the end of an 'if', and will run only if the previous if(s) statement were false.
* Everything in a computer is represented by numbers, so every comparison in C can be done by treating values like numbers- even true, false, and characters.
* There are a bunch of comparison operators:
* == is equal to
* != is not equal to
* \> is greater than
* < is less than
* \>= is less than or equal to
* <= is less than or equal to
* We also have some logical operators, which allow us to chain together logical operations:
* ! is called NOT operator-It reverses the state of the operand
* && is called AND operator-It returns true when both conditions are true
* || is called OR operator-It returns true when at-least one of the condition is true

View File

@@ -0,0 +1,64 @@
---
title: If
---
# If
The if statement executes different blocks of code based on conditions.
```
if (condition) {
// Do something when `condition` is true
}
else {
// Do something when `condition` is false
}
```
When `condition` is true, code inside the `if` section executes, otherwise `else` executes. Sometimes you would need to add a second condition. For readability, you should use a `else if` rather than nesting `if` statements.
```
if (condition) {
// Do something if `condition` is true
}
else if (anotherCondition) {
// Do something if `anotherCondition` is ture
}
else {
// Do something if `condition` AND `anotherCondition` is false
}
```
Note that the `else` and `else if` sections are not required, while `if` is mandatory.
## Example
```
#include <stdio.h>
int main () {
// Local variable definition
int a = 10;
// Check the boolean condition
if(a < 5) {
// If condition is true then print the following
printf("a is less than 5!\n" );
}
else {
// If condition is false then print the following
printf("a is not less than 5!\n" );
}
printf("Value of a is : %d\n", a);
return 0;
}
```
## Output
```
-> a is not less than 5!
-> Value of a is : 100
```

123
guide/english/c/index.md Normal file
View File

@@ -0,0 +1,123 @@
---
title: C
---
# Hello World! - Your first C Program
## Getting the most out of this course
Make sure that you're comfortable with all of the concepts in this part of the guide before moving on. Getting your first program running is important because it will allow you to follow along with the examples, which is another good thing to do- practice makes perfect! Concepts that might be confusing will have an annotation that links to an appendix. If you don't understand a concept, make sure that you consult the appendix for more information.
## Course Goal
The goals of this course are to teach the C language to beginners. Ideally, someone who has never touched a computer language before will be able to know C by following these guides. However, they will still be useful to more experienced programmers by including a summary at the end of each article. Although the content taught here is transferable to microcontrollers like the Arduino, it is not the focus of this guide.
## What is C?
C is a general purpose programming language invented by Dennis Ritchie between 1969 and 1973 at Bell Labs. Since then, it has been used to create things like the Linux Kernel, which allows software to interact with hardware on Linux-based operating systems. It can do this, and other low-level operations, because it was designed to be very close to machine code while still being human-readable. Because of this, it provides direct access to computer memory and hardware. This makes it very useful in hardware and robotics applications where having access to those features quickly is important.
C, like other low-level languages, requires compilation. The compilation process takes the C code that can be read by a person and turns it into code that can be read and executed by a computer. Compilation requires a compiler, which can either be used from the command line or can be used in an IDE.
If you would prefer to use the command line, consider `gcc`. It can be found by default on GNU+Linux operating systems and on Mac, and is easy to get on Windows. For beginners, however, having an IDE may be more comfortable. Consider CodeBlocks or Xcode (use Command Line Tools if you do not want the whole XCode package) if you're interested in being able to write and run code from a GUI.
Now that you have that background, let's start with our 'Hello, World' program. 'Hello, World' is a traditional way of getting started with a language: it shows that we can write code and make it run, so it's a good place to start!
## Hello world in C
```C
#include <stdio.h>
int main(void)
{
printf("hello, world\n");
return 0;
}
```
Let's break this program down step-by-step.
First is the `#include`:
```C
#include <stdio.h> // This is called preprocessor directives
```
This is an instruction to the compiler to find and include a set of header files. Header files contain additional code that we can use. In this case, the compiler has been instructed to include `<stdio.h>`, which contains all kinds of useful functions like `printf()`. We can also write it as `#include"stdio.h"`. We'll get into detail about what functions are later, but for now just remember that a function is a collection of code that we can use.
```C
int main(void)
{
}
```
This code declares the main function. The main function is special- it will always get called and is always the 'main' part of your program. If this isn't in your program, your program can't run and won't compile.
Starting the function declaration with `int` means that this function will give an `int` value when it's done running through its code- it's this function's output. `int` is the 'integer' data type, and integers are whole numbers like -3, 0, or 18. So we know that this code will run, and when it's done, it will give us back an integer. By convention, this integer is 0.
Next is `main`. `main` is the name of this function, and as you learned earlier, it's important to have a `main` function because your program won't work without it. `main` is followed by `(void)`. This tells the compiler that this function doesn't take any parameters, meaning that it has no input.
This might not make a lot of sense right now, but you'll be learning more about this when you start reading about functions in C later. For now, just remember that `main` is required for your C program, it isn't taking any input, and it's giving a number as its output.
Finally, there are the brackets: `{` and `}`. These mark the beginning and end of the function. The open curly bracket (`{`) marks the beginning, and the close curly bracket (`}`) marks the end. Everything between the two is within the function.
Now let's look at the meat of the program:
```C
printf("Hello, World!\n");
```
`printf` is a function that takes text and prints it to the screen. The parenthesis indicates what information we want the `printf` function to take and print to the screen. We show that this is a string we want printed by surrounding it in quotes "like this".
Notice the \n found within the quotes- this tells the `printf` function to print a newline. A newline is what gets printed when you hit enter on your keyboard. Without explicitly telling C to print a newline, everything will be printed on the same line.
Finally, the printf() statement is concluded with a semicolon (`;`). This shows that this line of code is over. Without it, the compiler doesn't know where one line ends and another begins, so it's important to include.
The program ends with a return statement:
```C
return 0;
```
This shows that the function is over and that it should end by giving a value of 0 to whatever made it run. When you're running code on your computer, this is good to have because it allows other programs to interact with yours in a better way.
As before, this line ends with a semicolon to indicate that the line has completed.
## Compilation and Running
You can save your hello world file as whatever you want, but it needs to end with the .c file extension. In this example, the file has been named "helloworld.c", because that is a clear name with a .c file extension.
There are many ways to compile and get C code running on your computer. Here are a few:
#### Compilation and running from the command line with GCC
If you're running Mac or GNU+Linux, you've already got GCC installed.
In order to run your C program, it needs to be compiled. In order to compile from the command line using gcc, run the following command from your terminal:
```shell
gcc -o helloworld ./helloworld.c
```
`gcc` is the Gnu C Compiler, and it will compile the C file we give it into a program that can be run by your computer.
`-o helloworld` tells GCC that you want the compiled file (the output of gcc) to be a file called "helloworld". The final part of the command tells GCC where the C file to be compiled can be found. If you aren't comfortable with navigating from the command line, this step will be hard, but that's okay- it's easy to learn and come back, or you can try from an IDE.
Once you've got it compiled, run the following command:
```shell
./helloworld
```
If everything has gone well, you should see `Hello, World!` printed to the screen.
#### Compilation and running C with CodeBlocks
<a href='http://www.codeblocks.org/downloads/26' target='_blank' rel='nofollow'>Codeblocks can be downloaded from here.</a>
Make a new program with `file` -> `new` -> `file`, select C/C++ source, select C as your language, and then copy over the helloworld.c text that you read through earlier. Compile and run the code with `Build` -> `Build and Run`.
#### Compilation and running C with Xcode
[Xcode can be downloaded from here.](https://developer.apple.com/xcode/)
#### Compilation and running C with Dev-C++
<a href='https://sourceforge.net/projects/orwelldevcpp/' target='_blank' rel='nofollow'>Dev-C++ can be downloaded from here.</a>
Make a new program with `file` -> `new` -> `Source File`, then copy over the helloworld.c text that you read through earlier and then save the file with`file` -> `save As` as hello.c , and Compile and run the code with `Execute` -> `Compile & Run`.
# Before you go on...
## A review
* C is lingua franca of programming languages.
* C was used to re-implement the Unix operating system.
* C is useful because it's small, fast, and has access to low-level operations. Because of this, it gets used a lot in robotics, operating systems, and consumer electronics, but not in things like webpages.
* A C program has a few critical parts:
* The include statement, which tells the C compiler where to find additional code that will be used in the program.
* The main function, which is where the code will first be executed and is required in order to compile.
* Stuff within that main function which will get executed, including a return statement that closes the program and gives a value to the program that called it.
* C needs to be compiled in order to run.
* C can be used to access specific hardware addresses and to perform type punning to match externally imposed interface requirements, with a low run-time demand on system resources.

View File

@@ -0,0 +1,626 @@
---
title: Loops of all kinds
---
# Loops of all kinds in C
Loops are what you use when you have code that you want to loop, meaning that after it runs, you might want it to loop around to the beginning and run again. There are a few of these in C.
They can be categorized as:
(a) Entry controlled loops- Loops in which the condition is checked before every iteration. e.g. for loop, while loop
(a) Exit controlled loop- Loops in which the execution takes place once even if the condition is false. e.g. for do-while loop
## While loops
The simplest of the bunch are while loops. While loops will run while the condition within the parenthesis is true. They should be used when you want something to happen until a certain condition takes place.
### Syntax
```
while(condition) {
statement(s);
}
```
Here's an example:
```C
#include <stdio.h>
int main(void) {
int my_number = 0;
while(my_number != 10){
++my_number;
}
printf("my_number = %i", my_number);
return 0;
}
```
While the statement within the while loop is true, the content within the brackets will be run. When the program hits the `while(my_number)`, it checks the statement within the parenthesis. If that statement is false, it won't run the while loop. Instead, it will skip over the code between the two brackets and will pick up where it left off.
If the statement is true, the code within the brackets will be run. Once the code within the brackets has run, the statement within the parenthesis will be checked again. Just like before, if the statement is true, the code will be run, if it's false, the code will be skipped.
Something that you may run into when playing with this or any other loop is the idea of an infinite loop- a loop that will run an infinite amount of times because there's nothing to stop it. Sometimes this can happen on purpose:
```C
while(1) {
printf("This will get printed forever unless the program is stopped!");
}
```
Of course, it can also happen accidentally. Here's the same code as before, but with a subtle difference that turns it into an infinite loop:
```C
#include <stdio.h>
int main(void) {
int my_number = 11;
while(my_number != 10){
++my_number;
}
printf("my_number = %i", my_number);
return 0;
}
```
When this while loop is evaluated, `my_number` will be checked to see if it isn't 10. It isn't, because it's been initialized at 11, so the code within the while loop will run and `my_number` will be 12. 12 does not equal 10, so the code within the while loop will be run and `my_number` will be 13. This will keep running forever because this condition will never become false- the only way for it to stop is for the program to be forced to stop running. This is an example of an infinite loop, because if left alone, it will run an infinite amount of times.
## Do-while loops
Do-while loops are a less commonly used version of a while loop. While loops start with an evaluation, so if that evaluation is false, the code within the brackets will not be run. With a do-while loop, however, the code within the brackets gets run once, then the evaluation is performed to see if it should be run again.
### Syntax
```
do {
statement(s);
} while( condition );
```
Here's a look at that:
```C
#include <stdio.h>
int main(void){
int a = 0;
do {
a++
} while(a == -123);
printf("%i\n", a);
return 0;
}
```
If this were a while loop, the code within the brackets would never get run because this condition isn't true when the evaluation is performed. However, because this is a do-while loop, the code will be performed once, and then the evaluation is done to see if it should be done again. Do-while loops are useful for when you know you want something to be done once, but you may need it to be run additional times after that.
## For loops
For loops are for when we want something to run a set number of times.
### Syntax
```
for(initialisation; condition; changer)
{
statement(s);
}
```
Here's an example of that:
```C
#include <stdio.h>
int main(void) {
int a = 4;
int b = 2;
int result = 0;
for(int count = 0; count != b; count++) {
result = result + a;
}
printf("a times b is %i\n", result);
return 0;
}
```
Multiplication is just repeated addition, so this is doing addition on `a`, `b` times. Let's a take a look at the `for` bit in particular:
```C
for(int count = 0; count != b; count++)
```
Unlike the for loop, there are three things in our parenthesis that are separated by semicolons. The first section is for initialization, and is referred to as 'initialization': it allows you to make a new variable and set it a value, or set an existing variable to a different value, or you can not set anything and just put a semicolon down.
The next section is a boolean condition that will be checked for true or false, just like our while loop. It's referred to as a 'condition', because it's the condition that will get checked before starting a loop.
The final section is referred to as the 'increment/decrement'. Its job is to perform some operation every loop - usually adding or subtracting from the initial variable - after the code within the brackets has been run through. In this case, it's just adding one to the count. This is the most common way for the increment to be used, because it lets you keep count of how many times you've run through a for loop.
### Syntax Comparison
```
main()
{
int i = 1;
while(i<=5)
{
printf(“While”);
i++;
}
getch();
}
main()
{
int i = 1;
do
{
printf(“do-while”);
i++;
} while(i<=5);
getch();
}
main()
{
int i
for(i=1;i<=5;i++)
{
printf(“for”);
}
getch();
}
```
# Loop Control Statements
Loop control statements change execution form its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements:
#### 1. Break statement
Terminates the <b>loop</b> or <b>switch</b> statement and transfers execution to the statement immediately following the loop or switch.
#### 2. Continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
#### 3. Goto statement
Transfers control to the labeled statement.
# Some Fun and Useful Quirks
## Infinite looping with for loops
Take a moment to consider what this code will do:
```C
for(;;){
printf("hello, world! \n");
}
while("Free Code Camp"){
printf("hello, world! \n");
}
```
There's nothing in the initialization section, so nothing has been initialized. That's fine, and that is done sometimes because you don't always want or need to initialize anything.
Next is the condition, which is blank. That's a little odd. This means that no condition will be tested, so it's never going to be false, so it will run through the loop, perform the afterthought (which is to do nothing), and then check the condition again, which will make it run again. As you've probably realized, this is an infinite loop. As it turns out, this is actually useful. When creating performing an infinite loop, the method of doing `while(1)` is perfectly legitimate, but performs a comparison every time. `for(;;)`, on the other hand, does not. For that reason, `for(;;)` has a legitimate use in that it is a hair more efficient than other methods of infinite looping. Thankfully, many compilers will take care of this for you.
The loop in second code while("Free Code Camp") will also execute infinitely.The reason is because C considers any non-zero value as true and hence will execute the loop infinitely.
## Not using brackets
Throughout this page, you've read that the code 'within the brackets' is what gets run, and that's mostly true. However, what if there are no brackets?
```C
while(true)
printf("hello, world! \n");
```
In cases like this, C will treat the next line as the only content that needs to be looped. C ignores whitespace, so that indent is just there for clarity. Only that one line will be treated as though it is in the loop, and this is a property that if statements, for loops, and while loops all share. Because the whitespace is ignored, the placement doesn't matter: it could be on the same line, the next line, or 300 lines and two spaces down as long as there's no other lines of code in between. This feature can make your code look a bit cleaner when you only have one line of code to run in a statement.
## Semicolons instead of brackets
If there are no brackets, the compiler will look only at the next line and have that be the content of the loop. Semicolons tell the compiler that a line is over. With these things combined, we can have C wait until something becomes true. Let's say we have a method called `is_button_pressed` that returns false if a button is not pressed, and true if a button is pressed:
```C
while(!is_button_pressed());
```
Nothing happens in this loop, because the only line it will look at is a semicolon. As a result, the `is_button_pressed` method will be called, and its return value will be evaluated. If the button is not pressed and the return value is false, the `!` will flip it to true so the function is run again and evaluated again. If the return value is true, the `!` will flip it to false and the while loop will be exited.
This has the effect of putting a pause in your code. In this case, the code reached the while loop, and didn't go any further. Instead, it kept checking for the status of the button to change. This would be useful for when you want nothing to happen until a certain condition has been met.
# Before you go on...
## A review
* Loops allow your code to be run more than once, when certain conditions are met.
* There are a couple of loops available to us in C:
* While loops, which allow us to run code while a condition is true
* Do-while loops, which run code and then continue running it if a condition is true
* For loops, which run code while a condition is true and allow us to perform an operation every loop.
## Using loops for designing patterns.
#### Example 1: Program to print half pyramid using *
```
*
* *
* * *
* * * *
* * * * *
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
```
#### Example 2: Program to print half pyramid a using numbers
```
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}
```
#### Example 3: Program to print half pyramid using alphabets
```
A
B B
C C C
D D D D
E E E E E
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j;
char input, alphabet = 'A';
printf("Enter the uppercase character you want to print in last row: ");
scanf("%c",&input);
for(i=1; i <= (input-'A'+1); ++i)
{
for(j=1;j<=i;++j)
{
printf("%c", alphabet);
}
++alphabet;
printf("\n");
}
return 0;
}
```
Programs to print inverted half pyramid using * and numbers
#### Example 4: Inverted half pyramid using *
```
* * * * *
* * * *
* * *
* *
*
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
```
#### Example 5: Inverted half pyramid using numbers
```
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}
```
#### Example 6: Program to print full pyramid using *
```
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, space, rows, k=0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i, k=0)
{
for(space=1; space<=rows-i; ++space)
{
printf(" ");
}
while(k != 2*i-1)
{
printf("* ");
++k;
}
printf("\n");
}
return 0;
}
```
#### Example 7: Program to print pyramid using numbers
```
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int i, space, rows, k=0, count = 0, count1 = 0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(space=1; space <= rows-i; ++space)
{
printf(" ");
++count;
}
while(k != 2*i-1)
{
if (count <= rows-1)
{
printf("%d ", i+k);
++count;
}
else
{
++count1;
printf("%d ", (i+k-2*count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}
```
#### Example 8: Inverted full pyramid using *
```
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
```
**Source Code**
```c
#include<stdio.h>
int main()
{
int rows, i, j, space;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(space=0; space < rows-i; ++space)
printf(" ");
for(j=i; j <= 2*i-1; ++j)
printf("* ");
for(j=0; j < i-1; ++j)
printf("* ");
printf("\n");
}
return 0;
}
```
#### Example 9: Print Pascal's triangle
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int rows, coef = 1, space, i, j;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=0; i<rows; i++)
{
for(space=1; space <= rows-i; space++)
printf(" ");
for(j=0; j <= i; j++)
{
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
```
#### Example 10: Print Floyd's Triangle.
```
1
2 3
4 5 6
7 8 9 10
```
**Source Code**
```c
#include <stdio.h>
int main()
{
int rows, i, j, number= 1;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i <= rows; i++)
{
for(j=1; j <= i; ++j)
{
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}
```

View File

@@ -0,0 +1,58 @@
---
title: Macros in C
---
## Macros in C
A macro is a piece of code with a given name. When the name is used, it is replaced by the content of the macro.
#### Defining macros
The `#define` keyword is used to define new macros. It's followed by a name and a content. By convention, macro names are written in uppercase.
```C
#define PI 3.14
```
If you use the macro this way:
```C
printf("Value of PI: %d", PI);
```
Is the same as write this:
```C
printf("Value of PI: %d", 3.14);
```
#### Types of macros
There are two type of macros. The `Object-like` macros, showed above, and the `Function-like` macros.
#### Function-like Macros
Function-like uses the same `#define` keyword. The difference is that you use a pair o parentheses after the function name.
```C
#define hello_world() printf("Hello World!")
```
So calling:
```C
hello_world()
```
You get:
```C
printf("Hello World!");
```
You can set parameters too:
```C
#define hello(X) printf("Hello " X "!")
```
Now calling:
```C
hello("World");
```
You get the equivallent of:
```C
printf("Hello World!");
```
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
[GCC Online Documentation: Macros](https://gcc.gnu.org/onlinedocs/cpp/Macros.html)
[GCC Online Documentation: Object-like macros](https://gcc.gnu.org/onlinedocs/cpp/Object-like-Macros.html#Object-like-Macros)
[GCC Online Documentation: Function-like macros](https://gcc.gnu.org/onlinedocs/cpp/Function-like-Macros.html#Function-like-Macros)

View File

@@ -0,0 +1,32 @@
---
title: malloc
---
# malloc in C
malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory where something is stored.
malloc() is part of stdlib.h and to be able to use it you need to use `#include <stdlib.h>`.
## Using Malloc
malloc() allocates memory of a requested size and returns a pointer to the beginning of the allocated block. To hold this returned pointer, we must create a variable. The pointer should be of same type used in the malloc statement.
Here we'll make a pointer to a soon-to-be array of ints
```C
int* arrayPtr;
```
Unlike other languages, C does not know the data type it is allocating memory for; it needs to be told. Luckily, C has a function called `sizeof()` that we can use.
```C
arrayPtr = (int *)malloc(10 * sizeof(int));
```
This statement used malloc to set aside memory for an array of 10 integers. As sizes can change between computers, it's important to use the sizeof() function to calculate the size on the current computer.
Any memory allocated during the program's execution will need to be freed before the program closes. To `free` memory, we can use the free() function
```C
free( arrayPtr );
```
This statement will deallocate the memory previously allocated. C does not come with a `garbage collector` like some other languages, such as Java. As a result, memory not properly freed will continue to be allocated after the program is closed.
# Before you go on...
## A Review
* Malloc is used for dynamic memory allocation and is useful when you don't know the amount of memory needed during compile time.
* Allocating memory allows objects to exist beyond the scope of the current block.
* C passes by value instead of reference. Using malloc to assign memory, and then pass the pointer to another function, is more efficient than having the function recreate the structure.

View File

@@ -0,0 +1,158 @@
---
title: Basic Math
---
# Math in C
C provides a lot of options for doing math. We'll start with some of the more common ones first.
## The basic stuff
These following examples aren't complete code, they're just examples of what a piece of code looks like. Remember that in C, we'll need to have everything declared before we're using it- `result`, `a`, and `b` will need to have already been initialized and set to a value. Whether they are `int`, `double`, or whatever is important to prevent errors and loss of information- we'll get to that later.
#### Addition: `+`
Addition is performed with a `+`, like so:
```C
result = a + b;
```
In the above example, the variable `result` will be equal to a + b.
#### Subtraction: `-`
Addition is performed with a `-`, like so:
```C
result = a - b;
```
In the above example, the variable `result` will be equal to a - b.
#### Multiplication: `*`
Multiplication is performed with a `*`, like so:
```C
result = a * b;
```
In the above example, the variable `result` will be equal to a multiplied by b.
#### Division: `/`
Division is performed with a `/`, like so:
```C
result = a / b;
```
In the above example, the variable `result` will be equal to a divided by b. This is not always a fraction of a over b, however. When dealing with integers, things get a little different- more on that later.
When dividing always check that the divisor (in this example variable b) is not equal to 0 , dividing with 0 will cause your program to crash.
# The not-so-basic stuff
## Modulo: '%'
Okay, now things start getting a little weird.
Modulo allows you to find the remainder in division. Remember that with integers, we can't have a decimal. Division is about finding how many times one number will fit into another, modulo is about finding what's left over. Take 27 divided by 4: 4 fits into 27 6 times. 6 times 4 is 24, which means there is 3 left over. As a result, 27%4 is 3. 10 divided by 5 is 2, 2 times 5 is 10, so there is 0 left over. As a result, 10%5 is 0.
The modulo operator is more important than you may think, especially in C where the difference between floating point and integer numbers is enforced. It's worth being comfortable with. Here's an example:
```C
result = a % b;
```
In the above example, `result` will be equal to a modulo b.
## Integers and math
Integers can't have decimals. As a result, when you perform division with integers, any sort of decimal will be truncated. For example, 17 divided by 10 is 1.7. However, if we're only dealing with integers, that result will be 1, not 1.7. 10 fits into 17 1 time, so the answer is 1.
When dealing with floating point numbers, this isn't an issue. Floating point numbers can take decimal places, so we don't have to worry about things getting truncated.
### Why does C do this?
C, as discussed earlier, is a low-level language. There are big differences between floating point and integer numbers in the hardware of a computer, and they require that certain data types have certain properties (like not accepting decimals, for example). C makes no assumptions as to what you want, and forces you to think about it yourself.
### Why don't we just use floating point numbers all the time?
This also comes down to C being a low-level language. C is much, much faster and much, much lighter than many other languages, and one of the reasons it is this way because of the programmer being able to make intelligent decisions about data types. Remember that floating point numbers take up a lot more memory than integers. As a result, it's important to use the appropriate data type, and deal with integer to floating point conversions whenever needed.
### How do we get around this?
Casting (described later) is one solution. The other is using floating point numbers. If one or both of the numbers being operated on are a floating point number, the result will be a floating point number. This becomes more complex when we start dealing with order of operations, but for now, be aware that this works:
```C
double result = 23.0 / 2;
```
# A full example
```C
#include <stdio.h>
// This is a comment. It gets ignored by the compiler, so we can write notes after the double slashes.
int main(void) {
int a = 3;
int b = 5;
int result = 0;
// Doing things with variables:
result = a + b;
printf("a plus b = %i \n", result);
// You can also do the operation inside the printf.
// Here's an example of that with subtraction:
printf("a minus b = %i \n", a-b);
// You don't need to do this with variables at all.
// Here's an example of that with multiplication:
printf("10 times 5 = %i \n", 10*5);
// Here's a look at division.
// Notice that the decimals are truncated because we're dealing with integers.
printf("12 divided by 5 = %i \n", 12/5);
// Now let's force floating point numbers by including a decimal.
// Notice that even though these are integers, the decimal forces them to be
// treated as floating point numbers, so they aren't truncated.
// Note that I'm printing a double with %d, not an int with %i.
printf("12.0 divided by 5 = %d \n", 12.0/5);
return 0;
}
```
Give that a run to see what happens, and be sure to play with the operators and values to see what and how things change.
# Math library
C provides a math library (`math.h`) that provides multiple useful math functions. As an example, the power of a number can be calculated as:
```#include<math.h>
int result = pow(2,3) // will result in 2*2*2 or 8
```
Some other (`math.h`) library functions that may prove useful are:
```#include <math.h>
double angle = cos(90.00); // Givs us 0.00
int result = sqrt(16); // Gives us 4
double result = log(10.00) // Gives us 2.30 (note this is ln(10), not log base 10)
```
// C code to illustrate
// the use of ceil function.
#include <stdio.h>
#include <math.h>
int main ()
{
float val1, val2, val3, val4;
val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;
printf ("value1 = %.1lf\n", ceil(val1));
printf ("value2 = %.1lf\n", ceil(val2));
printf ("value3 = %.1lf\n", ceil(val3));
printf ("value4 = %.1lf\n", ceil(val4));
return(0);
}
# Before you go on...
## A review
* There are several basic operators:
* `+` for addition
* `-` for subtraction
* `*` for multiplication
* `/` for division
* `%` for modulo
* There are also a bunch more operators, but we'll get into detail with them later.
* Integer math is a thing that C is pretty strict about.
* C is very strict about data types
* If only integers are involved, an integer will be returned
* If a floating point number is involved in an operation, that part of the operation becomes floating point
* C provides a `math.h` library with multiple functions like `pow` for calculating the power of a number.

View File

@@ -0,0 +1,171 @@
---
title: More math
---
# More math in C
Okay, so you've seen the basics. There's a lot more out there in C, though, so here's a look at that.
## Order of Operations
Take a look at the following equation:
> 1 + (3-2) * 5
If we were to simply read and compute from left to right, we would take 1, add 3, subtract 2, and multiply by 5, getting 10. However, this neglects order of operations. We should do (3-2) first, getting 1, then multiply by 5, then add 1. This gives an answer of 6.
Just like in regular math, C has an order of operations. Operations have a precedence, and if one operation has a higher precedence than another, the higher precedence will be computed first. Using parenthesis can increase that precedence, just like in normal math.
## Unary Operations
Unary operations are operations where there is only one variable. There are a few in C.
### Post-fix and Pre-fix Operators
There are a lot of situations where you want to take a number and either go up or down by 1. For those situations, we have post-fix and pre-fix operators:
```C
1: a++;
2: ++a;
3: a--;
4: --a;
```
Both the examples at 1 and 2 will increase the value of a by one. Both of the examples at 3 and 4 will decrease the value of a by one. However, 1 does not do quite the same thing as 2, and 3 does not do quite the same thing as 4. Pre-fix operators are called this because the operation is a prefix (2 and 4 are our prefix operators). This acts slightly differently from our post-fix operators at 1 and 3. Pre-fix operators perform the operation, then return the value. Post-fix operators return the value, then perform the incrementation.
### Unary plus and minus
In the normal math you're used to, you use a '-' in front of a number or variable, and that makes the number or variable negative. If the number or variable is already negative, it becomes positive.
C does the same thing: put a `-` in front of a number or variable to have that effect, like so:
```C
int number = -3;
number = -number;
```
So `number` starts as negative 3, but then becomes positive because a negative negative is positive.
## Bitwise operations
Because C is low level as mentioned before, you have access to the individual binary bits (if you choose to take advantage of this). There are some binary operations built in to let us do this. For these examples, we'll use `a` and `b` as our variables. They can be any sort of variable because all variables will be represented in bits, so the exact data type doesn't matter for these.
### AND
`c = a & b;` will perform a bitwise AND. This means that if the first bit of `a` and the first bit of `b` are both 1, the first bit of c will be 1, and 0 otherwise. If the second bit of `a` and `b` are both 1, the second bit of c will be 1, and 0 otherwise. This goes on until all bits have been and'd.
### OR
`c = a | b;` will perform a bitwise OR. The first bit of `c` is 1 if the first bit in either `a` or `b` is 1, the second bit is 1 if the second bit in either `a` or `b` is 1, and so on.
### NOT
`b = ~a;` will set `b` to the one's complement of `a`, meaning that any 1 becomes a 0 and any 0 becomes a 1.
### XOR
`c = a ^ b;` will perform a bitwise XOR. This is an exclusive or, meaning that the first bit of `c` is 1 if either `a` or `b` is 1, but not both. The second bit is 1 if either is 1 but not both, and so on.
### Shift
A bitwise shift will take the bits and move them to some number of places to the left or right. For example, say we have a set of bits: `101110`. C performs an arithmetic shift when bit shifting. Let's use a table to make that more clear:
| Bit | | 1 | 2 | 3 | 4 | 5 | 6 |
|-------|---|---|---|---|---|---|---|
|Before | | 1 | 0 | 1 | 1 | 1 | 0 |
|During | 1 | 0 | 1 | 1 | 1 | 0 | |
|After | | 0 | 1 | 1 | 1 | 0 | 0 |
This is an arithmetic bitwise shift going one to the left. Notice that in the shift left, the leftmost 1 that started in position 1 ended up outside of the space it could fit, so it was removed. In the shift, an opening appeared on the left, so it was filled with a 0.
Now let's take a look at an arithmetic bitshift right by one:
| Bit | 1 | 2 | 3 | 4 | 5 | 6 | |
|-------|---|---|---|---|---|---|---|
|Before | 1 | 0 | 1 | 1 | 1 | 0 | |
|During | | 1 | 0 | 1 | 1 | 1 | 0 |
|After | 1 | 1 | 0 | 1 | 1 | 1 | |
Notice that here a slot opened up in position 1, but instead of being filled by 0, it was filled by the most significant bit. In this case, this is a 1. If the bit that started in position 1 was 0, the gaps would have been filled with 0's.
This is because numbers on your computer are represented using Two's Complement, so shifting in this way doesn't make a negative number positive. Two's Complement is worth reading more on if you are interested in how computers use binary to do math and represent numbers.
To perform a shift left, use the `<<` operator, like so:
```C
c = a << b;
```
This will shift `a` to the left by `b` bits, and set that result equal to `c`.
This example will shift `a` to the right by `b` bits, and set that result equal to `c`.
```C
c = a >> c;
```
## Compound Assignment Operators
Sometimes you want to increase a variable by a certain value. You could do this:
```C
a = a + b;
```
However, this is what the compound assignment operators are for. Instead, you can write this, which does the exact same thing:
```C
a += b;
```
This exists for a bunch of other operators, too. Here's a handy table for you:
The Short Way | The Long Way
:--------------:|:------------:
`a += b` | `a = a + b`
`a -= b` | `a = a - b`
`a *= b` | `a = a * b`
`a /= b` | `a = a / b`
`a %= b` | `a = a % b`
`a &= b` | `a = a & b`
`a ^= b` | `a = a ^ b`
`a <<= b` | `a = a << b`
`a >>= b` | `a = a >> b`
There's also `|=`, which isn't on the table because the `|` character breaks the table. It does act like all of these other operations, though.
## Casting
Sometimes you don't want a number to be a number, or you want an integer to be a float, or something like that. That's what casting is for.
As you recall from the discussion of integer division, the following example will give an integer value without any decimal, because both of the numbers going in are integers:
```C
#include <stdio.h>
int main(void) {
int a = 12;
int b = 5;
printf("a divided by b is %i", a/b);
}
```
However, using casting, we can turn them into floats using casting. This allows them to be divided as floats, and the equation will return a float value:
```C
#include <stdio.h>
int main(void) {
int a = 12;
int b = 5;
printf("a divided by b is %f", (float) a / b);
}
```
Now it's a floating point 12 divided by 5, so this returns a floating point number that doesn't truncate after the decimal place.
To turn a number into an `int`, use `(int)`, to turn it into a `double`, use `(double)`, and so on.
## Math.h
So that's all the built-in stuff, but just like how you can `#include` stdio and stdbool, you can include a library called `math.h`. This library has all kinds of helpful functions for all kinds of math. It's worth giving a read to <a href='https://en.wikipedia.org/wiki/C_mathematical_functions#Overview_of_functions' target='_blank' rel='nofollow'>the Wikipedia page on it</a> if you want the full list of functions. Here's an example on how to use `abs`, which is the first in their list:
```C
a = abs(-1);
```
`abs` computes the absolute value of the value passed to it. In this case, it's recieved -1, so it will turn that into 1, and `a` will be equal to 1. There are plenty more to give much more functionality, and this is how you'll be able to do exponents, trigonometry, and much more.
# Before you go on...
## A review
* There's a bunch more math operators in C
* Order of operations exists in C
* Parenthesis exist and work just like regular math to change order of operations
* There are a few Unary Operations, which are operations where there is only one variable:
* The post-fix and pre-fix operators are used to add and subtract 1
* Adding one: `++a;` or `a++;`
* Subtracting one: `--a` or 'a--'
* `-` can be placed in front of a variable or number and acts just like a negative in math
* There are some bitwise operations, too
* AND is done with &
* OR is done with |
* NOT is done with ~
* XOR is done with ^ (XOR doesn't work with floating type number in C)
* Compound assignment operations exist for all of the non-unary operations
* a += b is the same as a = a + b, and so on
* Casting allows you to swap between data types
* math.h has more math stuff to play with

View File

@@ -0,0 +1,219 @@
---
title: Operators
---
# Operators in C
## 1. Arithmetic Operators
- `+` Adds to operands (values)
```C
int a = 6;
int c = a + 1; // c = 7
```
- `-`Subtracts the second operand from the first
```C
int a = 8;
int b = 9;
int c = a - b; // c = -1
```
- `*` Multiplies two operands
```C
int a = 8;
int b = 9;
int c = a * b; // c = 72
```
- `/` Divides the first operand by the second
```C
int a = 8;
int b = 4;
int c = a / b; // c = 2
```
- `%` Gives the remainder after an integer division
```C
int a = 8;
int b = 9;
int c = b % a; // c = 1 because b = 1*a + 1 = 8 + 1
```
- `++` Increases int value by one
```C
int a = 8;
a++; // a = 9
int b = a++; // postfix operator; a = 10, b = 9
int c = ++a; // prefix operator; a = 11, c = 11
```
- `--` Decreases int value by one
```C
int a = 8;
a--; // a = 7
int b = a--; // postfix operator; a = 6, b = 7
int c = --a; // prefix operator; a = 5, c = 5
```
// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
## 2. Relational Operators
- `==` Equal - true when the two operands are equal
```C
int a = 5, b = 5;
bool c = (a == b); // c = true
```
- `!=` Not equal - true when the two operands are NOT equal
```C
int a = 5, b = 6;
bool c = (a != b); // c = true
```
- `>` Greater than - True when first operand is bigger than the second.
```C
int a = 8, b = 5;
bool c = (a > b); // c = true
```
- `<` Less than - True when the first operand is smaller then the second.
```C
int a = 5, b = 8;
bool c = (a < b); // c = true
```
- `>=` Greater than or equal - True when the first operand is bigger, or equal to the second.
```C
int a = 8, b = 5;
bool c = (a >= b); // c = true
bool d = (a >= 8); // d = true
```
- `<=` Less than or equal - True when the first operand is smaller or equal to the second.
```C
int a = 5, b = 8;
bool c = (a <= b); // c = true
```
## 3. Logical Operators
- `&&` AND operator - True when **both** of the operands are true.
```C
bool c = (5 < 6) && (8!=7); // both operands true, therefore c = true
```
- `||` OR operator - True when either the first or the second operands are true (or both)
```C
bool c = (5 < 6) || (8 == 7) // first operand is true, therefore c = true
```
- `!` NOT operator - True when the operand is false.
```C
bool c = !(8 == 7) // translate: NOT (false), therefore c = true
```
## 4. Bitwise Operators
- `&` AND operator - If at a place there is a bit in both operands, then it is copied to the result
```C
A = 11001
B = 01000
RESULT = 01000
```
- `|` OR operator - If at a place there is a bit in either operands, then it is copied to the result
```C
A = 11001
B = 01000
RESULT = 11001
```
- `^` XOR (exclusive OR) operator - If at a place there is a bit in one of the operands (not both), then it is copied to the result
```C
A = 11001
B = 01000
RESULT = 10001
```
- `~` Negation operator - Reverses the bits. 1 -> 0, 0 -> 1
```C
C = 01000
RESULT = 10111
```
- `<<` Left shift operator - The left operand is moved left by as many bits, as the right operand
```C
A = 11001
A << 2
RESULT = 00100
```
- `>>` Right shift operator - The left operand is moved right by as many bits, as the right operand
```C
A = 11001
A >> 2
RESULT = 00110
```
## 5. Assignment Operators
- `=`
```C
int a = 7; // 'a' is going to be equal to 7
```
- `+=`
```C
int a = 7;
a += 5; // equivalent to a = a + 5 = 7 + 5 = 12
```
- `-=`
```C
int a = 7;
a -= 2; // equivalent to a = a - 2 = 7 - 2 = 5
```
- `*=`
```C
int a = 7;
a *= 3; // equivalent to a = a * 3 = 7 * 3 = 21
```
- `/=`
```C
int a = 21;
a /= 3; // equivalent to a = a / 3 = 21 / 3 = 7
```
- `%=`
```C
int a = 21;
a %= 5; // equivalent to a = a % 5 = 21 % 5 = 1
```
Misc Operators ↦ sizeof & ternary
Besides the operators discussed above, there are a few other important operators including sizeof and ? : supported by the C Language.
Operator Description Example
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
* Pointer to a variable. *a;
? : Conditional Expression. If Condition is true ? then value X : otherwise value Y
## 6. Operator precedence in C
Operators with the highest precedence appear at the top of the list. Within an expression, operators
with higher precedence will be evaluated first.
- Postfix `() [] -> . ++ --`
- Unary `+ - ! ~ ++ -- (type)* & sizeof`
- Multiplicative `* / %`
- Additive `+ -`
- Shift `<< >>`
- Relational `< <= > >=`
- Equality `== !=`
- Bitwise AND `&`
- Bitwise XOR `^`
- Bitwise OR `|`
- Logical AND `&&`
- Logical OR `||`
- Conditional `?:`
- Assignment `= += -= *= /= %= >>= <<= &= ^= |=`
- Comma `,`

View File

@@ -0,0 +1,43 @@
---
title: Passing pointers to funtions
---
# Passing pointers to funtions
C allows passing a pointer to a function. To achieve this, simply declare the parameters as pointer type.
This way of passing references to functions is useful when you want to modify variables that are out of the scope of that function.
```C
// incorrect implementation of swap
#include <stdio.h>
void swap(int a, int b){
int c;
c = a;
a = b;
b = c;
}
int main(){
int var1 = 10;
int var2 = 20;
swap(var1, var2);
printf("Value of var1: %d \n", var1); // prints 10
printf("Value of var2: %d \n", var2); // prints 20
}
```
In this code example the swap function does not work as intended since it swaps two variables that exist only inside the scope of that function. To fix this we make a modification as shown below.
```C
// correct implementation of swap
#include <stdio.h>
void swap(int* a, int* b){
int c = *a;
*a = *b;
*b = c;
}
int main(){
int var1 = 10;
int var2 = 20;
swap(&var1, &var2);
printf("Value of var1: %d \n", var1); // prints 20
printf("Value of var2: %d \n", var2); // prints 10
}
```
In the second code example you were able to change the values of the variables only because you were constantly de-referencing a pointer within the function instead of trying to change the values directly

View File

@@ -0,0 +1,285 @@
---
title: Pointers
---
# Pointers in C
By now you should be aware that C is a low-level language, and nothing shows that better than pointers. Pointers are variables that get you the variable value by "pointing" to a memory location rather than storing the value of the variable itself. This allows for some handy tricks, and is also what gives us access to arrays and file handling, among other things.
#
```
type *var-name;
```
## Making and Using a Pointer
```c
#include <stdio.h>
int main(void){
double my_double_variable = 10.1;
double *my_pointer;
my_pointer = &my_double_variable;
printf("value of my_double_variable: %f\n", my_double_variable);
++my_double_variable;
printf("value of my_pointer: %f\n", *my_pointer);
return 0;
}
```
Output:
```
value of my_double_variable: 10.100000
value of my_pointer: 11.100000
```
In this code, there are two declarations. The first is a typical variable initialization which creates a `double` and sets it equal to 10.1. New in our declarations is the usage of `*`. The asterisk (`*`) is usually used for multiplication, but when we use it by placing it in front of a variable it tells C that this is a pointer variable.
The next line tells the compiler where that somewhere else actually is. By using `&` in this way, it becomes the 'dereferencing operator', and returns the memory location of the variable it's looking at.
With that in mind, let's take another look at this chunk of code:
```c
double *my_pointer;
// my_pointer now stored the address of my_double_variable
my_pointer = &my_double_variable;
```
`my_pointer` has been declared, and it's been declared as a pointer. The C compiler now knows that `my_pointer` is going to point to a memory location. The next line assigns `my_pointer` a memory location value using the `&`.
Now let's take a look what referring to a memory location means for your code:
```c
printf("value of my_double_variable: %f\n", my_double_variable);
// Same as my_double_variable = my_double_variable + 1
// In human language, adding one to my_double_variable
++my_double_variable;
printf("value of my_pointer: %f\n", *my_pointer);
```
Notice that in order to get the value of the data at `*my_pointer`, you'll need to tell C that you want to get the value the variable is pointing at. Try running this code without that asterisk, and you'll be able to print the memory location, because that's what the `my_variable` variable is actually holding.
You can declare multiple pointer in a single statement as with standard variables, like so:
```c
int *x, *y;
```
Notice that the `*` is required before each variable. This is because being a pointer is considered as part of the variable and not part of the datatype.
## Practical Uses of Pointers
### Arrays
The most common application of a pointer is in an array. Arrays, which you'll read about later, allow for a group of variables. You don't actually have to deal with `*` and `&` to use arrays, but that's what they're doing behind the scenes. A commonly used array is for strings. Since strings are not defined in C, they are simply created as a character array, commonly denoted by `char * stringName;`
### Functions
Sometimes you want to adjust the value of a variable inside of a function, but if you simply pass in your variable by-value, the function will work with a copy of your variable instead of the variable itself. If, instead, you pass in the pointer pointing to the memory location of the variable, you can access and modify it from outside of its normal scope. This is because you are touching the original memory location itself, allowing you to adjust something in a function and having it make changes elsewhere. In contrast to "call by value", this is called "call by reference".
The following program swaps the values of two variables inside of the dedicated `swap` function. To achieve that, the variables are passed in by reference.
```c
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed to the swap function
swap( &num1, &num2);
printf("Number1 = %d\n", num1);
printf("Number2 = %d", num2);
return 0;
}
void swap(int * n1, int * n2)
{
// pointer n1 and n2 points to the address of num1 and num2 respectively
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
```
Output
```
Number1 = 10
Number2 = 5
```
The addresses, or memory locations, of `num1` and `num2` are passed to the function `swap` and are represented by the pointers `*n1` and `*n2` inside of the function. So, now the pointers `n1` and `n2` point to the addresses of `num1` and `num2` respectively.
So, now the pointer n1 and n2 points to the address of num1 and num2 respectively.
When, the value of pointers are changed, the value in the pointed memory location also changes correspondingly.
Hence, changes made to *n1 and *n2 are reflected in num1 and num2 in the main function.
### POINTERS AS PARAMETERS TO FUNCTION
when we pass any parameter to function we are making a copy of the parameter. let see with the example
```C
#include <stdio.h>
void func(int);
int main(void) {
int a = 11;
func(a);
printf("%d",a);// print 11
return 0;
}
void func(int a){
a=5
printf("%d",a);//print 5
}
```
In the example above we are changinging the value of integer a in function func, but we still geting 11 in the main function. This happens because in the function copy of integer a has passed as parameter, so in this function we have not access to the 'a' which is in main function.
So how could you change the value of integer defined in main , by using another function? Here POINTERS comes in to role.
when we supply pointer as a parameter , we have access to address of that parameter and we could to any thig with this parameter and result will be shown everywhere.
Below is an example which does exactly the same thing we want...
By dereferencing `n1` and `n2`, we now can modify the memory to which `n1` and `n2` point. This allows us to change the value of the two variables `num1` and `num2` declared in the `main` function outside of their normal scope. After the function is done, the two variables now have swapped their values, as can be seen in the output.
### Tricks with Memory Locations
Whenever it can be avoided, it's a good idea to keep your code easy to read and understand. In the best case scenario, your code will tell a story- it will have easy to read variable names and make sense if you read it out loud, and you'll use the occasional comment to clarify what a line of code does.
Because of that, you should be careful when using pointers. It's easy to make something confusing for you to debug or for someone else to read. However, it is possible to do some pretty neat things with them.
Take a look at this code, which turns something from uppercase to lowercase:
```c
#include <stdio.h>
#include <ctype.h>
char *lowerCase (char *string) {
char *p = string;
while (*p) {
if (isupper(*p)) *p = tolower(*p);
p++;
}
return string;
}
```
This starts by taking a string (something you'll learn about when you get into arrays) and runs through each location. Notice the p++. This increments the pointer, which means that it is looking at the next memory location. Each letter is a memory location, so in this way the pointer is looking at every letter and deciding what to do for each one.
### Const Qualifer
The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed ( Which depends upon where const variables are stored, we may change value of const variable by using pointer ).
# Pointer to variable
We can change the value of ptr and we can also change the value of object ptr pointing to.
Following code fragment explains pointer to variable
```c
#include <stdio.h>
int main(void)
{
int i = 10;
int j = 20;
int *ptr = &i; /* pointer to integer */
printf("*ptr: %d\n", *ptr);
/* pointer is pointing to another variable */
ptr = &j;
printf("*ptr: %d\n", *ptr);
/* we can change value stored by pointer */
*ptr = 100;
printf("*ptr: %d\n", *ptr);
return 0;
}
```
# Pointer to constant
We can change pointer to point to any other integer variable, but cannot change value of object (entity) pointed using pointer ptr.
```c
#include <stdio.h>
int main(void)
{
int i = 10;
int j = 20;
const int *ptr = &i; /* ptr is pointer to constant */
printf("ptr: %d\n", *ptr);
*ptr = 100; /* error: object pointed cannot be modified
using the pointer ptr */
ptr = &j; /* valid */
printf("ptr: %d\n", *ptr);
return 0;
}
```
# Constant pointer to variable
In this we can change the value of the variable the pointer is pointing to. But we can't change the pointer to point to
another variable.
```c
#include <stdio.h>
int main(void)
{
int i = 10;
int j = 20;
int *const ptr = &i; /* constant pointer to integer */
printf("ptr: %d\n", *ptr);
*ptr = 100; /* valid */
printf("ptr: %d\n", *ptr);
ptr = &j; /* error */
return 0;
}
```
# constant pointer to constant
Above declaration is constant pointer to constant variable which means we cannot change value pointed by pointer as well as we cannot point the pointer to other variable.
```c
#include <stdio.h>
int main(void)
{
int i = 10;
int j = 20;
const int *const ptr = &i; /* constant pointer to constant integer */
printf("ptr: %d\n", *ptr);
ptr = &j; /* error */
*ptr = 100; /* error */
return 0;
}
```
# Before you go on...
## A review
* Pointers are variables, but instead of storing a value, they store a memory location.
* `*` and `&` are used to access values at memory locations and to access memory locations, respectively.
* Pointers are useful for some of the underlying features of C.
#Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being:
1) the sizeof operator
* `sizeof(array)` returns the amount of memory used by all elements in array
* `sizeof(pointer)` only returns the amount of memory used by the pointer variable itself
2) the & operator
* &array is an alias for &array[0] and returns the address of the first element in array
* &pointer returns the address of pointer
3) a string literal initialization of a character array
* `char array[] = “abc”` sets the first four elements in array to a, b, c, and \0
* `char *pointer = “abc”` sets pointer to the address of the “abc” string (which may be stored in read-only memory and thus unchangeable)
4) Pointer variable can be assigned a value whereas array variable cannot be.
```c
int a[10];
int *p;
p = a; /*legal*/
a = p; /*illegal*/
```
5) Arithmetic on pointer variable is allowed.
```c
p++; /*Legal*/
a++; /*illegal*/
```

View File

@@ -0,0 +1,65 @@
---
title: Short-Circuit Evaluation
---
# Short-Circuit Evaluation
The Short-Circuit evaluation consist in check or execute the second argument only if the first argument is not enough to determine the value of the expression.
You can do a short-circuit evaluation with && and || operators.
## Example with && operator:
```c
canOpenFile(filename) && openFile(filename); // If you can open the file then open it.
```
The example above is equivalent to:
```c
if ( canOpenFile(filename) ) {
openFile(filename);
}
```
## Example with || operator:
```c
isServerOn || startServer(); // If the server is not on then start it.
```
The example above is equivalent to:
```c
if ( !isServerOn ) {
startServer();
}
```
## Keep it all together in real example
```c
#include <stdio.h>
#include <stdlib.h>
char *getName();
int main(int argc, char *argv[]) {
// Get first argument passed via terminal
char *name = argv[1];
// If name is not passed via terminal then print message and then get the name
name || printf("Please give me your name:") && (name = getName());
printf("Hello %s\n", name);
}
char *getName() {
// Allocate memory
char *name = malloc(30);
scanf("%s", name);
return name;
}
```

View File

@@ -0,0 +1,63 @@
---
title: Structures
---
## Structures in C
### What are Structures?
* A **structure** is a user-defined type in C. It is based on the idea that certain times, programmer wants to manage not just primitive data-types but also programmer-defined data-types.
* **Structure**, as the name suggests, consists of various primitive data-types, like character, integers, floating point variables, arrays, etc.
* **Structure** can also contain various other user-defined data types. You would learn about nested-structures next.
* **Structures** form the basis of **_object-oriented-programming_** as the concept of *class* originates from structures.
### struct keyword
* `struct` keyword can help us in defining a user-defined data type.
```C
struct StudentRecord
{
char Name[20];
int Class;
char Address[30];
char Phone[10];
};
```
* We can also define a **structure** using **typedef** which makes initializing a structure later in our program easier.
```C
typedef struct StudentRecord
{
char Name[20];
int Class;
char Address[30];
char Phone[10];
}Record;
```
In `main()`, the user-defined data-type **StudentRecord** is defined as:
```C
int main(void)
{
struct StudentRecord student1;
}
```
And using **typedef**, the user-defined data-type looks like:
```C
int main(void)
{
Record student1;
}
```
To access the data stored in **student1**, we use dot( **.** ) operator to access the contents of the structure type variable.
```C
int main(void)
{
struct StudentRecord student1;
student1.Class = 10;
printf("Enter Name of Student\n");
scanf("%s",&student1.Name);
printf("Enter Address of Student\n");
scanf("%s",&student1.Address);
printf("Enter Phone Number of Student\n");
scanf("%s",&student1.Phone);
// Printing the Data
printf("Name: %s \n, Class: %d \n, Address: %s \n, Phone: %s \n",student1.Name, student1.Class, student1.Address, student1.Phone);
}
```
### More Information
https://www.tutorialspoint.com/cprogramming/c_structures.htm

View File

@@ -0,0 +1,87 @@
---
title: Switch Case
---
# Switch Case
The switch statement is like a set of `if statements`.
It's a list of possibilities, with an action for each possibility, and an optional default action, in case nothing else evaluates to true.
We exit from the switch by `break`. If the `break` statement is not reached before the beginning of the next case, the execution will fall through and begin executing the code in the next case.
## Syntax of switch...case
```c
switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
```
## Example
Using a switch statement over multiple if/else statements can contribute to more speed and readability.
```c
# include <stdio.h>
int main() {
char operator;
double firstNumber,secondNumber;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);
switch (operator) {
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber+secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
break;
// Operator is doesn't match any case constant (+, -, *, /)
default:
printf("Error! operator is not correct");
}
return 0;
}
```
## Output:
```c
-> Enter an operator (+, -, *,): -
-> Enter two operands: 32.5
-> 12.4
-> 32.5 - 12.4 = 20.1
```
## Review : Switch vs if else
* Check the Testing Expression: An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.
* Switch better for Multi way branching: When compiler compiles a switch statement, it will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression. Therefore, if we need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression, while in case of if expressions, the compiler has no such knowledge.
* if-else better for boolean values: If-else conditional branches are great for variable conditions that result into a boolean, whereas switch statements are great for fixed data values.
* Speed: A switch statement might prove to be faster than ifs provided number of cases are good. If there are only few cases, it might not effect the speed in any case. Prefer switch if the number of cases are more than 5 otherwise, you may use if-else too.
* If a switch contains more than five items, its implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.
* Clarity in readability: A switch looks much cleaner when you have to combine cases. Ifs are quite vulnerable to errors too. Missing an else statement can land you up in havoc. Adding/removing labels is also easier with a switch and makes your code significantly easier to change and maintain.

View File

@@ -0,0 +1,80 @@
---
title: Ternary Operator
---
## Ternary Operator
Programmers use ternary operators in C for decision making inplace of conditional statements **if** and **else**.
The ternary operator is an operator that takes three arguments. The first argument is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison. If it helps you can think of the operator as shortened way of writing an if-else statement.
Here's a simple decision-making example using **if** and **else**:
```c
int a = 10, b = 20, c;
if (a < b) {
c = a;
}
else {
c = b;
}
printf("%d", c);
```
This example takes more than 10 lines, but that isn't necessary. You can write the above program in just 3 lines of code using the **ternary operator**.
### Syntax
`condition ? value_if_true : value_if_false`
The statement evalutes to statement\_1 if the condition is true, and statement\_2 otherwise.
Here's the above example re-written to use the ternary operator:
```c
int a = 10, b = 20, c;
c = (a < b) ? a : b;
printf("%d", c);
```
Output of the example should be:
```c
10
```
`c` is set equal to `a`, because the condition `a<b` was true.
This looks pretty simple, right? Do note that `value_if_true` and `value_if_false` must have the same type, and they cannot be full statements but simply expressions.
The ternary operator can be nested too same like nested if-else statements. Consider this nested if-else statement :
```c
int a = 1, b = 2, ans;
if (a == 1) {
if (b == 2) {
ans = 3;
} else {
ans = 5;
}
} else {
ans = 0;
}
printf ("%d\n", ans);
```
Here's the above code re-written using nested ternary operator:
```c
int a = 1, b = 2, ans;
ans = (a == 1 ? (b == 2 ? 3 : 5) : 0);
printf ("%d\n", ans);
```
The output of both of the above codes should be:
```c
3
```

View File

@@ -0,0 +1,101 @@
---
title: Variables and Basic Data Types
---
# Variables and Basic Data Types
## What is a variable?
Variables store values. Basically you give a name to a stored value, which you want to use later. It is important to note that one variable can store only one value at once. However later on, you can change the stored values later on in the code and you can also assign the value of one variable to another.
>When you create a variable, it is called `declaring`, and when you give it a value to store, it is called `assignment`. If you give the variable a value at the same time as declaring it, it is called `initializing`.
>C is very fussy about how you create variables and what you store in them. C is a `strongly typed` language, which means you have to define the type and name for each variable when you declare it. The name of a variable can be composed of letters, digits, and the underscore character.
## Basic types
In Standard C there are four important basic data types: `int`, `float`, `double`, `char`.
### Integers
For whole number values, the `int` keyword is used (short for integer).
Lets's look at a simple program:
```C
#include <stdio.h>
int main(void){
int a; // Declaring a variable which stores integer values and is called 'a'
int b = 5; //Initializing an int called 'b' with the value 5
a = 6; // Assigning the value 6 to the variable 'a'
int c;
c = a + b; // Assign the sum of 'a' and 'b' to the variable c
int d = a + c; //But we could also initialize it right away.
//Some shiny things
printf("%d \n", c);
printf("%d %d \n", a, b);
return 0;
}
```
Let's break down what we did under the `Some shingy things`:
```C
printf("%d \n", c);
```
To print out the value of the variable `c`, you can use the `printf()` function. Note the `%d` enclosed in the double quotes. This tells the computer to expect a **d**ecimal value, and that it is after the comma.
```C
printf("%d %d \n", a, b);
```
You can print out several integers in the order given after the comma.
Note that when you try to store a decimal value in an `int`, you will only get the whole part of it, because they will be truncated.
we can also write the program in the manner below:
```
#include <stdio.h>
int main(void){
int a=3,b=4,c; // we can also assign and declare the values in 1 line
c = a + b; // Assign the sum of 'a' and 'b' to the variable c
printf("%d %d \n", a, b);
printf("%d \n", c);
return 0;
}
```
### Floats and doubles
To store decimal values, you can use the `float` and `double` keywords. The difference between them is the precision, `double` has about 13 digits while `float` has about 7, but this differs from CPU to CPU.
```C
#include <stdio.h>
int main(void){
double a = 3.23;
printf("The variable a has the value: %f \n", a); //Double values can be printed with %f
return 0;
}
```
### Characters
You can store a single character with the `char` keyword. You will learn about storing multiple characters later, when we introduce `arrays`. Let's look at some code:
```C
#include <stdio.h>
int main(void){
char a = 'A'; // Initializing a char with the value 'A', note the simple quotes!
printf("The character was: %c ", a) //Chars can be printed with %c
return 0;
}
```
## The Boolean type
Later in C a new type was added, called `bool`. Bool stores true/false values, which comes in handy when you have to make decisions in the code. To use it though, you have to inlcude another header next to `<stdio.h>` called `<stdbool.h>`.
```C
#include <stdio.h>
#include <stdbool.h>
int main(void){
bool a = true;
bool b = false;
return 0;
}
```
## Comments
The type of a variable tells the compiler how much space to create (allocate) for the variable. Now you have seen the basic data types, but there are modifiers for them to modify the amount of space allocated for a variable. Modifiers can increase or decrease the default values. C has 5 modifiers: `short`, `long`, `signed`, `unsigned`, `long long`. They are prefixed to the basic types.

View File

@@ -0,0 +1,105 @@
---
title: Variables in C
---
# Using Variables in C
Now you know what your options with data types are. Let's apply it with a simple example here:
```C
#include <stdio.h>
int main(void) {
int my_first_variable = 12;
double my_second_variable = 983.9;
printf("My int is %i\n", my_first_variable);
printf("My double is %f\n", my_second_variable);
return 0;
}
```
There's a lot of new things to take a look at here! You've already seen the `#include` and `int main(void)`, so that's not worth dwelling on. What is new is `int my_first_variable = 12;`.
From earlier, you should recall that `int` allows us to store integer values. After the word `int` comes `my_first_variable`. This is a variable- it can store values, and you can change what values are being stored in it. We start with a declaration, where we tell the computer that the initial value of this variable is 12. It's important to tell the computer that we want a variable to exist before we try to use it. Otherwise, the variable won't exist, and the compiler won't know what to do when you try to tell it to use a variable that doesn't exist.
The next line is `double my_second_variable = 983.9`. The similar structure from before should make it clear that you're telling the computer to create a variable called 'my_second_variable' that can hold `double` values, and that you want it to be set to 983.9.
The actual name of the variable isn't important. It can be whatever you want, as long as it isn't any of the words that C has reserved for the actual language, and it can only include numbers and letters, never any spaces.The variable name cannot start with a number. By convention, C uses clear variable names that substitute underscores for spaces. The variable could also be camelCase, like this:
```C
double myFirstVariable = 983.9
```
In fact, it would be this way in other languages. However, in C this is not typically done.
After the variables are created, we start actually using them:
```C
printf("My int is %i\n", my_first_variable);
printf("My double is %f\n", my_second_variable);
```
This is the same printf() that you used earlier, but now it has a few different features. First, notice that there are now two things within the parenthesis: the text to be printed to the screen, and the variable. Also notice the `%i` and the `%f`. This is called a *format specifier*, and is used to specify what format something should be printed in. Whenever printf() comes across one of these, it will try to insert the variable given into that point.
Because the data types of our variables are represented in a computer in several different ways, there are several different ways for C to display them:
Data Type | Format Specifier
----------------|------------------
char | %c, or %hhi to print as a number when signed, %hhu to print as a number when unsigned
short | %hi, or %hu when unsigned
int | %i, %d can also be used
long | %li, or %lu when unsigned
long long | %lli, or %llu when unsigned
float | %f
double | %f
long double | %Lf
unsigned int | %lu
In order to print a variable, you must have a format specifier, and then a variable to format. Several format specifiers can be together in the same printf(), as well:
```C
printf("%i and %f", my_first_variable, my_second_variable);
```
In order to scan a variable, you must have a format specifier, and then the address of the variable(denoted by adding '&' sign before the variable name) to be taken as input. Several format specifiers can be together in the same scanf(), as well:
```C
scanf("%i and %f", &my_first_variable, &my_second_variable);
```
Now let's start changing the values within our variables. Here's the same examples from before, but with a few more lines:
```C
#include <stdio.h>
int main(void) {
int my_first_variable = 12;
double my_second_variable = 983.9;
printf("My int is %i\n", my_first_variable);
printf("My double is %f\n", my_second_variable);
my_second_variable = -18.2 + my_first_variable;
printf("Now my double is %f\n", my_second_variable);
return 0;
}
```
Now there's a line that reads `my_second_variable = -18.2 + my_first_variable;`. This equation assigns a new value to the variable on the left. Whenever a new value is being assigned, the variable that it is being assigned to must always be on the left, and must always be there alone. Your program will find the result of the right hand side, and assign it to the variable on the left. In this case, we've added my_first_variable to -18.2. my_first_variable is 12, and -18.2 + 12 is -6.2, so my_second_variable becomes -6.2 after this step. We'll get more into math in a little bit!
## A little more on floats and doubles
When printing out floats and doubles, a lot of times we need precision after the decimal point. If we have
```C
float var1 = 15.3;
printf("%f");
```
We get `15.300000`. So, say we just want two places after the decimal to give us `15.30`. We would use %.2f. Notice, we use a decimal point in front of the amount of decimal places we want followed by the f, signifing we want to print a float or double.
# Names for Variables
* The only characters you can use in names are alphabetic characters, numeric digits, and
the underscore (_) character.
* The first character in a name cannot be a numeric digit.
* Uppercase characters are considered distinct from lowercase characters.
* You cant use a C keyword for a name.
# Before you go on...
## A review
* Variables need to be created before they are used.
* Variables are created in the following format: `datatype variable_name = number`.
* Format specifiers allow for variables to be printed.
* The equals sign `=` allows for values to be assigned to variables.