Category Archives: C Tutorial

C Array

In C programming, an array is ordered collection of homogeneous elements placed in contiguous memory locations. In c, an array is a derived data type that can be used to store collection of any primitive data types such as int, char, double, float, double, etc. In order to store multiple values together in array, all the elements should be of the same data type. Array elements can be accessed individually by adding an unique index or subscript to it. Arrays are typed, thus once you declare the type of the array then you would only have elements of the same type.

An array variable is useful in c when we want to hold multiple values of single data type in single variable. Suppose, you want to store marks of 10 students then you need to declare 10 different variables to hold marks like student1_marks, student2_marks etc. But with the help of an array you can store marks of all students in single variable. Given below is a graphical representation of an array.

graphical-representation-of-array

 

Array is used to store multiple values in a single variable, instead of declaring separate variables for each value. An array is made up of a key and a value pair, and the key points to the value. Arrays may be of any variable type. In this tutorial you will learn how to declare, initialize and access array elements with the help of examples.

Types of Array In C

In this tutorial, we will learn about the various types of array in c programming. All array types provide the same basic functionality. In C programming we have the following two array types:

  • One Dimensional Array
  • Multi-dimensional array

One Dimensional Array

One dimensional array is the simplest form of arrays found in C. A one-dimensional array is a structured collection of array elements that can be accessed individually by specifying the position of an element with a single index value. Learn how to declare and initialize one dimensional array. We will also learn to access array elements in one dimensional array.

Syntax:-

General syntax to declare a one dimensional array is as follows:

Example:-

Given below is a simple example to declare a one dimensional array in c programming:

Multi-dimensional array

In c language, we are allowed to create multi-dimensional array. Multi-dimensional arrays is nothing just an array of arrays. Learn how to declare and initialize multi-dimensional array. We will also learn to access array elements in multi-dimensional array.

Syntax:-

General syntax to declare a multi-dimensional array is as follows:

Example:-

Given below is a simple example to declare a multi-dimensional array in c programming:

Declaring Array In C

There are multiple ways we can declare an array in c. An array can be declared by specifying array type, array name followed by size of the array inside square brackets []. Optionally you can initialize array in c by passing a list of initial values inside square brackets [].

Declaring Array by Specifying the Size

An array can be declared by specifying the size or the number of elements. The size of the array specifies the maximum number of elements that the array can hold. General syntax to declare an array by specifying size is as follows:

Syntax:-

An array can be declared by specifying data type, name of the array followed by size of the array inside square brackets []. The arraySize specifies the maximum number of elements that the array can hold. The type must be any valid C data type such as double, float, short etc.

Example:-

Here, we have declared an integer array marks with array size 5. The array size 5 means it can store 5 integer values

Declaring Array by Initializing Elements

An array can be initialized at the time of its declaration. Declaring array by initializing elements allows compiler to allocate array of size equal to the number of elements in array. General syntax to declare an array by initializing elements is as follows:

Syntax:-

Example:-

In the above example we have declared an array with 5 elements. Even though we have not specified the array size, the compiler will allocate memory size of 5 integer elements for it.

Declaring Array by Specifying the Size and Initializing Elements

An array can also be declared by specifying the array size and initializing array elements at the same time. In this method of array declaration, if the number of elements is less than the array size specified, then the compiler will automatically initialize rest of the elements with 0 value.

Syntax:-

Example:-

In the above example we have declared an array with array size 5, but we have initialized it with only 4 elements. Even though we have not initialized 5 elements, the compiler will initializes first 4 elements as specified by user and rest elements as 0. The above array declaration is same as given below:

Initializing Array In C

Initializing Array In C is process to declare and provide with initial element values. An array can be initialized in multiple ways same array declaration. The simplest way to initialize an array is to initialize individual array elements one by one using the index. Consider the following example.

In the above example, we have first declared the array and then later we have initialized it with individual element values. However you can also initialize the array during declaration in a single statement as follows:

Here, the number of elements inside braces { } should not exceed the array size we specified between square brackets [ ]. You can also initialize an array like this.

Here, we have not specified the array size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.

Note:- Un-initialized array always contain garbage values.

Accessing Array Elements

Accessing Array Elements in c is to refer individual array element value. It is quick and easy to access array element. Array elements can be accessed using an integer index. Array index starts from 0 and goes till size of array minus 1. The last element of the array can be accessed as arrayName[size-1]. Here, the size is equal to the number of elements in array. Suppose, you declare an array like below:

If you want to access the first element of the array, then you can access it by arr[0]. And if you want to access the second element of the array then you can do it using arr[1] and so on. Some of the important facts about array indexing is as follows:

  • The first index of the array is 0 not 1.
  • To access the last element of the array, do arrayName[size-1].

Properties of array in C

Since, array is an important concept in C language. It has many array properties associated with it. Below are some of the properties of array in C:

  • An array can store a fixed number of elements.
  • Elements of the array stored at contiguous memory locations.
  • Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1.
  • An array is a variable that can only store elements of the same data type.
  • You can access any of the array element randomly.

Advantages of array in C

Array is an important concept in C language. The arrays provides many advantages to the programmers while programming. Some of important advantages of array in c are as follows:

Code Optimization:- It helps us to write more optimized and clean code, since we can store multiple values in a single array variable at once.

Ease of Access:- It is easy to access individual or all array elements from array. It is also possible to access array elements random or in any order.

Ease of sorting:- Array makes it easy to sort elements with just a few lines of code.

Ease of traversing :- Traversing through array elements becomes easy using a loop statement.

Disadvantages of array in C

We have discussed several advantages of array in c, but it also have some disadvantages. Below are some disadvantages of array in C:

Fixed Size:- Array size has to be fixed size. This means that once array size is initialized, it can not be increased or decreased.

Homogeneous :- Since arrays are homogeneous, we can only store a single type of element in an array.

Example:-

Output:

 

C Scope Rules

The c scope rules define the region of visibility or availability for a variable, out of which we can not reference that variable. There are two main kinds of c scope rules:

  • global
  • local

Global Variable

Global variables can be accessed at any point throughout the program and can be used in any function. There is a single copy of the global variable is available. Global variables are defined outside of all the functions, usually on top of the program.

Local Variable

Variables declared inside a function or block of code are called local variables. They can be accessed only inside that function or block of code. Local variables are not available to outside functions.

Example Program:

Note:- A program can have the same name for local and global variables but the local variable overrides the value.

C Functions

As we know C Programming Language is a function-oriented programming language, functions are one of the key building blocks of any c program. The function is a way to wrap up the set of statements to perform the specific task and give it a name so that it can be invoked from anywhere in the program.

Function in C Programming language gives us a way to divide the complete program into subunits that perform a specific task for that program, this way it enhances the modular approach and increases the reusability of the program.

We pass information in a function call as its parameter and the function can either return some value to the point is where it called from or returns nothing.

Advantages of function

  • It enhances the modularity of the program.
  • It enhances the reusability.
  • It makes development easy as development can be shared in a team.
  • It reduces the coupling.
  • It reduces duplication.

Type Of Function –

  • Built-in function
  • User-defined functions

Built-In Function In C-

Built-in functions are the functions available in C Programming Language to perform some common and standard tasks, these functions are available in the C library. These libraries include the functions for file access, mathematical computations, graphics, memory management, etc.
A built-in function can be accessed simply by including the relative header file and at the point of function call by just writing the function name, followed by an optional list of arguments.

User-defined functions In C –

User-defined functions are custom functions defined by the user itself to perform a custom task that is not available as built-in, in this way users can define and write subprograms as functions to perform a task relevant to their programs.

Function Type Based on Structure of function

  • Functions with no arguments and no return value.
  • Functions with arguments but no return value.
  • Function with no arguments but with the return value.
  • Functions with arguments and with the return value.

Functions with no arguments and no return value in C

Syntax:

Functions with arguments and no return value in C

Syntax:

Function with no arguments but with return value in C

Syntax:

Functions with arguments and with return value in C

Syntax:

Structure of a Function

There are two main parts of the function. The function header and the function body.

Function Header

In the first line of the above code

It has three main parts –

  1. The name of the function
  2. The parameters of the function enclosed in parenthesis
  3. Return value type

Function Body

Whatever is written within { } in the above example is the body of the function.

Function Prototype or Function Declaration

A function prototype or declaration is made by declaring the return type of the function, the name of the function, and the data types of the parameters of the function. A function declaration is the same as the declaration of the variable. The function declaration is always terminated by the semicolon. A call to the function cannot be made unless it is declared. The general form of the declaration is:-

Syntax:

Example:

The variable’s name need not be the same as the variables of the parameter list of the function. Another method can be

The variables in the function declaration can be optional but data types are necessary.

Function in Action

Below is a program to swap two numbers with the use of the function –

Output:

 

 

 

C Loops

C Loops

In c programming loops are a fundamental concept. Loop statements allow a set of instructions to be executed repeatedly until a certain condition is fulfilled. This way loops are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. Loops are also known as iterating statements or looping statements. For example, if you want to print a message 100 times, then rather than typing the same code 100 times, you can use a loop.

Need Of Loops In C

While programming there comes a situation where we want to execute a block of code several numbers of times. In general, we will need to write the same block of code multiple times in the program. These statements will be executed in a sequential manner the first block of code executes first, followed by the second, and so on. That would take up a lot of effort which is just copy-pasting the same block of code required a number of times. This makes the process very complicated as well as lengthy and time-consuming. That’s where the loops come into play. With loops, we can group a set of instructions that we needed to be executed repeatedly. Then the loop statement does the remaining job.

Components of a loop

Generally, a loop statement has the following four components:

  • Initialization
  • Test Expression(Condition)
  • Increment/Decrement
  • Loop Body

Each of the loop components has a different purpose associated with it. We will discuss each of the above loop components for a better understanding of the working of the loops.

Initialization:- Before we enter into a loop, we must initialize its control variable. In the initialization part, the control variable is initialized with its the first value. The initialization expression is executed only once at the beginning of the loop. Here, we can initialize the variable, or we can use an already initialized variable.

Test Expression:- Test expression is executed with each iteration of the loop. The value of the test expression is used to decide whether the loop body will be executed or not. If it returns a true value then the loop body is executed for the current iteration. If it returns a false value then the loop is terminated. It must return a boolean value either true or false.

Increment/Decrement:- The Increment/Decrement expression is executed at the end of the loop. It increments or decrements the control variable value.

Loop Body:-The loop body contains the block of code to be executed repeatedly (as long as the test expression is true). The value of the test expression decides whether the code inside the loop body will be executed or not. If the value of the test expression evaluates to be true then the loop body is executed, otherwise, the loop is terminated.

Types of Loops In C

In this tutorial, we will learn about the various types of loops in c programming. While all loop types provide the same basic functionality, they differ in their syntax and condition checking time. In C programming we have the following three loop types:

 

c-types-of-loops

C for loop statement

The for loop is an entry-controlled loop that allows executing a block of code repeatedly with a fixed number of times on the basis of the test expression. The for loop is used when we want to execute a block of code known times.

Syntax:-

C while loop Statement

The while loop is an entry-controlled loop. While loop will execute a block of statements as long as a test expression or test condition is true. When the expression evaluates to false, the control will move to the next line just after the end of the loop body. In a while loop, the loop variable must be initialized before the loop begins. And the loop variable should be updated inside the while loop’s body.

Syntax:-

C do while loop Statement

The do-while loop is an exit-controlled loop. Unlike the for loop and while loop, the do-while loop evaluates its test expression after executing the statements inside the loop body. The do-while loop will first execute a block of code and then test the condition for the next iteration. It will execute the next iteration only if the condition is true. This means in the do-while loop the block of code will always execute at least once.

Syntax:-

C Decision Making Statements

In C Programming, decision-making statements allow you to make a decision, based upon the result of a test condition. The decision-making statements are also known as Conditional Statements. The if, if-else, If else if Ladder and switch statements are used as decision-making statements in c programming.

What Is Decision Making Statements

So far, we have learned that all statements in a c program are executed sequentially (top to bottom) in the order in which they are written. This occurs until there are no jump statements or loop statements. But sometimes we may need to change the order of program execution depending on some specific conditions. Here comes the need for decision-making structures that enable computers to decide on a set of statements to be executed depending upon some conditional choices. These statements are called the decision-making statements or Conditional Statements.

Decision Making Statements In C

In C programming, we have a rich set of Decision Making statements that enable computers to decide which block of code to be executed based on some conditional choices. Decision-making statement statements are also referred to as conditional statements. A Decision-making statement evaluates single or multiple test expressions which result in “TRUE” or “FALSE”. The outcome of the test expression/condition helps to determine which block of the statement(s) to execute if the condition is “TRUE” or “FALSE” otherwise. It is to be noted that the C language assumes any non-zero or non-null value as true and if zero or null, treated as false.

Types of Decision-Making Statements

In C, we have the following types of decision-making statements –

c-decision-making-statements-types

if Statement

C If statement allows a block of code to be executed only when a specified condition is true. An if statement evaluates a boolean expression followed by one or more statements. The given boolean expression results in a boolean value that can only be either true or false. If the statement is always used with a condition. The condition is evaluated first before executing any statement inside the body of If.

Syntax:-

Example:-

The above example is valid for the single statement in the body of the if statement. When there is a set of multiple statements in the body of the if statement. Then it is written inside a pair of parenthesis.

If Else Statement

The if-else statement is an extended version of the If statement. When we want to execute the same block of code if a condition is true and another block of code if a condition is false, In such a case we use an if-else statement. if the condition is true then the statements inside the body are executed otherwise else part is executed.

Syntax:-

Nested If else Statement

When there is an if statement inside another if statement then it is known as a nested if-else statement. It is used to check multiple conditions.

Syntax:-

if-else if ladder Statement

The if-else if ladder statement is used to select one of among several blocks of code to be executed. It checks the first conditional expression, and if it returns false, then it will check the second conditional expression, and so on. If all conditional expressions return false, it executes the else part.

Syntax:-

Switch Case Statement

A switch case statement is a simplified form of the nested if-else statement, it avoids long blocks of if-else if statements.

Syntax:-

C Operators

An operator is special symbol that is used to perform certain specific operation on its operand.C Programming Language have rich set of built in operators to perform various type of operations. There are operators for assignment, arithmetic functions, logical functions and many more. These operators can be used with many types of variables or constants, but some are restricted to work on specific types. Most operators are binary, meaning they take two operands. A few are unary and only take one operand.

Type of operators in C

Operators in C programming language can be broadly classified as below –

  • Assignment Operators
  • Arithmetic Operators
  • Increment and Decrement Operators
  • Relational Operators
  • Logical Operators
  • Conditional Operators
  • Bitwise Operators
  • Special Operators

C Assignment Operators

Assignment operators are used to assign value to variable, we can assign a variable value or the result of an arithmetical expression.

Example:-

Here is full list Assignment operators available in C Programming Language –

Operator Meaning Example Description
= Simple assignment operator a = b It assing value of b to a
+= Add and assign a += b It is equivalent to a = a + b
-= Subtract and assign a -= b It is equivalent to a = a- b
*= Multiply and assign a *= b It is equivalent to a = a * b
/= Divide and assign a /= b It is equivalent to a = a / b
%= Modulus and assign a %= b It is equivalent to a = a %b
<<= Right shift and assign a <<= b Right-shifted b bits (assigned to a)
>>= left shift and assign a >>= b Left-shifted b bits (assigned to a)
&= Bitwise AND and assignment a &= b a AND b (assigned to a)
^= Bitwise exclusive OR (XOR) and assignment a ^= b a XOR b (assigned to a)
|= Bitwise inclusive OR and assign a |= b a OR b (assigned to a)

C Arithmetic Operators

Arithmetic Operators are used to perform arithmetic operations. Here is full list Arithmetic operators available in C Programming Language –

Operator Meaning Example Description
+ Addition operator a + b a plus b
Minus operator a – b a minus b
* Multiply operator a * b a multiply by b
/ Division operator a / b a divided b
% Modulus operator a % b It returns remainder of a/b

Increment and Decrement Operators (post and pre)

In C Programming Language, ++ and — are know as increment and decrement operators respectively. These are unary operators it means they worls on single operand. ++ adds 1 to operand and — subtracts 1 to operand respectively.When ++ is used as prefix(like: ++i), ++i will increment the value of i and then return it but, if ++ is used as postfix(like: i++), operator will return the value of operand first and then only increment it.

Operator Example Description
++ [prefix] ++a The value of a after increment
++ [postfix] a++ The value of a before increment
— [prefix] –a The value of a after decrement
— [postfix] a– The value of a before decrement

C Relational Operators

Relational Operators are used evaluate a comparison between two operands. The result of a relational operation is a Boolean value that can only be true or false. Here is full list of Relational operators available in C Programming Language –

Operator Meaning Example Description
== Equal to a == b 1 if a equal to b; 0 otherwise
!= Not equal to a != b 1 if a not equal to b; 0 otherwise
> greater than a > b 1 if a > b; 0 otherwise
< less than a < b 1 if a < b; 0 otherwise
>= greater than or equal to a >= b 1 if a >= b; 0 otherwise
<= less than or equal to a <= b 1 if a <= b; 0 otherwise

C Logical Operators

Logical operators are used to combine expressions with relational operation using logical (AND,OR,NOT) operators. There are 3 logical operators available in C Programming Language –

Operator Meaning Example Description
&& Logical AND a && b Logical AND of a and b
|| Logical OR a || b Logical OR of a and b
! NOT !a Logical NOT of a

C Conditional operator ( ? : )

Conditional operator is also know as ‘ternary operator.’

Syntax:-

If condition is true the expression will return result1, if it is not it will return result2.

C Bitwise Operators

Bitwise operator are used to perform bit level operation over its operand.

Let A = 60; and B = 13;

Binary equivalent

A = 0011 1100

B = 0000 1101

Operator Meaning Example Description
& Binary AND (A & B) It returns 12 which is 0000 1100
| Binary OR (A | B) It returns 12 which is 0000 1100
^ Binary XOR (A ^ B) It returns 49 which is 0011 0001
~ Ones Complement (~A ) It returns -60 which is 1100 0011
<< shift left A << 2 It returns 240 which is 1111 0000
>> shift right A >> 2 It returns 15 which is 0000 1111

sizeof() Operator In C Programming

It returns the size of its operand’s data type in bytes.

Example:

This will assign the value 1 to a because char is a one-byte long data type.

Comma operator ( , ) In C

The comma operator (,) allows us to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

For example, the following code:

  • first assign the value 3 to j
  • assign j+2 to variable i.

At the end, variable i would contain the value 5 while variable j would contain value 3.

AddressOf ( & ) Operator In C

Returns the address of an variable.

Example:

Pointer ( * ) Operator In C Programming

Pointer to a variable.

Example:

Operators Precedence and Associativity In C Programming

Category Operator Associativity
Postfix () [] -> . ++ – – Left to right
Unary + – ! ~ ++ – – (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + – Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

C Storage Classes

In C Programming Language a “C Storage Classes” refers to the scope or visibility and the lifetime of the C Variable. Scope of the C Variable defines the availability of the variable in a block of the C Program, and by a lifetime of the variable means how long variable will persist in the program.

Functions of storage class

  • It tells the location of the C Variable.
  • Sets the initial or default value of the C Variable.
  • It defines the scope of the C Variable.
  • It defines the lifetime of the C Variable.

Types of C Storage Classes

C Programming Language Supports the following four types of storage classes:

  • auto
  • register
  • static
  • extern

auto-storage class

It is the default storage class for local variables. Variables with auto storage class are declared at the beginning of a code block, and memory is allocated automatically as the program execution enters a code block and frees up automatically on exiting from the code block. The scope of automatic variables is local to the block where they are declared and is not accessible directly in the other block.

Syntax:

Example :

register – Storage Class

C Variables with register storage class are the same as local variables to the code block but they are stored in the CPU register instead of computer memory. Hence it enables quick access to that variable. The maximum size of the variable is equal to register size and dependent upon the register size

Syntax:

Example:

static – Storage Class

It is the default storage class for global variables. Static storage class can be used only if we want the value of a variable to persist between different function calls. C Variable declared with static storage class will keep its value retained for different function calls.

Syntax:

Example:

extern – Storage Class

C Variable declared with extern storage class is said to be “Global Variables“, which means variables are accessible throughout the program till the end of program execution. External variables are declared outside the functions and can be invoked from and anywhere in a program. External variables can be accessed very fast as compared to any other storage class.

Syntax:

Example:

C Constants

In C Programming Language constant is an entity with a fixed value, and this value does not change throughout the execution of the program. C constants are also known as ‘Literals’. There are four basic types of constants in C Programming Language.

Integer Constants

An integer constant can only hold integer quantity which is a sequence of whole numbers or digits.

  • Integer constant can not have a decimal point or fractional part.
  • Blanks and commas are not allowed within an integer constant.
  • An integer constant can be either +ve or -ve.
  • The constant must lie within the range of the declared data type (including qualifiers long, short, etc.).

An integer constant can be either Decimal, Hexa Decimal, or Octal.
A decimal integer constant consists of any combination of digits taken from the set 0 through 9. If the decimal constant contains two or more digits, the first digit can not be 0 (Zero).

Example:

12, 15, 456 etc.

An octal integer constant is a combination of digits taken from the set 0 through 7. In octal representation, the first digit must be a 0(Zero), in order to identify the constant as an octal number.

Example:

0, 05, 054

A hexadecimal integer constant must begin with either 0x or 0X. It can then be followed by any combination of digits taken from the set 0 through 9 and alphabets from A to F (either upper-case or lower-case are valid).

Example:

0x65F, 0X7A

Floating Point Constants

A floating-point or real constant contains a decimal point or an exponent.

  • A real constant must have at least one digit each to the left and right of the decimal point.
  • It can be either +ve or -ve.
  • Commas and blank space are not allowed within a real constant.

A real constant can be represented in two forms: Factorial form or Exponential form.

A real constant in a fractional form must have at least one digit each to the left and right of the decimal point.

Example:

15.75, -2.25

A floating-point in exponent form consists of a mantissa and an exponent.

Example:

-2.5e-3, 25E-4

Character Constants

A character constant is a single character, enclosed in single quotation marks. It can be a single alphabet, a digit, or a special symbol. The maximum length of a character constant is one character.

Example:

‘A’, ‘5’, ‘$’

String Constants

A string constant is a sequence of characters enclosed in double quotes. It may contain letters, digits, special characters, and blank spaces.

Example:

“HELLO”, “world”

C Variables

What is an Identifier?

Like any other programming language, we must aware of the naming conventions in C Programming Language before starting programming. An identifier is a name given to program elements such as c variables, arrays & functions. In the programming language C, an identifier is a sequence of alphabets or digits. Following rules must be kept in mind while naming an identifier.

  • The first character must be an alphabet (uppercase or lowercase) or can be an underscore.
  • All succeeding characters must be alphabets or digits.
  • No special characters or punctuation symbols are allowed except the underscore”_”.
  • No two successive underscores are allowed.
  • Keywords should not be used as identifiers.

What is a keyword?

In C Programming Language there are set words that you cannot use as an identifier. These words are known as “reserved” words or “Keywords”. Keywords are standard identifiers and their meaning and purpose are predefined by the compiler.

There are a set of 32(Thirty-Two) keywords in the C programming language.

int float double long
short signed unsigned const
if else switch break
default do while for
register extern static struct
typedef enum return sizeof
goto union auto case
void char continue volatile

Note:-We cannot use keywords for declaring Variable Name, For Function Name, and for declaring Constant Variable

What is a variable?

Like in any other programming language, in C Programming Language Variables are identifiers used to refer to a memory location in computer memory that holds a value for that variable, this value can be changed during the execution of the program. The size of the memory block allocated and the type of the value it holds are completely dependent upon the type of variable. Naming a variable in C Programming Language is an important task.

Rules for naming a variable –

  • A variable name can consist of letters, alphabets and start with underscore characters.
  • The first character of the variable should always be an alphabet and cannot be a digit.
  • Keywords are not allowed to use as a variable name.
  • Blank spaces are not allowed in a variable name.
  • C is case sensitive i.e. UPPER and lower case are significant.
  • Special characters like #, $ are not allowed except the underscore.
  • A variable name can be consist of 31 characters only if we declare a variable more than 1 characters compiler will ignore after 31 characters.

Recommendation:- Variable name must be readable and should be relative to its purpose.

Declaring a variable

In C Programming Language a variable must be declared before using it. Declaring variables is the way in which a C program tells the compiler about the number of variables it needs, what they are going to be named, and how much memory it will need. It is important to have knowledge about the type of variables and the size of these types.

Syntax:

Example:

Here is an example of declaring an integer, which we’ve called counter. (Note the semicolon at the end of the line; that is how your compiler separates one program statement from another.)

This statement means we’re declaring some space for a variable called counter, which will be used to store integer data. Note that we must specify the type of data that a variable will store.

Declaring multiple variables

Multiple variables can be declared with one statement.

Syntax:

Example:

Initializing variables

We can also declare and assign some content to a variable at the same time.

This is called initialization.

Assigning variables

After declaring variables, you can assign a value to a variable later on using a statement like this:

You can also assign a variable the value of another variable, like so:

Or assign multiple variables the same value with one statement:

 

 

C Data Types

Like any other programming language in C Programming Language “Variables” are one of the vital building blocks of any C data types and program. Variables are reserved memory locations to store values, when we create a variable we are supposed to allocate some memory space for that variable.

The C programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable’s data type and the name of the variable.

Example:

In C Programming Language every variable must have attached a data type to it, the data type for a variable defines :

  • The amount of memory space allocated for variables.
  • A data type specifies the possible values for variables.
  • The operations that can be performed on variables.

In C Programming Language data types can be broadly classified as :

  • Primary data types – int, float, double, char, void
  • Derived data types – Derived from primitive data type ex: array, pointer, function, etc.
  • User-defined – Defined by the programmer himself.

Primary Data Types In C Language

The C Programming Language supports primary data types. A primary type is predefined by the language and is named by a reserved keyword.

Integer types:

Integers are whole numbers.int is used to define integer numbers.

Syntax:

 

Type Storage size Value range
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

Floating Point Types:

The float data type is used to store numbers with a decimal point(real number).

Syntax:

 

Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Character Type:

Used to define characters. The character type variables can hold a single character.

Syntax:

 

Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127

Void Type:

The void type means no values. It can not be used with the variable declaration. It is usually used with function to specify its return type or its arguments.

Example:

User-defined type declaration

C Programming language allows users to create new data types. But it is usually created using an existing data type with another identifier. This user-defined data type identifier can later be used to declare variables. In short, its purpose is to redefine the name of an existing data type.

Syntax:

Now we can use number identifier instead of int to declare integer variables.

Enum Data Type

This is a user-defined data type having a finite set of enumeration constants or aliases.

Syntax:

 

C Program Structure

Like any other programming language, c language have specification available for c program structure, every c program is consist of the following building blocks –

 

  • Documentations block
  • Preprocessor Statements – Link Preprocessors, Definition Preprocessors
  • Global declarations
  • The main ( ) function
  • Local Declarations
  • Program statements
  • User-defined functions

Documentations Block

Documentation block is the header of any c program structure which mainly consists of a set of comments, that is used to provide the information about the program written like name of a program, the utility of the program, date of creation, date of last modification, author name, licensing or copyrights information and any other information that programmer wish to put for the references.

Example:

 

Preprocessor Statements

This is the section where we define all the preprocessor directives, preprocessor statement begins with the # symbol. Preprocessor statements tell the compiler to include C preprocessors directives such as header files and constants prior to compilation of the C program. Preprocessor statements are further categorized as below –

Link Preprocessor- These preprocessor directives tell the compiler to link the functions from a system library.

Example:

Definition Preprocessor – This is the section where we define all the symbolic constants we gonna use in our program.

Example:

Global Declarations

This is the section where all the global variable and function declaration comes. All the variables and functions defined or declared outside the main function are treated as global.

The main ( ) function

This is the most vital part of each and every C program, it is mandatory for the C program to have only one main ( ). The C program execution starts with the main ( ) function. The c program can not be executed without the main function. It is illegal to terminate it by a semicolon. The main ( ) is the building block where all the logic of the program comes into the picture. The main ( ) is responsible for the execution of all the user-defined statements, functions, and library functions. The main ( ) function further structured into – Local variable declaration, function declaration and user-defined executable statements.

Local Declarations

In this section, we declare all the variables that will be used in the main ( ) function. Here we can also declare arrays, functions, pointers, etc. These variables can also be initialized with basic data types and initial values. For examples.

  • All the local variable declaration is done in the variable declaration section.
  • the main ( ) function can further have the declaration for user-defined functions.
  • All the user-defined function definition appears immediately after the main function.

Program statements

This is the section where we place our main logic of the program which included the executable statements, that tell the computer to perform a specification action. Program statements can be input-output statements, arithmetic statements, control statements, simple assignment statements, and any other statements and it also includes comments that are enclosed within /* and */. The comment statements are ignored during the compilation and execution of the program and each executable statement must be ended with a semicolon.

  • the main ( ) function should contain at least one executable statement.
  • All statements in the declaration and executable parts end with a semicolon.

User-defined functions

This is the section of the C Program where we put all the user-defined sub-program or custom functions created to perform a specific task. A user-defined function must be defined before use it. A user-defined function can be written before or immediately after the main ( ) function and called inside the main ( ) function.

C Introduction

What is C? What is it for?

C is a general-purpose high-level (compiler language) computer programming language, developed by Dennis Ritchie at Bell Labs in late 1972 and was designed with the sole purpose to run on a PDP-11 with a UNIX operating system. Let’s know more about c introduction.

C is known as programmer’s language, every program we write is limited by the language which is used to write it but in the case of C, we can program anything from small programs for personal amusement to the new operating system. C is one of a large number of high-level languages which can be used for general-purpose programming. C is best suited for modern computers and modern programming.

High Levels and Low Levels

Computer programming languages majorly are of two types, that is Low-Level Languages and High-Level Languages. Low-Level languages are further categorized into Machine language and Assembly language. This level depends upon the condition that how closely they interact with the computer. Low level is perhaps the easiest to understand, Low level languages are machine-oriented and work most closely to the hardware, and require extensive knowledge of computer hardware, its configuration, and organization.

Machine Language

Machine Language is the language which directly understood by the computer and does not need any further translation before execution. In Machine Language instruction is given in form of machine code and which is a string of 1′s (one) and 0’s (zero). When this sequence of codes is sent as input to the computer, it understands the codes and converts them into electrical signals to perform a specific operation.
Machine Language is not easy to learn. The only advantage is that program run very fast because no further translation is required for the CPU to execute it.

Assembly Language

It is the first level of improvement in the programming language. An assembly language program is a set of human-readable shortcodes that substitute opcodes (Operation Codes). A translator program is required to translate or map the Assembly Language to machine language. This translator program is known as ‘Assembler’. Assembly language is much easier to write learn and debug than machine language.

Let’s take look at the below example code where the same instruction is coded in machine and assembly language: The instruction means:

add the integers in registers $t1 and $t2 and put the result in the register $t0.

Assembly language is machine-dependent means programs written for one computer might not run in other computers with different hardware configurations.

HIGH-LEVEL LANGUAGES

High-Level Languages instructions are given in natural English-like words, it is many problems oriented irrespective of the type of computer you are using. High-level languages not only give as a way to express instructions to computers, but they also give a channel of communication among human beings. They are not machine biased instead they give away to express ideas and a way to solve logical problems.

In High-Level Languages, you must be well versed with tokens, keywords, programming syntax, and the logic of the problem to solve a specific problem.

To execute a set of instructions on a specific machine that is programmed in High-Level Language, it must be translated first to its machine language. This is done by a computer program that is known as a compiler. A Compiler is a program that translates a High-level language program to a machine language code which is executable code. By using the appropriate compiler we can execute our High-level language programs on any platform.

HLLs Advantages:

  • High-level language programs are machine-independent.
  • High-level languages are more abstract and easy to learn and do not require deep knowledge of computer hardware.

C is known as a high-level, compiler language. C language is equipped with a full-fledged set of features that allow programs to write a program in an organized, easy, and logical way. This is very important when we are writing lengthy programs because complex problems are only manageable with a clear organization and program structure. C gives a way for creating meaningful variable names and meaningful function names to be used in programs without having loss of efficiency and effectiveness of the program, it gives complete freedom of coding style. It has a set of very flexible control structures for decision-making and looping that is excellent for controlling the flow of programs.

C Programming Language characteristics

  • Function or procedure-oriented
  • C is much more flexible and free-wheeling.
  • Small Size
  • Loose typing
  • Structured Language
  • Low level or BitWise operation readily available
  • Pointer implementation – extensive use of pointers for memory, array, structures, and functions.

C Programming Language Advantages

  • Easy to learn and use
  • It has high-level constructs that allow the programmer to organize programs in a clear, easy, and logical way.
  • Full-fledged set of features we can program anything from a small program for personal amusement to a new operating system.
  • Platform Independent and portable
  • Higher the speed of program execution
  • A lot of libraries are already written in C.

C Programming Language Disadvantages

  • C does not have an OOPS feature
  • There is no strict type checking (for example we can pass an integer value for the floating data type).
  • Poor error detection at runtime
  • C doesn’t have the concept of the namespace.
  • C doesn’t have the concept of constructors and destructors.