Category Archives: C Programming Basics

C Tokens

What Is Token

The smallest individual entity used in a c program is known as a token. Tokens are the various elements in a program; identified by the compiler. It can be anything that is meaningful to the compiler. Compiler parses the program and extracts the individual tokens. The tokens are the important building block of the C programming language. We can not create a c program without using c tokens.

Types of Token In C

C supports the following six types of tokens:

  • Keywords
  • Identifiers
  • Strings
  • Operators
  • Constants
  • Special Symbols

c-tokens-type

Keywords

There is a set of reserved words that you cannot use as an identifier. These words are known as “reserved words” or “Keywords”. Keywords are standard identifiers and their function and behavior are predefined by the compiler. There are 32 keywords in the C language.

Example:-

Identifiers

An identifier is a name given to program elements such as functions, variables, structures, unions, arrays, etc. It is a sequence of letters, digits, and underscores. The keywords can not be used as identifiers. The identifier must differ in spelling and case from keywords.

Example:-

Strings

String refers to a series or sequence of characters such as letters, numbers, and special characters. In C programming, string is enclosed in double-quotes(“”) and characters are enclosed in single quotes(”).

Example:-

Operators

The operator is a special symbol that is used to carry out some specific operation on its operand. In c programming, we have a rich set of built-in operators to carry out a different typess of operations. There are operators for assignment, arithmetic operations, logical operations, comparison operations, etc.

Example:-

Constants

Constants refer to immutable values. These are basically literals whose values cannot be modified or changed during the execution of the program.

Example:-

Special Symbols

The special symbols have some special meaning associated with them. They cannot be used for some other purpose except a special purpose attached to them.

Example:-

C Comments

C Comments

In c programming, comments are a set of statements that are not executed by the compiler. The use of comments makes it easy for humans to understand the source code. Usually, comments give you an inside or explanation about the variable, method, class, or any statement that exists in the source code. The comment statements are ignored during the execution of the program. In this tutorial I’ll explain you how to use comments properly with syntax and examples.

Types of Comments In C

In C programming, there are 2 types of comments.

  • Single Line Comment
  • Multi-Line Comment

types-of-comments-in-c

It is recommended to choose a commenting style and use it consistently throughout your source code. Doing this makes your code more readable.

Single line Comment

A ‘//’ (double forward slash) is used to specify a single line comment, which extends up to the newline character. This can be used to comment out everything until a line break. Let’s see an example of a single line comment in C.

Syntax:-

General syntax of single line comments is as follows:

Example:-

Simple example to demonstrate the use of single line comments is as follows:

Output:-

Now when we run the above program we see the following output, here the comment is completely ignored by compiler.

Multi-line Comment

You can also create a comment that spans multiple lines. If you want to comment multiple lines then you can do it using /* and */. The compiler ignores everything from /* to */. Let’s see an example of a multi-line comment in C.

Syntax:-

General syntax of multi-line comments is as follows:

Example:-

Simple example to demonstrate the use of multi-line comments is as follows:

Output:-

Now when we run the above program we see the following output, here the comment is completely ignored by compiler.

Uses of multi-line comments are as follows:

  • Useful for commenting out a section of code
  • Cannot be nested within other multi-line comments

C Input & Output

Input & Output is the way general-purpose computers can communicate or interact with the outside world. In C Programming Language input & output is the way a program can read in or write out data streams. Streams can be used for both un-formatted and formatted input and output.

To perform standard input and output, we need to include the following preprocessor directive into our files.

There are three standard streams are available to all c programs –

  • stdin (standard input)
  • stdout (standard output)
  • stderr (standard error)

Reading and writing single characters

getchar() function is used to read a single character from the “stdin” data stream, it returns the EOF (end of file) if there are no more characters to read or when you hit the end of a file or when the user types the end of the file.

putchar() function is used to write a single character to the “stdout” data stream. It puts a single character at a time, we can loop it for writing multiple characters.

Example:

Reading and writing string

The gets() function reads the input data stream until the EOF is determined, while the puts() function is used to write a string to the “stdout” stream until a newline character is detected.

Syntax:

Example:

Formatted I/O

The printf() function

The printf() function is used for writing formatted out to the “stdout” stream. This way it allows us to print values and variables to the standard output stream (in most cases, the screen).

Syntax:

Example:

The above printf statement contains two sets of arguments: the control string enclosed in double-quotes, and identifiers to specify the value to be printed. The control string contains text, conversion specifiers, or both.

Below is the list of some common conversion specifiers –

format string input type
%c character
%d digit (integer)
%f float
%lf double
%u unsigned
%s string

The scanf() function

The scanf() function is used for reading formatted input from the “stdin” data stream. It reads the string as per the format specified.

Syntax:

Example:

C Type Casting

Here you know about type casting is a mechanism in the c programming language that enables a variable of one data type to be converted to another datatype. When a variable is typecasted into a different type, the compiler basically treats the variable as the new data type.

Type of casting

  • implicit or automatic
  • explicit or given

implicit or automatic

An implicit or automatic casting compiler will automatically change one type of data into another. For instance, if you assign an integer value to a floating-point variable, the compiler will insert code to convert the int to afloat.

Example:

Here the value of 'a' has been promoted from short to int and we have not had to specify any type-casting operator. implicit conversions affect fundamental data types. Typecasting should always be used in the right order (low to the higher data type). Typecasting in wrong places may result in loss of precision, which the compiler can signal with a warning. for example, instance truncating afloat when typecasting to an int. This can be avoided with an explicit conversion. Below is the right order for numerical conversion.

short int -> int -> unsigned int ->long int -> unsigned long int -> float -> double -> long double

explicit or given

Casting allows you to make this type of conversion explicit, or to force it when it wouldn’t normally happen. To perform typecasting, put the desired type including modifiers (like double) inside parentheses to the left of the variable or constant you want to cast.

Example:

type casting from char to int results in ASCII code –

 

C Character Set

A character set in C Programming Language is set all valid characters that can be used to form words, numbers, and expression’s in source programs. The source character set is consist of the characters used for the source program text, while the execution character set is the set of characters used during the execution of the program.

It is not necessary that the source character set match and execution character set are the same.

Below is the list of characters available in C Programming Language –

The 26 lowercase Roman characters:

The 26 uppercase Roman characters:

The 10 decimal digits:

The 30 graphic characters:

Five white space characters:

Space( ),Horizontal tab (\t) , Carriage return(\v), Newline(\n) , form feed (\f)

C Escape Sequence

In C Programming Language c escape sequence is a special string comprising a backslash (\) followed by a letter or by a combination of digits used to control output on the monitor. C escape sequences are typically used to represent actions such as newline, carriage returns, tab movements, and nonprinting characters over the monitor. The following table lists the common ANSI c escape sequences and their meaning.

Escape Sequence Represents
\a Bell (alert)
\b Backspace
\f Formfeed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quotation mark
\ " Double quotation mark
\\ Backslash
\? Literal question mark
\ ooo ASCII character in octal notation
\x hh ASCII character in hexadecimal notation
\x hhhh Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal.

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