DEV Community

Tawhid
Tawhid

Posted on • Edited on

Learn C with me! C in one blog

C is being there for years now but for beginners C is very hard to learn.I already use C and bash on a daily basis because I use linux as daily drive.Today I will teach you how to code in C.
You can grab the cheatsheet from here
after this blog I hope you will have a base understanding of C.

variables:

variable is a container that stores a value.

Rules for naming a variable in c:
-First character should be an underscore or a letter
-No commas or space allowed
-names are case sensitive
-no other special character rather than ("_")

int myNum = 5;             // Integer (whole number)
float myFloatNum = 5.99;   // Floating point number
char myLetter = 'D';       // Character
Enter fullscreen mode Exit fullscreen mode

If a variable value can't be changed it is called
a constant.
Types of constants:
-Integer constants //1,2
-Real constants //-9.5,7.6
-character constant // @
If there is something reserved builtin a language it is called a keyword.Various keywords have various uses.
Keywords:
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double.

Header files:
A header file is afile that has a .h extension.
These preprocessor directives are used for instructing compiler that these files need to be processed before compilation.
the stdio we imported at start is a header file.
It means standard input output.

Return Code:
we return a code with the status of the compilation in C.
You need to include stdlib header to use it.
exit() and return are equivalent.
The following exit codes are microsoft specific.

exit(1): It indicates abnormal termination of a program perhaps as a result a minor problem in the code.
exit(2): It is similar to exit(1) but is displayed when the error occurred is a major one. This statement is rarely seen.
exit(127): It indicates command not found.
exit(132): It indicates that a program was aborted (received SIGILL), perhaps as a result of illegal instruction or that the binary is probably corrupt.
exit(133): It indicates that a program was aborted (received SIGTRAP), perhaps as a result of dividing an integer by zero.
exit(134): It indicates that a program was aborted (received SIGABRT), perhaps as a result of a failed assertion.
exit(136): It indicates that a program was aborted (received SIGFPE), perhaps as a result of floating point exception or integer overflow.
exit(137): It indicates that a program took up too much memory.
exit(138): It indicates that a program was aborted (received SIGBUS), perhaps as a result of unaligned memory access.
exit(139): It indicates Segmentation Fault which means that the program was trying to access a memory location not allocated to it. This mostly occurs while using pointers or trying to access an out-of-bounds array index.
exit(158/152): It indicates that a program was aborted (received SIGXCPU), perhaps as a result of CPU time limit exceeded.
exit(159/153): It indicates that a program was aborted (received SIGXFSZ), perhaps as a result of File size limit exceeded.

Print a value:
The printf() function is used to output values/print text.

#include <stdio.h>

int main() {
  printf("Hello World!\n");
  printf("I am learning C.\n");
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Comments:
Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

Multi-line comments start with /* and ends with */.

Specifiers:
if we try to print a variable name it will give use error unless we use specifers.
ex:

printf("%d\n", Afloat);
Enter fullscreen mode Exit fullscreen mode

%d or %i = int
%f = floats
%lf = double
%c = characters
%s = string

Operator:

Operators are used to perform operations on variables and values.
Arithmetic:

  • = Addition
  • = substraction
  • = multiplication / = Division % = Modulus ++ = increment -- = Decrement Assignment: = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3

Condition:
C has the following conditional statements:

Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of C code to be executed if a condition is true.

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:

//instead of this
int time = 20;
if (time < 18) {
  printf("Good day.\n");
} else {
  printf("Good evening.\n");
}
//you can do this
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");
Enter fullscreen mode Exit fullscreen mode

Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
Enter fullscreen mode Exit fullscreen mode

The break Keyword
When C reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

The default Keyword
The default keyword specifies some code to run if there is no case match.

Loops:

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.
while loop

while (condition) {
  // code block to be executed
}
//for loop
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    printf("%d\n", i);
}
//do while loop
do {
  // code block to be executed
}
while (condition);
Enter fullscreen mode Exit fullscreen mode

Arrays:
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To create an array, define the data type (like int) and specify the name of the array followed by square brackets [].

To insert values to it, use a comma-separated list, inside curly braces:

int myNumbers[] = {25, 50, 75, 100};

Change an Array Element
To change the value of a specific element, refer to the index number:

myNumbers[0] = 33;

Loop Through an Array
You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

Example

int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {
  printf("%d\n", myNumbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

Set Array Size
Another common way to create arrays, is to specify the size of the array, and add elements later:

Example:

// Declare an array of four integers:
int myNumbers[4];

// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Enter fullscreen mode Exit fullscreen mode

Strings:
Strings are used for storing text/characters.

For example, "Hello World" is a string of characters.

Unlike many other programming languages, C does not have a String type to easily create string variables. However, you can use the char type and create an array of characters to make a string in C:

char greetings[] = "Hello World!";

User Input:
You have already learned that printf() is used to output values in C.

To get user input, you can use the scanf() function:

Example
Output a number entered by the user:

// Create an integer variable that will store the number we get from the user
int myNum;

// Ask the user to type a number
printf("Type a number: \n");

// Get and save the number the user types
scanf("%d", &myNum);

// Output the number the user typed
printf("Your number is: %d", myNum);
Enter fullscreen mode Exit fullscreen mode

Memory Address:
When a variable is created in C, a memory address is assigned to the variable.

The memory address is the location of where the variable is stored on the computer.

When we assign a value to the variable, it is stored in this memory address.

To access it, use the reference operator (&), and the result will represent where the variable is stored:

Example:

int myAge = 43;
printf("%p", &myAge); // Outputs 0x7ffe5367e044
Enter fullscreen mode Exit fullscreen mode

Pointer:

A pointer is a variable that stores the memory address of another variable as its value.

C uses pointers to create dynamic data structures .Data structures built up from blocks of memory allocated from the heap at run-time. C uses pointers to handle variable parameters passed to functions. Pointers in C provide an alternative way to access information stored in arrays.

A pointer variable points to a data type (like int) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer:

Example

int myAge = 43;     // An int variable
int* ptr = &myAge;  // A pointer variable, with the name ptr, that stores the address of myAge

// Output the value of myAge (43)
printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)
printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
Enter fullscreen mode Exit fullscreen mode

Functions:
For example, main() is a function, which is used to execute code, and printf() is a function; used to output/print text to the screen.

Create a Function
To create (often referred to as declare) your own function, specify the name of the function, followed by parentheses () and curly brackets {}:

void myFunction() {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be executed when they are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

// Create a function
void myFunction() {
  printf("I just got executed!");
}

int main() {
  myFunction(); // call the function
  return 0;
}

// Outputs "I just got executed!"
Enter fullscreen mode Exit fullscreen mode

Math Functions:
There is also a list of math functions available, that allows you to perform mathematical tasks on numbers.

To use them, you must include the math.h header file in your program:

#include <math.h>
//Square root
printf("%f", sqrt(16));
Enter fullscreen mode Exit fullscreen mode

Support is appreciated!
Buy me a coffee

Top comments (4)

Collapse
 
pauljlucas profile image
Paul J. Lucas

You also return from main(), but then mention exit() status codes — and never define exit() nor mention that you need to #include <stdlib.h> to use it, nor mention that return and exit() from main() are equivalent. Your status codes are also Microsoft-specific. Indeed, status codes are not defined by the C standard with the exception of 0 or non-0.

You explain what pointers are but not why anybody would need to use them. Why would you need to have the address of another variable?

Some of your printf() examples don't include the \n at the end.

Collapse
 
dumboprogrammer profile image
Tawhid

Thank you so much man for pointing out the mistakes.
I really appreciate it.
Thanks to you I was able to make it better.

Collapse
 
pauljlucas profile image
Paul J. Lucas

C is the mother of all languages ...

No, FORTRAN is.

First character should be an underscore or a letter

No, first character must be a letter; an underscore counts as a letter. "Should" means "is a good idea, but not required."

It would also really help if you used the correct markdown for your code blocks so indentation happens properly. Use 3 back-ticks on a line by themselves to surround your code blocks. Your code examples are hard to read.

Your example for the ?: operator is not how it's typically used.

It's not clear what the point of your article is since there are many good introductions to C (with good formatting) that already exist. What does yours bring to the table?

Collapse
 
dumboprogrammer profile image
Tawhid

Thanks for pointing out, I have fixed them