Learn C Programming

Learn C Programming   

 

developerinsider.in/turbocpp

         The Definitive Guide

C is a powerful general-purpose programming language. It is fast, portable and available in all platforms.
If you are new to programming, C is a good choice to start your programming journey.
This is a comprehensive guide on how to get started in C programming language, why you should learn it and how you can learn it.
 c programming
c programming
  








Introduction

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • Basic Examples                                                                                                                                                                                                                                                                                              

    C Keywords and Identifiers

    In this tutorial, you will learn about keywords; reserved words in C programming that are part of the syntax. Also, you will learn about identifiers and how to name them.

    Character set

    A character set is a set of alphabets, letters and some special characters that are valid in C language.

    Alphabets

    Uppercase: A B C ................................... X Y Z
    Lowercase: a b c ...................................... x y z
    C accepts both lowercase and uppercase alphabets as variables and functions.

    Digits

    0 1 2 3 4 5 6 7 8 9

    Special Characters

    Special Characters in C Programming
    , < > . _
    ( ) ; $ :
    % [ ] # ?
    ' & { } "
    ^ ! * / |
    - \ ~ +
    White space Characters
    Blank space, newline, horizontal tab, carriage, return and form feed.

    C Keywords

    Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:
    1. int money;
    Here, int is a keyword that indicates money is a variable of type int (integer).
    As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords allowed in ANSI C.
    C Keywords
    auto double int struct
    break else long switch
    case enum register typedef
    char extern return union
    continue for signed void
    do if static while
    default goto sizeof volatile
    const float short unsigned
    All these keywords, their syntax, and application will be discussed in their respective topics. However, if you want a brief overview of these keywords without going further, visit List of all keywords in C programming.

    C Identifiers

    Identifier refers to name given to entities such as variables, functions, structures etc.
    Identifiers must be unique. They are created to give a unique name to an entity to identify it during the execution of the program. For example:
    1. int money;
    2. double accountBalance;
    Here, money and accountBalance are identifiers.
    Also remember, identifier names must be different from keywords. You cannot use int as an identifier because int is a keyword.

    Rules for naming identifiers

    1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
    2. The first letter of an identifier should be either a letter or an underscore.
    3. You cannot use keywords as identifiers.
    4. There is no rule on how long an identifier can be. However, you may run into problems in some compilers if the identifier is longer than 31 characters.
    You can choose any name as an identifier if you follow the above rule, however, give meaningful names to identifiers that make sense.


    C Variables, Constants and Literals

    In this tutorial, you will learn about variables and rules for naming a variable. You will also learn about different literals in C programming and how to create constants.

    Variables

    In programming, a variable is a container (storage area) to hold data.
    To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location. For example:
    1. int playerScore = 95;
    Here, playerScore is a variable of int type. Here, the variable is assigned an integer value 95.
    The value of a variable can be changed, hence the name variable.
    1. char ch = 'a';
    2. // some code
    3. ch = 'l';

    Rules for naming a variable

    1. A variable name can have only letters (both uppercase and lowercase letters), digits and underscore.
    2. The first letter of a variable should be either a letter or an underscore.
    3. There is no rule on how long a variable name (identifier) can be. However, you may run into problems in some compilers if the variable name is longer than 31 characters.
    Note: You should always try to give meaningful names to variables. For example: firstName is a better variable name than fn.
    C is a strongly typed language. This means that the variable type cannot be changed once it is declared. For example:
    1. int number = 5; // integer variable
    2. number = 5.5; // error
    3. double number; // error
    Here, the type of number variable is int. You cannot assign a floating-point (decimal) value 5.5 to this variable. Also, you cannot redefine the data type of the variable to double. By the way, to store the decimal values in C, you need to declare its type to either double or float.
    Visit this page to learn more about different types of data a variable can store.

    Literals

    A literal is a value (or an identifier) whose value cannot be altered in a program. For example: 1, 2.5, 'c' etc.
    Here, 1,2.5 and 'c' are literals. Why? You cannot assign different values to these terms.

    1. Integers

    An integer is a numeric literal(associated with numbers) without any fractional or exponential part. There are three types of integer literals in C programming:
    • decimal (base 10)
    • octal (base 8)
    • hexadecimal (base 16)
    For example:
    Decimal: 0, -9, 22 etc
    Octal: 021, 077, 033 etc
    Hexadecimal: 0x7f, 0x2a, 0x521 etc
    In C programming, octal starts with a 0, and hexadecimal starts with a 0x.

    2. Floating-point Literals

    A floating-point literal is a numeric literal that has either a fractional form or an exponent form. For example:
    -2.0
    0.0000234
    -0.22E-5
    Note: E-5 = 10-5

    3. Characters

    A character literal is created by enclosing a single character inside single quotation marks. For example: 'a', 'm', 'F', '2', '}' etc;

    4. Escape Sequences

    Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc.
    In order to use these characters, escape sequences are used.
    Escape Sequences
    Escape Sequences Character
    \b Backspace
    \f Form feed
    \n Newline
    \r Return
    \t Horizontal tab
    \v Vertical tab
    \\ Backslash
    \' Single quotation mark
    \" Double quotation mark
    \? Question mark
    \0 Null character

    For example: \n is used for a newline. The backslash \ causes escape from the normal way the characters are handled by the compiler.

    5. String Literals

    A string literal is a sequence of characters enclosed in double-quote marks. For example:
    "good"                  //string constant
    ""                     //null string constant
    "      "               //string constant of six white space
    "x"                    //string constant having a single character.
    "Earth is round\n"         //prints string with a newline

    Constants

    If you want to define a variable whose value cannot be changed, you can use the const keyword. This will create a constant. For example,
    1. const double PI = 3.14;
    Notice, we have added keyword const.
    Here, PI is a symbolic constant; its value cannot be changed.
    1. const double PI = 3.14;
    2. PI = 2.9; //Error

    You can also define a constant using the #define preprocessor directive. We will learn about it in C Macros tutorial.

        
          

    C Data Types

    In this tutorial, you will learn about basic data types such as int, float, char etc. in C programming.
    In C programming, data types are declarations for variables. This determines the type and size of data associated with variables. For example,
    1. int myVar;
    Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.

    Basic types

    Here's a table containing commonly used types in C programming for quick access.
    Type Size (bytes) Format Specifier
    int at least 2, usually 4 %d
    char 1 %c
    float 4 %f
    double 8 %lf
    short int 2 usually %hd
    unsigned int at least 2, usually 4 %u
    long int at least 4, usually 8 %li
    long long int at least 8 %lli
    unsigned long int at least 4 %lu
    unsigned long long int at least 8 %llu
    signed char 1 %c
    unsigned char 1 %c
    long double at least 10, usually 12 or 16 %Lf

    int

    Integers are whole numbers that can have both zero, positive and negative values but no decimal values. For example, 0, -5, 10
    We can use int for declaring an integer variable.
    1. int id;
    Here, id is a variable of type integer.
    You can declare multiple variables at once in C programming. For example,
    1. int id, age;
    The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -2147483648 to 2147483647.

    float and double

    float and double are used to hold real numbers.
    1. float salary;
    2. double price;
    In C, floating-point numbers can also be represented in exponential. For example,
    1. float normalizationFactor = 22.442e2;
    What's the difference between float and double?
    The size of float (single precision float data type) is 4 bytes. And the size of double (double precision float data type) is 8 bytes.

    char

    Keyword char is used for declaring character type variables. For example,
    1. char test = 'h';
    The size of the character variable is 1 byte.

    void

    void is an incomplete type. It means "nothing" or "no type". You can think of void as absent.
    For example, if a function is not returning anything, its return type should be void.
    Note that, you cannot create variables of void type.

    short and long

    If you need to use a large number, you can use a type specifier long. Here's how:
    1. long a;
    2. long long b;
    3. long double c;
    Here variables a and b can store integer values. And, c can store a floating-point number.
    If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can use short.
    short d;
    You can always check the size of a variable using the sizeof() operator.
    1. #include <stdio.h>
    2. int main() {
    3. short a;
    4. long b;
    5. long long c;
    6. long double d;
    7. printf("size of short = %d bytes\n", sizeof(a));
    8. printf("size of long = %d bytes\n", sizeof(b));
    9. printf("size of long long = %d bytes\n", sizeof(c));
    10. printf("size of long double= %d bytes\n", sizeof(d));
    11. return 0;
    12. }

    signed and unsigned

    In C, signed and unsigned are type modifiers. You can alter the data storage of a data type by using them. For example,
    1. unsigned int x;
    2. int y;
    Here, the variable x can hold only zero and positive values because we have used the unsigned modifier.
    Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1, whereas variable x can hold values from 0 to 232-1.

    Other data types defined in C programming are:
    • bool Type
    • Enumerated type
    • Complex types

    Derived Data Types

    Data types that are derived from fundamental data types are derived types. For example: arrays, pointers, function types, structures, etc.
    We will learn about these derived data types in later tutorials.
                                                                                                                                                                

    C Input Output (I/O)

    In this tutorial, you will learn to use scanf() function to take input from the user, and printf() function to display output to the user.

    C Output

    In C programming, printf() is one of the main output function. The function sends formatted output to the screen. For example,

    Example 1: C Output

    1. #include <stdio.h>
    2. int main()
    3. {
    4. // Displays the string inside quotations
    5. printf("C Programming");
    6. return 0;
    7. }
    Output
    C Programming
    How does this program work?
  • All valid C programs must contain the main() function. The code execution begins from the start of the main() function.
  • The printf() is a library function to send formatted output to the screen. The function prints the string inside quotations.
  • To use printf() in our program, we need to include stdio.h header file using #inclue <stdio.h> statement.
  • The return 0; statement inside the main() function is the "Exit status" of the program. It's optional.

Example 2: Integer Output

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int testInteger = 5;
  5. printf("Number = %d", testInteger);
  6. return 0;
  7. }
Output
Number = 5
We use %d format specifier to print int types. Here, the %d inside the quotations will be replaced by the value of testInteger.

Example 3: float and double Output

  1. #include <stdio.h>
  2. int main()
  3. {
  4. float number1 = 13.5;
  5. double number2 = 12.4;
  6. printf("number1 = %f\n", number1);
  7. printf("number2 = %lf", number2);
  8. return 0;
  9. }
Output
number1 = 13.500000
number2 = 12.400000
To print float, we use %f format specifier. Similarly, we use %lf to print double values.

Example 4: Print Characters

  1. #include <stdio.h>
  2. int main()
  3. {
  4. char chr = 'a';
  5. printf("character = %c.", chr);
  6. return 0;
  7. }
Output
character = a
To print char, we use %c format specifier.

C Input

In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards.

Example 5: Integer Input/Output

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int testInteger;
  5. printf("Enter an integer: ");
  6. scanf("%d", &testInteger);
  7. printf("Number = %d",testInteger);
  8. return 0;
  9. }
Output
Enter an integer: 4
Number = 4
Here, we have used %d format specifier inside the scanf() function to take int input from the user. When the user enters an integer, it is stored in the testInteger variable.
Notice, that we have used &testInteger inside scanf(). It is because &testInteger gets the address of testInteger, and the value entered by the user is stored in that address.

Example 6: Float and Double Input/Output

  1. #include <stdio.h>
  2. int main()
  3. {
  4. float num1;
  5. double num2;
  6. printf("Enter a number: ");
  7. scanf("%f", &num1);
  8. printf("Enter another number: ");
  9. scanf("%lf", &num2);
  10. printf("num1 = %f\n", num1);
  11. printf("num2 = %lf", num2);
  12. return 0;
  13. }
Output
Enter a number: 12.523
Enter another number: 10.2
num1 = 12.523000
num2 = 10.200000
We use %f and %lf format specifier for float and double respectively.

Example 7: C Character I/O

  1. #include <stdio.h>
  2. int main()
  3. {
  4. char chr;
  5. printf("Enter a character: ");
  6. scanf("%c",&chr);
  7. printf("You entered %c.", chr);
  8. return 0;
  9. }
Output
Enter a character: g
You entered g.
When a character is entered by the user in the above program, the character itself is not stored. Instead, an integer value (ASCII value) is stored.
And when we display that value using %c text format, the entered character is displayed. If we use %d to display the character, it's ASCII value is printed.

Example 8: ASCII Value

  1. #include <stdio.h>
  2. int main()
  3. {
  4. char chr;
  5. printf("Enter a character: ");
  6. scanf("%c", &chr);
  7. // When %c is used, a character is displayed
  8. printf("You entered %c.\n",chr);
  9. // When %d is used, ASCII value is displayed
  10. printf("ASCII value is % d.", chr);
  11. return 0;
  12. }
Output
Enter a character: g
You entered g.
ASCII value is 103.

I/O Multiple Values

Here's how you can take multiple inputs from the user and display them.
  1. #include <stdio.h>
  2. int main()
  3. {
  4. int a;
  5. float b;
  6. printf("Enter integer and then a float: ");
  7. // Taking multiple inputs
  8. scanf("%d%f", &a, &b);
  9. printf("You entered %d and %f", a, b);
  10. return 0;
  11. }
Output
Enter integer and then a float: -3
3.4
You entered -3 and 3.400000

Format Specifiers for I/O

As you can see from the above examples, we use
  • %d for int
  • %f for float
  • %lf for double
  • %c for char
Here's a list of commonly used C data types and their format specifiers.
Data Type         Format Specifier
int            %d
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
signed char %c
unsigned char %c
long double

C Introduction Examples

In this tutorial, you will find links to simple C programs such as: displaying a line, adding two numbers, find ASCII value of a character, etc.
We have learned about the following topics so far:
  1. Variables and Constants
  2. Data Types
  3. Input and Output in C programming
  4. Operators
To understand these topics better, we have created some examples.
Before you go through these examples, we suggest you to try creating these programs on our own.
We understand that programming can by start If you are just a programming newbie. In that case, go through each example below and see if you can understand them. Once you do that, try writing these programs on your own.

Examples

C program to print a sentence
C program to print an integer entered by the user
C program to add two integers entered by the User
C program to multiply two floating-point numbers
C program to find ASCII value of a character entered by the user
C program to find quotient and remainder of Two Integers
C program to find the size of int, float, double and char
C program to demonstrate the working of keyword long
C program to swap two numbers
%Lf   

C Programming Operators

In this tutorial, you will learn about different operators in C programming with the help of examples.
An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.

C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)

Example 1: Arithmetic Operators

  1. // Working of arithmetic operators
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int a = 9,b = 4, c;
  6. c = a+b;
  7. printf("a+b = %d \n",c);
  8. c = a-b;
  9. printf("a-b = %d \n",c);
  10. c = a*b;
  11. printf("a*b = %d \n",c);
  12. c = a/b;
  13. printf("a/b = %d \n",c);
  14. c = a%b;
  15. printf("Remainder when a divided by b = %d \n",c);
  16. return 0;
  17. }
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The operators +, - and * computes addition, subtraction, and multiplication respectively as you might have expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1. The % operator can only be used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
// Either one of the operands is a floating-point number
a/b = 2.5  
a/d = 2.5  
c/b = 2.5  

// Both operands are integers
c/d = 2

C Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.

Example 2: Increment and Decrement Operators

  1. // Working of increment and decrement operators
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int a = 10, b = 100;
  6. float c = 10.5, d = 100.5;
  7. printf("++a = %d \n", ++a);
  8. printf("--b = %d \n", --b);
  9. printf("++c = %f \n", ++c);
  10. printf("--d = %f \n", --d);
  11. return 0;
  12. }
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes like a++ and a--. Visit this page to learn more about how increment and decrement operators work when used as postfix.

C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment operator is =
Operator Example Same as
= a = b 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

Example 3: Assignment Operators

  1. // Working of assignment operators
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int a = 5, c;
  6. c = a; // c is 5
  7. printf("c = %d\n", c);
  8. c += a; // c is 10
  9. printf("c = %d\n", c);
  10. c -= a; // c is 5
  11. printf("c = %d\n", c);
  12. c *= a; // c is 25
  13. printf("c = %d\n", c);
  14. c /= a; // c is 5
  15. printf("c = %d\n", c);
  16. c %= a; // c = 0
  17. printf("c = %d\n", c);
  18. return 0;
  19. }
Output
c = 5 
c = 10 
c = 5 
c = 25 
c = 5 
c = 0

C Relational Operators

A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators

 c programming
c programming language

 

  1. // Working of relational operators
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int a = 5, b = 5, c = 10;
  6. printf("%d == %d is %d \n", a, b, a == b);
  7. printf("%d == %d is %d \n", a, c, a == c);
  8. printf("%d > %d is %d \n", a, b, a > b);
  9. printf("%d > %d is %d \n", a, c, a > c);
  10. printf("%d < %d is %d \n", a, b, a < b);
  11. printf("%d < %d is %d \n", a, c, a < c);
  12. printf("%d != %d is %d \n", a, b, a != b);
  13. printf("%d != %d is %d \n", a, c, a != c);
  14. printf("%d >= %d is %d \n", a, b, a >= b);
  15. printf("%d >= %d is %d \n", a, c, a >= c);
  16. printf("%d <= %d is %d \n", a, b, a <= b);
  17. printf("%d <= %d is %d \n", a, c, a <= c);
  18. return 0;
  19. }
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1 

C Logical Operators

An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming.
Operator Meaning Example
&& Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0.
|| Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1.
! Logical NOT. True only if the operand is 0 If c = 5 then, expression !(c==5) equals to 0.

Example 5: Logical Operators

  1. // Working of logical operators
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int a = 5, b = 5, c = 10, result;
  6. result = (a == b) && (c > b);
  7. printf("(a == b) && (c > b) is %d \n", result);
  8. result = (a == b) && (c < b);
  9. printf("(a == b) && (c < b) is %d \n", result);
  10. result = (a == b) || (c < b);
  11. printf("(a == b) || (c < b) is %d \n", result);
  12. result = (a != b) || (c < b);
  13. printf("(a != b) || (c < b) is %d \n", result);
  14. result = !(a != b);
  15. printf("!(a == b) is %d \n", result);
  16. result = !(a == b);
  17. printf("!(a == b) is %d \n", result);
  18. return 0;
  19. }
Output
(a == b) && (c > b) is 1 
(a == b) && (c < b) is 0 
(a == b) || (c < b) is 1 
(a != b) || (c < b) is 0 
!(a != b) is 1 
!(a == b) is 0 
Explanation of logical operator program
  • (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
  • (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
  • (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
  • (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
  • !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
  • !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Visit bitwise operator in C to learn more.

Other Operators


Comma Operator

Comma operators are used to link related expressions together. For example:
  1. int a, c = 5, d;

The sizeof operator

The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).

Example 6: sizeof Operator

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int a;
  5. float b;
  6. double c;
  7. char d;
  8. printf("Size of int=%lu bytes\n",sizeof(a));
  9. printf("Size of float=%lu bytes\n",sizeof(b));
  10. printf("Size of double=%lu bytes\n",sizeof(c));
  11. printf("Size of char=%lu byte\n",sizeof(d));
  12. return 0;
  13. }
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

Other operators such as ternary operator ?:, reference operator &, dereference operator * and member selection operator -> will be discussed in later tutorials.








Flow Control

  • if...else Statement
  • C for Loop
  • C while Loop
  • break and continue
  • switch Statement
  • C go to Statement
  • Decision Examples   
  

C if...else Statement

In this tutorial, you will learn about if statement (including if...else and nested if..else) in C programming. This allows you to perform different action based on different test condition.

C if Statement

The syntax of the if statement in C programming is:
  1. if (test expression)
  2. {
  3. // statements to be executed if the test expression is true
  4. }

How if statement works?

The if statement evaluates the test expression inside the parenthesis ().
  • If the test expression is evaluated to true, statements inside the body of if are executed.
  • If the test expression is evaluated to false, statements inside the body of if are not executed.
How if statement works in C programming?
c language programming

To learn more about when test expression is evaluated to true (non-zero value) and false (0), check relational and logical operators.

Example 1: if statement

  1. // Program to display a number if it is negative
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int number;
  6. printf("Enter an integer: ");
  7. scanf("%d", &number);
  8. // true if number is less than 0
  9. if (number < 0)
  10. {
  11. printf("You entered %d.\n", number);
  12. }
  13. printf("The if statement is easy.");
  14. return 0;
  15. }
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
When the user enters -2, the test expression number<0 is evaluated to true. Hence, You entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
The if statement is easy.
When the user enters 5, the test expression number<0 is evaluated to false and the statement inside the body of if is not executed

C if...else Statement

The if statement may have an optional else block. The syntax of the if..else statement is:
  1. if (test expression) {
  2. // statements to be executed if the test expression is true
  3. }
  4. else {
  5. // statements to be executed if the test expression is false
  6. }

How if...else statement works?

If the test expression is evaluated to true,
  • statements inside the body of if are executed.
  • statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
  • statements inside the body of else are executed
  • statements inside the body of if are skipped from execution.
How if...else statement works in C programming?

Example 2: if...else statement

  1. // Check whether an integer is odd or even
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int number;
  6. printf("Enter an integer: ");
  7. scanf("%d", &number);
  8. // True if the remainder is 0
  9. if (number%2 == 0)
  10. {
  11. printf("%d is an even integer.",number);
  12. }
  13. else
  14. {
  15. printf("%d is an odd integer.",number);
  16. }
  17. return 0;
  18. }
Output
Enter an integer: 7
7 is an odd integer.
When the user enters 7, the test expression number%2==0 is evaluated to false. Hence, the statement inside the body of else is executed.

C if...else Ladder

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test expressions and execute different statements.

Syntax of nested if...else statement.

  1. if (test expression1)
  2. {
  3. // statement(s)
  4. }
  5. else if(test expression2)
  6. {
  7. // statement(s)
  8. }
  9. else if (test expression3)
  10. {
  11. // statement(s)
  12. }
  13. .
  14. .
  15. else
  16. {
  17. // statement(s)
  18. }

Example 3: C if...else Ladder

  1. // Program to relate two integers using =, > or < symbol
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int number1, number2;
  6. printf("Enter two integers: ");
  7. scanf("%d %d", &number1, &number2);
  8. //checks if the two integers are equal.
  9. if(number1 == number2)
  10. {
  11. printf("Result: %d = %d",number1,number2);
  12. }
  13. //checks if number1 is greater than number2.
  14. else if (number1 > number2)
  15. {
  16. printf("Result: %d > %d", number1, number2);
  17. }
  18. //checks if both test expressions are false
  19. else
  20. {
  21. printf("Result: %d < %d",number1, number2);
  22. }
  23. return 0;
  24. }
Output
Enter two integers: 12
23
Result: 12 < 23

Nested if...else

It is possible to include an if...else statement inside the body of another if...else statement.

Example 4: Nested if...else

This program given below relates two integers using either <, > and = similar to the if...else ladder's example. However, we will use a nested if...else statement to solve this problem.
  1. #include <stdio.h>
  2. int main()
  3. {
  4. int number1, number2;
  5. printf("Enter two integers: ");
  6. scanf("%d %d", &number1, &number2);
  7. if (number1 >= number2)
  8. {
  9. if (number1 == number2)
  10. {
  11. printf("Result: %d = %d",number1,number2);
  12. }
  13. else
  14. {
  15. printf("Result: %d > %d", number1, number2);
  16. }
  17. }
  18. else
  19. {
  20. printf("Result: %d < %d",number1, number2);
  21. }
  22. return 0;
  23. }

If the body of an if...else statement has only one statement, you do not need to use brackets {}.
For example, this code
  1. if (a > b) {
  2. print("Hello");
  3. }
  4. print("Hi");
is equivalent to
  1. if (a > b)
  2. print("Hello");
  3. print("Hi"); 
  4.  
     

C for Loop

Loops are used in programming to execute a block of code repeatedly until a specified condition is met. In this tutorial, you will learn to create for loop in C programming.
C programming has three types of loops:
  1. for loop
  2. while loop
  3. do...while loop
We will learn about for loop in this tutorial. In the next tutorial, we will learn about while and do...while loop.

for Loop

The syntax of the for loop is:
  1. for (initializationStatement; testExpression; updateStatement)
  2. {
  3. // statements inside the body of loop
  4. }

How for loop works?

  • The initialization statement is executed only once.
  • Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is terminated.
  • However, if the test expression is evaluated to true, statements inside the body of for loop are executed, and the update expression is updated.
  • Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the loop terminates.
To learn more about test expression (when the test expression is evaluated to true and false), check out relational and logical operators.

for loop Flowchart

Flowchart of for loop in C programming
C language


Example 1: for loop

  1. # Print numbers from 1 to 10
  2. #include <stdio.h>
  3. int main() {
  4. int i;
  5. for (i = 1; i < 11; ++i)
  6. {
  7. printf("%d ", i);
  8. }
  9. return 0;
  10. }
Output
1 2 3 4 5 6 7 8 9 10
  1. i is initialized to 1.
  2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body of for loop is executed. This will print the 1 (value of i) on the screen.
  3. The update statement ++i is executed. Now, the value of i will be 2. Again, the test expression is evaluated to true, and the body of for loop is executed. This will print 2 (value of i) on the screen.
  4. Again, the update statement ++i is executed and the test expression i < 11 is evaluated. This process goes on until i becomes 11.
  5. When i becomes 11, i < 11 will be false, and the for loop terminates.

Example 2: for loop

  1. // Program to calculate the sum of first n natural numbers
  2. // Positive integers 1,2,3...n are known as natural numbers
  3. #include <stdio.h>
  4. int main()
  5. {
  6. int num, count, sum = 0;
  7. printf("Enter a positive integer: ");
  8. scanf("%d", &num);
  9. // for loop terminates when num is less than count
  10. for(count = 1; count <= num; ++count)
  11. {
  12. sum += count;
  13. }
  14. printf("Sum = %d", sum);
  15. return 0;
  16. }
Output
Enter a positive integer: 10
Sum = 55
The value entered by the user is stored in the variable num. Suppose, the user entered 10.
The count is initialized to 1 and the test expression is evaluated. Since the test expression count<=num (1 less than or equal to 10) is true, the body of for loop is executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and the count will equal to 2. Again, the test expression is evaluated. Since 2 is also less than 10, the test expression is evaluated to true and the body of for loop is executed. Now, the sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false), and the loop terminates.
Then, the value of sum is printed on the screen.

We will learn about while loop and do...while loop in the next tutorial.
     

C while and do...while Loop

Loops are used in programming to execute a block of code repeatedly until a specified condition is met. In this tutorial, you will learn to create while and do...while loop in C programming.
C programming has three types of loops.
  1. for loop
  2. while loop
  3. do...while loop
In the previous tutorial, we learned about for loop. In this tutorial, we will learn about while and do..while loop.

while loop

The syntax of the while loop is:
  1. while (testExpression)
  2. {
  3. // statements inside the body of the loop
  4. }

How while loop works?

  • The while loop evaluates the test expression inside the parenthesis ().
  • If the test expression is true, statements inside the body of while loop are executed. Then, the test expression is evaluated again.
  • The process goes on until the test expression is evaluated to false.
  • If the test expression is false, the loop terminates (ends).
To learn more about test expression (when the test expression is evaluated to true and false), check out relational and logical operators.

Flowchart of while loop

flowchart of while loop in C programming
c language


Example 1: while loop

  1. // Print numbers from 1 to 5
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int i = 1;
  6. while (i <= 5)
  7. {
  8. printf("%d\n", i);
  9. ++i;
  10. }
  11. return 0;
  12. }
Output
1
2
3
4
5
Here, we have initialized i to 1.
  1. When i is 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2.
  2. Now, i is 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3.
  3. This process goes on until i becomes 6. When i is 6, the test expression i <= 5 will be false and the loop terminates.

do...while loop

The do..while loop is similar to the while loop with one important difference. The body of do...while loop is executed at least once. Only then, the test expression is evaluated.
The syntax of the do...while loop is:
  1. do
  2. {
  3. // statements inside the body of the loop
  4. }
  5. while (testExpression);

How do...while loop works?

  • The body of do...while loop is executed once. Only then, the test expression is evaluated.
  • If the test expression is true, the body of the loop is executed again and the test expression is evaluated.
  • This process goes on until the test expression becomes false.
  • If the test expression is false, the loop ends.

Flowchart of do...while Loop

do while loop flowchart in C programming

Example 2: do...while loop

  1. // Program to add numbers until the user enters zero
  2. #include <stdio.h>
  3. int main()
  4. {
  5. double number, sum = 0;
  6. // the body of the loop is executed at least once
  7. do
  8. {
  9. printf("Enter a number: ");
  10. scanf("%lf", &number);
  11. sum += number;
  12. }
  13. while(number != 0.0);
  14. printf("Sum = %.2lf",sum);
  15. return 0;
  16. }
Output
Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70
 
 

C break and continue

We learned about loops in previous tutorials. In this tutorial, we will learn to use break and continue statements with the help of examples.

C break

The break statement ends the loop immediately when it is encountered. Its syntax is:
  1. break;
The break statement is almost always used with if...else statement inside the loop.

How break statement works?

Working of break statement

Example 1: break statement

  1. // Program to calculate the sum of a maximum of 10 numbers
  2. // If a negative number is entered, the loop terminates
  3. # include <stdio.h>
  4. int main()
  5. {
  6. int i;
  7. double number, sum = 0.0;
  8. for(i=1; i <= 10; ++i)
  9. {
  10. printf("Enter a n%d: ",i);
  11. scanf("%lf",&number);
  12. // If the user enters a negative number, the loop ends
  13. if(number < 0.0)
  14. {
  15. break;
  16. }
  17. sum += number; // sum = sum + number;
  18. }
  19. printf("Sum = %.2lf",sum);
  20. return 0;
  21. }
Output
Enter a n1: 2.4
Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30
This program calculates the sum of a maximum of 10 numbers. Why a maximum of 10 numbers? It's because if the user enters a negative number, the break statement is executed. This will end the for loop, and the sum is displayed.
In C, break is also used with the switch statement. This will be discussed in the next tutorial.

C continue

The continue statement skips the current iteration of the loop and continues with the next iteration. Its syntax is:
  1. continue;
The continue statement is almost always used with the if...else statement.

How continue statement works?

Working of continue statement in C programming

Example 2: continue statement

  1. // Program to calculate the sum of a maximum of 10 numbers
  2. // Negative numbers are skipped from the calculation
  3. # include <stdio.h>
  4. int main()
  5. {
  6. int i;
  7. double number, sum = 0.0;
  8. for(i=1; i <= 10; ++i)
  9. {
  10. printf("Enter a n%d: ",i);
  11. scanf("%lf",&number);
  12. if(number < 0.0)
  13. {
  14. continue;
  15. }
  16. sum += number; // sum = sum + number;
  17. }
  18. printf("Sum = %.2lf",sum);
  19. return 0;
  20. }
Output
Enter a n1: 1.1
Enter a n2: 2.2
Enter a n3: 5.5
Enter a n4: 4.4
Enter a n5: -3.4
Enter a n6: -45.5
Enter a n7: 34.5
Enter a n8: -4.2
Enter a n9: -1000
Enter a n10: 12
Sum = 59.70
In this program, when the user enters a positive number, the sum is calculated using sum += number; statement.
When the user enters a negative number, the continue statement is executed and it skips the negative number from the calculation.
 
 

C switch Statement

In this tutorial, you will learn to create switch statement in C programming.
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write.

Syntax of switch...case

  1. switch (expression)
  2. ​{
  3. case constant1:
  4. // statements
  5. break;
  6. case constant2:
  7. // statements
  8. break;
  9. .
  10. .
  11. .
  12. default:
  13. // default statements
  14. }
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.
  • If there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to constant2, statements after case constant2: are executed until break is encountered.
  • If there is no match, the default statements are executed.
If we do not use break, all statements after the matching label are executed.
The default clause inside the switch statement is optional.

switch Statement Flowchart

Flowchart of switch statement

Example: Simple Calculator

  1. // Program to create a simple calculator
  2. #include <stdio.h>
  3. int main() {
  4. char operator;
  5. double n1, n2;
  6. printf("Enter an operator (+, -, *, /): ");
  7. scanf("%c", &operator);
  8. printf("Enter two operands: ");
  9. scanf("%lf %lf",&n1, &n2);
  10. switch(operator)
  11. {
  12. case '+':
  13. printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
  14. break;
  15. case '-':
  16. printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
  17. break;
  18. case '*':
  19. printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
  20. break;
  21. case '/':
  22. printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
  23. break;
  24. // operator doesn't match any case constant +, -, *, /
  25. default:
  26. printf("Error! operator is not correct");
  27. }
  28. return 0;
  29. }
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 the operator variable. And, two operands 32.5 and 12.4 are stored in variables n1 and n2 respectively.
Since the operator is -, the control of the program jumps to
printf("%.1lf / %.1lf = %.1lf", n1, n2, n1/n2);
Finally, the break statement terminates the switch statement.
 
 

C go to Statement

In this tutorial, you will learn to create goto statement in C programming. Also, you will learn when to use a goto statement and when not to use it.
The goto statement allows us to transfer control of the program to the specified label.

Syntax of goto Statement

  1. goto label;
  2. ... .. ...
  3. ... .. ...
  4. label:
  5. statement;
The label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.
How goto statement works?

Example: goto Statement

  1. // Program to calculate the sum and average of positive numbers
  2. // If the user enters a negative number, the sum and average are displayed.
  3. # include <stdio.h>
  4. int main()
  5. {
  6. const int maxInput = 5;
  7. int i;
  8. double number, average, sum=0.0;
  9. for(i=1; i<=maxInput; ++i)
  10. {
  11. printf("%d. Enter a number: ", i);
  12. scanf("%lf",&number);
  13. if(number < 0.0)
  14. goto jump;
  15. sum += number;
  16. }
  17. jump:
  18. average=sum/(i-1);
  19. printf("Sum = %.2f\n", sum);
  20. printf("Average = %.2f", average);
  21. return 0;
  22. }
Output
1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60

Reasons to avoid goto

The use of goto statement may lead to code that is buggy and hard to follow. For example,
  1. one:
  2. for (i = 0; i < number; ++i)
  3. {
  4. test += i;
  5. goto two;
  6. }
  7. two:
  8. if (test > 5) {
  9. goto three;
  10. }
  11. ... .. ...
Also, the goto statement allows you to do bad stuff such as jump out of the scope.
That being said, goto can be useful sometimes. For example: to break from nested loops.

Should you use goto?

If you think the use of goto statement simplifies your program, you can use it. That being said, goto is rarely useful and you can create any C program without using goto altogether.
Here's a quote from Bjarne Stroustrup, creator of C++, "The fact that 'goto' can do anything is exactly why we don't use it".


C Control Flow Examples

In this article, you will find a list of C programs to sharpen your knowledge of decision-making statements and loops.
To understand all the examples on this page, you should know about the following topics:





























               

Comments