C Quick Guide

We are going to summarize the most used functions in C in this tutorial

Types of C Variables

Variables are containers for storing data values.


We have different types of variables in C Programming language.

  • int- stores integers, such as 123 or -123
  • float- stores floating point numbers, such as 19.99 or -19.99
  • char- stores single characters, like as 'q' or 'd'. Char values are surrounded by single quotes

Code:


  #include

  int main()
  {
  int myInt = 15;
  float myfloat = 4.7;
  char myChar = 'a';
  printf("%d\n", myInt);
  printf("%f\n", myfloat);
  printf("%c\n", myChar);
  return 0;
}


Output:


15

4.700000

a

Explanation:

In the main function,we declared int named myInt and assign value 15 to it (By using the syntax: type variableName = value;).

To print out variables in C, we use format specifiers
This is starts with a percentage sign %, followed by a character.
For example:
%d:for integers.
%f:for float.
%c for char.



C if... Else

The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is satisfied.


If:

Use the if statement to specify a block of C code to be executed if a condition is true.



      int main()
      {
      int x = 20;
      int y = 18;
      if (x > y)
      {
      printf("x is greater than y");
      }

      return 0;
      }


  

Output

x is greater than y


The > operator is used in the example above to determine whether two variables, x and y, are greater than one another. We print "x is greater than y" to the screen since x is 20 and y is 18, and we know that 20 is greater than 18 because of this.


Else:

Use the else statement to specify a block of code to be executed if the condition is false.



    #include 
    int main() {
    int time = 20;
    if (time < 18) {
    printf("Good day.");
    } else {
    printf("Good evening.");
    }
    return 0;
    }


  

Output

Good evening


Because time (20) in the previous example is larger than 18, the condition is false. As a result, we continue on to the next condition and print "Good evening" on the screen. "Good day" would be printed by the programme if the time was less than 18.


If .. Else:

Use the else if statement to specify a new condition if the first condition is false.



    #include 
    int main() {
    int time = 22;
    if (time < 10) {
    printf("Good morning.");
    } else if (time < 20) {
    printf("Good day.");
    } else {
    printf("Good evening.");
    }
    return 0;
    }


  

Output:


Good evening

The first condition is incorrect in the example above since time (22) is more than 10, which explains why. Since both the first and second conditions in the otherwise if statement are false, we continue on to the else condition and print the words "Good evening" on the screen.


When the time was 14, though, our programme printed "Good day."



C Switch

The Switch statement selects one of many code blocks to be executed.


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


This is how switch statement works:


  • • The switch expression is evaluated once
  • • The value of the expression is compared with the values of each case
  • • If there is a match, the associated block of code is executed
  • • The break statement breaks out of the switch block and stops the execution
  • •The default statement is optional, and specifies some code to run if there is no case match

Code


  #include 
  int main() {
  int day = 4;
  switch (day) {
  case 1:
  printf("Monday"); break;
  case 2:
  printf("Tuesday"); break;
  case 3:
  printf("Wednesday"); break;
  case 4:
  printf("Thursday"); break;
  case 5:
  printf("Friday"); break;
  case 6:
  printf("Saturday"); break;
  case 7:
  printf("Sunday"); break;
  }
  return 0;
  }


Output:


Thursday


Explanation

Here switch statement is operated on day, day has value 4 and case 4 is executed.



C 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.



char greetings []='Hello World'

#include 

int main()
{
char greetings[] = "Hello, World!";
printf("%s", greetings);
return 0;
}

Output:


Hello, World!


Explanation

As C does not have string type, So you can use the Char type and create an array of characters to make a string in C.


To output the string, you can use the printf() function together with the format specifier %s to tell C that we are now working with strings.


• Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets [].



char greetings [] = 'Hello, World!';
printf('%c', greetings [0]);

Output:


H



Note: We must use the %c format specifier to print a single character.



C For Loops

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


Loops are useful because they speed up programming, lower mistake rates, and improve readability.


Use the for loop when you are certain of the number of times you want to loop through a piece of code.



for (statement 1 ; statement 2 ; statement 3 ;) }
// code block
}


Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed.

Code:


  #include 
  int main() {
  int i;
  for (i = 0; i < 5; i++) {
  printf("%d\n", i);
  }
  return 0;
  }


Output

0 1 2 3 4

Explanation

Before the loop begins, statement 1 sets a variable (int i = 0).


Statement 2 specifies the prerequisites for the loop's operation (i must be less than 5). The loop will repeat itself if the condition is true and come to an end if it is false.

br

With each iteration of the loop's code block, statement 3 increases the value by one(i++).



C Arrays

Arrays, used to store multiple values in a single variable


To create an array, define the data type 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};


To access an arrelement, refer to its index number. Array indexes start with 0. myNumbers[0] refers to 25.

Code:


  #include 
  int main() {
  int myNumbers[] = {25, 50, 75, 100};
  printf("%d", myNumbers[0]);
  return 0;
  }


Output

25


Explanation

Declare integer Array named myNumbers and store {25, 50, 75 100} to it (By using the syntax: type arrayName = {value1, value2, ……};).


To output first value of array, use format specifiers %d because here array contains integers.

You can change the value of a specific element, refer to the index number:



myNumbers [0]=33


Now myNumbers[0] refers to 33.



C Functions

A unit of code known as a function, sometimes known as a method, only executes when it is invoked. You can supply parameters—data—to a function.


Functions are used to carry out certain activities and are crucial for code reuse: One code definition can be used several times.




#include 

// Create a function
void myFunction()
{
printf("Got executed!");
}

int main()
{
myFunction();
return 0;
}

Output:


got executed

Explanation:

Use parentheses () and curly brackets {} after the function name to create (also known as declare) your own function.


Write the name of the function in the main function, followed by two parentheses (), and a semicolon. When myFunction() is called in the example below, a text is printed.



C Pointers

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


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:


Code:


  #include 

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

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

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

  // Output the memory address
  printf("%p\n", ptr);

  return 0;
  }


Output:


43

0x7ff5367e044

0x7ff5367e044

Explanation:

We are creating an int variable that points to a pointer variable called ptr. Keep in mind that the pointer's type must match with the type of the variable you are manipulating.


Use the & operator to store the memory address of the myAge variable, and assign it to the pointer.


Now, ptr holds the value of myAge's memory address.



C References (Call by Reference) Using C Swap Function

Passing by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function.


In call by reference, the operation performed on formal parameters, affects the value of actual parameters because all the operations performed on the value stored in the address of actual parameters.


Code:


    #include 

    void swapnum(int *var1, int *var2)
    {
    int tempnum ;
    tempnum = *var1;
    *var1 = *var2;
    *var2 = tempnum;
    }

    int main()
    {
    int num1 =35, num2 = 45;
    printf("Before swapping:");
    printf("\nnum value is %d", num1);
    printf("\nnum2 value is %d", num2);

    /*Calling swap function*/
    swapnum(&num1, &num2);
    printf("\nAfter swapping:");
    printf("\nnum value is %d", num1);
    printf("\nnum2 value is %d", num2);
    return 0;
    }


  

before swapping :

num1 value is 35

num2 value is 45

after swapping:

num1 value is 45

num2 value is 35

Explanation:

Here, we're utilizing call by reference to switch the integers. As you can see, after using the swapnum() function, the values of the variables changed since the addresses of the variables num1 and num2 were swapped.


<

C Structures

The use of structures, also known as structs, allows you to collect numerous related variables in a single location. A member of the structure is referred to as each variable in it.

Unlike an array, a structure can contain many different data types.


Code:


  #include 
  // Create a structure called myStructure
  struct myStructure {

      int myNum;
      char myLetter;

  };

  int main() {

  // Create a structure variable of myStructure called s1
  struct myStructure s1;

  // Assign values to members of s1
  s1.myNum = 13;
  s1.myLetter = 'B';

  // Print values
  printf("My number: %d\n", s1.myNum);
  printf("My letter: %c\n", s1.myLetter);
  return 0;
  }


Output:


My Number : 13 My Letter : B

Explanation:

The struct keyword is used to create a structure, and curly brackets are used to declare each member of the structure. You must make a variable of the structure in order to access it.


Use the struct keyword inside the main() method, followed by the name of the structure and then the name of the structure variable.


To access members of a structure, use the dot syntax (.)


© Copyright 2022 Advanced PLC. All rights reserved.