C Programming

C Programming

Contents

Intoduction to programming for biginners

"C++ and Java, say, are presumably growing faster than plain C, but I bet C will still be around."

What is C Language?

C is a general purpose case sensitive, free form, procedural and high level programming language. C programming language was developed by an American computer scientist Dennis Ritchie between 1969 and 1973 at Bell Labs. It was created to develop the UNIX Operating System.

C programming language was designed to be compiled using a relatively straightforward compiler, to provide low-level access to memory and to provide language constructs that map efficiently to machine instructions, and to require minimal run-time support. Despite its low-level capabilities, the language was designed to encourage cross-platform programming.

Practical usage of C Programming

Before we get into the main topic we should know what are the practical usage of C Programming language? Why we will learn this language? Well I’ll suggest to learn the C programming before you get into any other programming languages like C++, JAVA, etc. Anyway, the major usage of C Programming are:

  1. Operating Systems (like UNIX)
  2. Language Compilers
  3. Assemblers
  4. Text Editors
  5. Print Spoolers
  6. Network Drivers
  7. Modern Programs
  8. Data Bases
  9. Language Interpreters

C can also be used for website programming using CGI(Common Gateway Interface) as a “gateway” for information between the Web application, the server, and the browser.

Features of C Programming

features of C Programming

  1. C is a simple and very efficient programming language.
  2. C is a robust language with rich set of built-in functions and operators that can be used to write any complex program.
  3. C is highly portable this means that programs once written can be run on another machines with little or no modification.
  4. A C program is basically a collection of functions that are supported by C library. We can also create our own function and add it to C library.

Setup an IDE to run C program

As we know that C is a high level programming language, so we need an IDE(Integrated Development Environment) to run a written C program. There are a huge number of IDEs available on internet for free. Just download and install it in your computer.

Some of the popular IDEs are:

  1. Turbo C++
  2. Dev C++
  3. Code:Blocks

Just download and install one of them and get start to learn your next steps of programming.

Your first C program

  #include  //header file

  int main()  //main function

  {

           printf("Hello World");

           return 0;

  }

OUTPUT: Hello World!

A C program basically consists of the following parts −

  • Preprocessor Directives
  • Main functions
  • Variables
  • Functions
  • Statements & Expressions
  • Comments

Let us take a look at the various parts of the above program −

  • The first line of the program #include <stdio.h> is a preprocessor directive, which tells the compiler to include stdio.h(Standard input/output header) file.

  • The next line int main() is the main function where the program execution begins.

  • The next line printf(“Hello World!”) is another function available in C standard header file which causes the output “Hello, World!”.

  • The next line return 0; terminates the main() function and returns the value 0.

Basic Syntax of C Programming

We are already familiar with the basic syntax of a simple C program when we built the “Hello World” program in C. Generally C language syntax specify the rules for sequence of characters to be written in C language.

The basic syntax rules of C language are:

  • We know that C is a case sensitive language so all the C instructions must be written in lower case letter.
  • All C statement must end with a semicolon.
  • Whitespace is used in C to describe blanks and tabs and required between keywords and identifiers.

Keywords in C language

Keywords are those special and preserved words that have some specific meaning in the C programming. As the keyword denote some specific meaning so they cannot be used as a variable name in the program.

There are 32 keywords in the C language. They are:

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

double

 

Identifiers in C language

An identifier is a name that the user gives to a particular variable, function or any other user defined item to identify them in the program.

There are some rules to use identifiers in the C program:

  1. C language does not allow punctuation characters such as @, $, and % within identifiers.
  2. An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and underscore sign.
  3. C is a case sensitive programming language. Thus, Programming and programming are two different identifiers in C.
  4. We cannot have reserved keywords as identifiers.
  5. Special characters like , . ; @ etc. are not allowed to be used as identifiers.

Data Types in C

We use variables or functions in our program. But we also have to define the data type of the variable or function. The data type of a variable defines which type of data the variable will contain or the function will return.

The C language supports two different kinds of data type:

  1. Primary Data Type
  2. Derived Data Type

Primary Data Types are the general purpose arithmetic type data types in C. They are divided into four different types: Integer(int) ,Floating Point(float), Character(char), void.

Derived Data Types are those data types that are derived from the primary data types like: Array, Pointer, Structure, Union.

Integer type:

Integers are used to store whole numbers.

Size and range of Integer type on 16-bit machine:

Data TypeSize(bytes)Range
int or signed int2-32,768 to 32767
unsigned int20 to 65535
short int or signed short int1-128 to 127
unsigned short int10 to 255
long int or signed long int4-2,147,483,648 to 2,147,483,647
unsigned long int40 to 4,294,967,295

Floating point type:

Floating types are used to store real numbers.

Size and range of Integer type on 16-bit machine

Data TypeSize(bytes)Range
Float43.4E-38 to 3.4E+38
double81.7E-308 to 1.7E+308
long double103.4E-4932 to 1.1E+4932

Character type:

Character types are used to store characters value.

Size and range of Integer type on 16-bit machine

TypeSize(bytes)Range
char or signed char1-128 to 127
unsigned char10 to 255

void type:

void means no value. This is usually used to specify the type of functions which returns nothing. We will get acquainted to this datatype as we start learning more advanced topics in C language, like functions, pointers etc.

Operators in C language

An operator is a symbol(+, -, x, etc.) that tells the compiler to perform some specific mathematical operation within some particular variable(s).

C language supports a wide range of operators to perform various mathematical operations:

1. Arithmetic Operators
2. Conditional Operators
3. Relational Operators
4. Assignment Operators
5. Logical Operators
6. Increment and Decrement Operators
7. Bitwise Operators
8. Special Operators

1. Arithmetic operators

Arithmetic operators are those operators that are used to perform various arithmetic operations like sum, minus, multiplication, division. The arithmetic operators that are supported by C language are:

OperatorOperation
+adds two operands
subtract second operands from first
*multiply two operand
/divide numerator by denominator
%remainder of division
  #include<stdio.h>
  int main()
  {
  int numb1, num2, sum,  sub, mul, div, mod;
  scanf (“%d %d”, &num1, &num2);
  sum = num1+num2;    //addition of numbers and storing in sum.
  printf(“\n Thu sum is = %d”, sum);
  sub = num1-num2;     //subtraction of numbers and storing in sub.
  printf(“\n Thu difference is = %d”, sub);
  mul = num1*num2;    //multiplication of numbers and storing in mul.
  printf(“\n Thu product is = %d”, mul);
  div = num1/num2;    //division of numbers and storing in div.
  printf(“\n Thu division is = %d”, div);
  mod = num1%num2;   //modulus of numbers and storing in mod.
  printf(“\n Thu modulus is = %d”, mod);

  return 0;
  }

2. Conditional operator

The conditional operators are used to check whether a defined condition is true or false.

The syntax of a conditional operator is :

expression 1 ? expression 2: expression 3

  #include<stdio.h>
  void main()
  {
  int i,j,larger;
  printf (“Input 2 integers : ”);
  scanf(“%d %d”,&i, &j);
  larger = i > j ? i : j;   //evaluation using ternary operator
  printf(“The largest of two numbers is %d \n”, larger); 
  }

3. Relational operators

The relational operator is used to check the relationship between two operands. There are various relational operators in C language:

OperatorOperation
==Check if two operand are equal
!=Check if two operand are not equal.
>Check if operand on the left is greater than operand on the right
<Check operand on the left is smaller than right operand
>=check left operand is greater than or equal to right operand
<=Check if operand on left is smaller than or equal to right operand
#include <stdio.h>
int main()
{
    int a = 5, b = 5, c = 10;

    printf("%d == %d = %d \n", a, b, a == b); // true
    printf("%d == %d = %d \n", a, c, a == c); // false
    printf("%d > %d = %d \n", a, b, a > b); //false
    printf("%d > %d = %d \n", a, c, a > c); //false
    printf("%d < %d = %d \n", a, b, a < b); //false
    printf("%d < %d = %d \n", a, c, a < c); //true
    printf("%d != %d = %d \n", a, b, a != b); //false
    printf("%d != %d = %d \n", a, c, a != c); //true
    printf("%d >= %d = %d \n", a, b, a >= b); //true
    printf("%d >= %d = %d \n", a, c, a >= c); //false
    printf("%d <= %d = %d \n", a, b, a <= b); //true
    printf("%d <= %d = %d \n", a, c, a <= c); //true
    return 0;
}

4. Assignment Operators

The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression.

OperatorOperation
=assigns values from right side operands to left side operand
+=adds right operand to the left operand and assign the result to left
-=subtracts right operand from the left operand and assign the result to left operand
*=mutiply left operand with the right operand and assign the result to left operand
/=divides left operand with the right operand and assign the result to left operand
%=calculate modulus using two operands and assign the result to left operand

5. Logical operators

C language has the following logical operators, they compare or evaluate logical and relational expressions.

OperatorOperation
&&Logical AND
||Logical OR
!Logical NOT

Logical AND (&&)

This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true.

Example

a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.

Logical OR (||)

The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true.

Example

a < m || a < n

The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.

Logical NOT (!)

The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression.

For example

! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y

6. Increment and Decrement Operator

Increment and decrement operator is used to increment and decrement the value of a particular variable respectively.

++Increment operator – increases integer value by one
Decrement operator – decreases integer value by one

7. Bitwise operators

C has a distinction of supporting special operators known as bitwise operators for manipulation data at bit level. A bitwise operator operates on each bit of data. Those operators are used for testing, complementing or shifting bits to the right on left. Bitwise operators may not be applied to a float or double.

OperatorOperation
&Bitwise AND
|Bitwise OR
^Bitwise exclusive OR
<<left shift
>>right shift

8. Special operator

C supports some special operators of interest such as comma operator, size of operator, pointer operators (& and *) and member selection operators (. and ->).

OperatorOperation
sizeofReturns the size of an variable
&Returns the address of an variable
*Pointer to a variable

Decision making in C

Decision making defines the order of execution of a program based on some specific conditions. A block of code will be executed if the specified condition is true else it will not be executed. C language supports decision making by the following statements:

  • IF Statement
  • IF-ELSE Statement
  • NESTED IF Statement
  • SWITCH-CASE Statement

Decision making with IF Statement:

It is the basic form where the if statement evaluate a test condition and direct program execution depending on the result of that evaluation.

Syntax:

            If (Expression)

            {

            Statement 1;

            Statement 2;

            }

Where a statement may consist of a single statement, a compound statement or nothing as an empty statement. The Expression also referred so as test condition must be enclosed in parenthesis, which cause the expression to be evaluated first, if it evaluate to true (a non zero value), then the statement associated with it will be executed otherwise ignored and the control will pass to the next statement.

Example of IF Statement:

#include <stdio.h>
void main( )
{
    int a, b;
    a = 41;
    b = 29;
    if (a > b )
    {
        printf("a is greater than b");
    }
}

Decision making with IF-ELSE Statement:

An if statement may also optionally contain a second statement, the “else clause,” which is to be executed if the condition is not met. Here is an example:

Example of IF-ELSE Statement:

#include <stdio.h>

void main( )
{
    int a, b;
    a = 26;
    b = 20;
    if (a > b )
    {
        printf("a is greater than y");
    }
    else
    {
        printf("b is greater than x");
    }
}

Decision making with NESTED-IF Statement:

It’s also possible to nest one if statement inside another. (For that matter, it’s in general possible to nest any kind of statement or control flow construct within another.) For example:

Example of NESTED-IF Statement:

#include <stdio.h>
void main( )
{
    int a, b, c;
    printf("Enter three numbers");
    scanf("%d %d %d",&a, &b, &c);
    if(a > b)
    { 
        if(a > c)
        {
            printf("a is the largest");
        }
        else 
        {
            printf("c is the largest");
        }
    }
    else
    {
        if(b > c)
        {
            printf("b is the largest");
        }
        else
        {
            printf("c is the greatest");
        }
    }
} 

Decision making with SWITCH-CASE Statement:

This is another form of the multi way decision. It is well structured, but can only be used in certain cases where;

  • Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (int, long, short or char).
  • Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases.

Example of SWITCH Statement:

#include<stdio.h>
void main( )
{
    int a, b, c, choice;
    while(choice != 3)
    {
        printf("\n 1. Press 1 for addition");
        printf("\n 2. Press 2 for subtraction");
        printf("\n Enter your choice");
        scanf("%d", &choice);
        switch(choice)
        {
            case 1:
                printf("Enter 2 numbers");
                scanf("%d%d", &a, &b);
                c = a + b;
                printf("%d", c);
                break;
            case 2:
                printf("Enter 2 numbers");
                scanf("%d%d", &a, &b);
                c = a - b;
                printf("%d", c);
                break;
            default:
                printf("you have passed a wrong key");
                printf("\n press any key to continue");
        }
    } 
} 

Loops in C language

Looping is a way by which we can execute any some set of statements more than one times continuously .In c there are mainly three types of loops are use :

  • while Loop
  • do while Loop
  • For Loop

How it is work…


cfg

While Loop:

Loops generally consist of two parts: one or more control expressions which (not surprisingly) control the execution of the loop, and the body, which is the statement or set of statements which is executed over and over.While loop is entry control loop.

The general syntax of a while loop is:

variable initialization;
while(condition)
{
    statements;
    variable increment or decrement; 
}

Example of while loop:

#include<stdio.h>

void main( )
{
    int x;
    x = 1;
    while(x <= 100)
    {
        printf("%d\t", x);
        x++;
    }
}

For Loop:

For loop executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. A For loop contains three parts: initialization, condition check and increment/decrement.

The general syntax of For Loop:

for(initialization; condition; increment/decrement)
{
    statement-block;
}

Example of For Loop:

#include<stdio.h>
void main( )
{
    int x;
    for(x = 1; x <= 10; x++)
    {
        printf("%d\t", x);
    }
}

Do-While Loop:

This is very similar to the while loop except that the test occurs at the end of the loop body. This guarantees that the loop is executed at least once before continuing. Such a setup is frequently used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable.

The general syntax of Do-While loop:

do
{
    .....
    .....
}
while(condition)

Example of Do-While Loop:

#include<stdio.h>
void main()
{
    int a, i;
    a = 5;
    i = 1;
    do
    {
        printf("%d\t", a*i);
        i++;
    } 
    while(i <= 10);
}

Break and Continue Statement in C Programming

Break Statement:

We have already met break in the discussion of the switch statement. It is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch.

With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition.

Example of Break Statement:

# include <stdio.h>
int main()
{
    int i;
    double number, sum = 0.0;

    for(i=1; i <= 10; ++i)
    {
        printf("Enter n%d: ",i);
        scanf("%lf",&number);

        // If user enters negative number, loop is terminated
        if(number < 0.0)
        {
            break;
        }

        sum += number; // sum = sum + number;
    }

    printf("Sum = %f",sum);
    
    return 0;
}

Continue Statement:

This is similar to break but is encountered less frequently. It only works within loops where its effect is to force an immediate jump to the loop control statement.

  • In a while loop, jump to the test statement.
  • In a do while loop, jump to the test statement.
  • In a for loop, jump to the test, and perform the iteration.

Like a break, continue should be protected by an if statement. You are unlikely to use it very often.

Example of Continue Statement:

# include <stdio.h>
int main()
{
    int i;
    double number, sum = 0.0;

    for(i=1; i <= 10; ++i)
    {
        printf("Enter a n%d: ",i);
        scanf("%lf",&number);

        // If user enters negative number, loop is terminated
        if(number < 0.0)
        {
            continue;
        }

        sum += number; // sum = sum + number;
    }

    printf("Sum = %.2lf",sum);
    
    return 0;
}

Storage Classes in C Programming

A storage class defines the visibility and lifetime of a particular variable in the program.

Visibility or scope of a variable defines where the value of the variable would be available inside a program.

And lifetime of a variable defines how long will that variable exist in the program.

We have four storage classes in C language:

  1. Automatic (auto) storage class.
  2. External (extern) storage class.
  3. Register storage class.
  4. Static storage class.

Automatic (auto) storage class:

A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automatically when the function’s execution is completed. Automatic variables can also be called local variables because they are local to a function. By default they are assigned garbage value by the compiler.

Scope: Local to the function block inside which they are defined.

Default Initial Value: Any random value i.e garbage value.

Lifetime: Till the end of the function/method block where the variable is defined.

Example:

#include<stdio.h>    
void main()
{
    int a;
    // or 
    auto int a;
}

External (extern) storage class:

A variable that is declared outside any function is a Global Variable. Global variables remain available throughout the program execution. By default, initial value of the Global variable is 0(zero). One important thing to remember about global variable is that their values can be changed by any function in the program.

Scope: Global i.e everywhere in the program. These variables are not bound by any function, they are available everywhere.

Default initial value: 0(zero).

Lifetime: Till the program doesn’t finish its execution, you can access global variables.

Example:

#include<stdio.h>
int num;     // global variable
void main()
{
    num = 20;
    printf("In main function.value is %d\n", num);
    fun();     
    func();    
fun()
{
    num = 50;
    printf("In function func.value is %d", num);
}
func()
{
    printf("\nIn function func.value is %d", num);
}

Register Storage Class:

Register variables inform the compiler to store the variable in CPU register instead of memory. Register variables have faster accessibility than a normal variable. Generally, the frequently used variables are kept in registers. But only a few variables can be placed inside registers. One application of register storage class can be in using loops, where the variable gets used a number of times in the program, in a very short span of time.

Scope: Local to the function in which it is declared.

Default initial value: Any random value i.e garbage value

Lifetime: Till the end of function/method block, in which the variable is defined.

Static Storage Class:

A static variable tells the compiler to persist/save the variable until the end of program. Instead of creating and destroying a variable every time when it comes into and goes out of scope, static variable is initialized only once and remains into existence till the end of the program. A static variable can either be internal or external depending upon the place of declaration.

Scope: Local to the block in which the variable is defined

Default initial value: 0(Zero).

Lifetime: Till the whole program doesn’t finish its execution.

Example:

#include<stdio.h>

void ex();   
 
int main()
{
    ex();
    ex();
    ex();
}
void ex()
{
    static int a = 0;       //a static variable
    a = a + 5;
    printf("%d\n",a);
}
Video Tutorial:

7
Leave a Reply

avatar
6 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
7 Comment authors
Rosalba VialeCortneyhttps://www.androidflap.com/best-pdf-to-word-converter/Talkhelper-pdf-converter-review/Www.Silentkeynote.Comwww.appleiphonelawsuit.com Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Casellet.Com
Guest

I like the article

www.appleiphonelawsuit.com
Guest

Thank you for the excellent post

Www.Silentkeynote.Com
Guest

This is actually useful, thanks.

Cortney
Guest

Thanks to the excellent manual

Rosalba Viale
Guest

This is a impressive story. Thanks! https://bzp65.com/