Unit 1
Introduction
Computers were developed to perform the all arithmetic and logical operations accurately and in time efficient manner. As computer is an electronic machine so it can understand only language of zeros and ones which is also called as binary language. The zero in binary language represents the absence of power supply whereas one represents the presence of power supply. In early days of computers, to perform arithmetic and logical operations, programs are written in terms of zeros and ones. But it was very difficult to understand the language of 0’s and 1’s. So Alan Turing wrote the set of shorthand codes to speed up and ease the computer programming. After which the notion of programming language introduced, which includes the set of characters with specified rules.
C language was developed by Dennis Ritchie at bell laboratory in year 1972. Most of the features of C language were derived from B language. Due to flexibility of C language, UNIX operating system which was initially written in assembly language was again rewritten in C language.
Features of C language
• C language follows structure oriented programming approach.
• C is a procedure oriented language.
• In C language, complete program is composed of various functions and procedures.
• C language follows Top-Down approach in program design.
In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming Language” and commonly known as K&R C.
Advantages of C language
• Reliability: C language allows low level access to data and commands and maintains the syntax of a high level language. These qualities make it a useful language for both systems programming and general purpose programs.
• Flexibility: C is a powerful and flexible language which provides fast program execution.
• Modularity: C language provides features like Functions, Structures, Unions and Built-in Library functions which support code reusability.
• Efficiency and Effectiveness: The programs of C language are less complex and do not require any special programming language platform other than compiler. C language plays vital role in hardware programming
Constant:
- Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
- Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
- Constants are treated just like regular variables except that their values cannot be modified after their definition.
In C/C++ program we can define constants in two ways as shown below:
- Using #define preprocessor directive
- Using a const keyword
Variables:
Variables are the names you give to computer memory locations which are used to store values in a computer program.
Here are the following three simple steps −
- Create variables with appropriate names.
- Store your values in those two variables.
- Retrieve and use the stored values from the variables.
When creating a variable, we need to declare the data type it contains.
Programming languages define data types differently.
For example, almost all languages differentiate between ‘integers’ (or whole numbers, eg 12), ‘non-integers’ (numbers with decimals, eg 0.24), and ‘characters’ (letters of the alphabet or words).
- char – a single 16-bit Unicode character, such as a letter, decimal or punctuation symbol.
- boolean – can have only two possible values: true (1) or false (0). This data type is useful in conditional statements.
- byte - has a minimum value of -128 and a maximum value of 127 (inclusive).
- short– has a minimum value of -32,768 and a maximum value of 32,767
- int: – has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
- long – has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
- float – a floating point number with 32-bits of precision
- double – this is a double precision floating point number.
Keywords:
Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier.
For example:
Here int is a keyword that indicates money is variable of type int (integer) . As C is case sensitive language all keywords must be written in lowercase.
Example:
int money;
C Constants are also like normal variables. But, only difference is, their values can not be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of constant
Integer constants
Real or Floating point constants
Octal & Hexadecimal constants
Character constants
String constants
Backslash character constants.
Backlash Character
There are some characters which have special meaning in C language.
They should be preceded by backslash symbol to make use of special function of them.
Given below is the list of special characters and their purpose.
Integer Constant
An integer constant must have at least one digit.
It must not have a decimal point.
It can either be positive or negative.
No commas or blanks are allowed within an integer constant.
If no sign precedes an integer constant, it is assumed to be positive.
The allowable range for integer constants is -32768 to 32767.
Real Constant
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
Character and String constant:
A character constant is a single alphabet, a single digit or a single special symbol enclosed within single quotes.
The maximum length of a character constant is 1 character.
String constants are enclosed within double quotes.
The Programming language C has two main variable types
Local Variables
Global Variables
Local Variables
Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.
When a local variable is defined - it is not initalised by the system, you must initalise it yourself.
When execution of the block starts the variable is available, and when the block ends the variable 'dies'.
Check following example's output
main()
{
int i=4;
int j=10;
i++;
if (j > 0)
{
/* i defined in 'main' can be seen */
printf("i is %d\n",i);
}
if (j > 0)
{
/* 'i' is defined and so local to this block */
int i=100;
printf("i is %d\n",i);
}/* 'i' (value 100) dies here */
printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/
}
This will generate following output
i is 5
i is 100
i is 5
Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1;
You will see -- operator also which is called decremental operator and it decrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;
Global Variables
Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.
Global variables are initalised automatically by the system when you define them!
Data Type Initialser
int 0
char '\0'
float 0
pointer NULL
If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.
int i=4; /* Global definition */
main()
{
i++; /* Global variable */
func();
printf( "Value of i = %d -- main function\n", i );
}
func()
{
int i=10; /* Local definition */
i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}
This will produce following result
Value of i = 11 -- func() function
Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global.
Rules for constructing variable names
1) A Variable name consists of any combination of alphabets, digits and underscores. Some compiler allows variable names whole length could be up to 247 characters. Still it would be safer to stick to the rule of 31 characters.
2) The first character of the variable name must either be alphabet or underscore. It should not start with the digit.
3) No commas and blanks are allowed in the variable name.
4) No special symbols other than underscore are allowed in the variable name.
We need to declare the type of the variable name before making use of that name in the program.
Type declaration can be done as follows:
To declare a variable as integer, follow the below syntax:
int variable_name;
Here int is the type of the variable named variable_name. ‘int’ denotes integer type.
Following are the examples of type declaration statements:
E.g.: int p, n;
float r;
A well-documented program is a good practice as a programmer. It makes a program more readable and error finding become easier. One important part of good documentation is Comments.
- In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program
- Comments are statements that are not executed by the compiler and interpreter.
In C/C++ there are two types of comments :
- Single line comment
- Multi-line comment
// single line comment
/* */ multiline comment
Type Declaration Instruction
- This instruction is used to declare the type of variables being used in the program.
- Any variable used in the program must be declared before using it in any statement.
- The type declaration statement is written at the beginning of main( ) function.
Example :
int bas ;
float rs, grosssal ;
char name, code ;
- While declaring the type of variable we can also initialize it as shown below.
int i = 10, j = 25 ;
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;
- The order in which we define the variables is sometimes important sometimes not.
int i = 10, j = 25 ;
is same as
int j = 25, i = 10 ;
However,
float a = 1.5, b = a + 3.1 ;
is alright, but
float b = a + 3.1, a = 1.5 ;
is not. This is because here we are trying to use a even before defining it.
- The following statements would work.
int a, b, c, d ;
a = b = c = 10 ;
However, the following statement would not work.
int a = b = c = d = 10 ;
Once again we are trying to use b (to assign to a) before defining it.
Type conversions depend on the specified operator and the type of the operand or operators. Type conversions are performed in the following cases:
- When a value of one type is assigned to a variable of a different type or an operator converts the type of its operand or operands before performing an operation
- When a value of one type is explicitly cast to a different type
- When a value is passed as an argument to a function or when a type is returned from a function
A character, a short integer, or an integer bit field, all either signed or not, or an object of enumeration type, can be used in an expression wherever an integer can be used. If an int can represent all the values of the original type, then the value is converted to int; otherwise, it is converted to unsigned int. This process is called "integral promotion." Integral promotions preserve value.
Integer is defined as a number which has no fractional component. Numbers which have a fractional component is known floating point numbers. Despite the fact that floating point numbers can represent numbers accurately, integers have their own place in the world of computing due to:
- Integers consumes significantly less space than Floating point numbers
- Calculations using integers are much faster (over 2 times) due to hardware architecture
In C programming language, integer data is represented by its own datatype known as int. It has several variants which differs based on memory consumption includes:
- int
- long
- short
- long long
Integer is defined as a number which has no fractional component. Numbers which have a fractional component is known floating point numbers. Despite the fact that floating point numbers can represent numbers accurately, integers have their own place in the world of computing due to:
Integers consumes significantly less space than Floating point numbers
Calculations using integers are much faster (over 2 times) due to hardware architecture
In C programming language, integer data is represented by its own datatype known as int. It has several variants which differs based on memory consumption includes:
int
long
short
long long
In C, one can define an integer variable as:
Signed and unsigned version:
As the range of numbers determined by a datatype like int is limited and both negative and positive numbers are required, we have two options:
- signed integers: range is equally divided among negative and positive numbers (including 0)
- unsigned integers: range starts from 0 to the upper positive number limit
Hence, unsigned integers are used when:
- negative numbers are not required
- increase the range of positive number by double
One can defined an unsigned integer by placing the keyword unsigned before the usual declaration/ initialization like:
The default declaration is the signed version signed.
Hence, there are 8 possible types for integer:
- int
- unsigned int
- short
- unsigned short
- long
- unsigned long
- long long
- unsigned long long
Format specifier
To print a value in C using printf, one needs to specify the datatype of the data to be printed. The format specifier of each variant of integer datatype is different in C.
For instance, int datatype has %d as the format specifier.
Following code demonstrates the idea:
Range and memory consumption
One can find the memory consumed by a data type as follows:
The signed char type when converted to integer type can represent both -ve and +ve values,but unsigned type can represent only +ve value.
In signed type the left most bit is reserve to store either 1 or 0 bit to represent -ve and +ve sign leaving only 7 bits to represent the actual value.So, it can represent an integer between -27 to (27 – 1) (-128 to 127). In case of unsigned type no such allocation is made so it can represent an integer between 0 and (28-1)(0 to 255).In the pictorial representation below the range of integer value they can represent is shown on the number line.
Float - It is used to store single precision floating point number.
Double - It is used to store a double precision floating point number.
The double type provides more precision than the float type. It simply means that the double- type provides more digits to the right of decimal point than the float type. To be precise, the float provides 6 digits of precision, while the double provides 14 digits of precision.
It is important to note that the float and double represents the same type - floating point numbers. The only difference is in the number of precision.
Console simply means screen and keyboard. There are two types of a console I/O functions:
- Formatted input-output function
- Unformatted input-output function
The major difference is that formatted function allows us to format the input from the keyboard and the output to be displayed on the screen.
printf() is the standard library function that is used for precise output formatting.
syntax of printf( ) function:
printf(format-control-string, other -arguments );
Format control string in printf( ) function describes the output format which consists of conversion specifiers, precisions, flags, field widths and literal characters.
Each conversion specifier starts with % sign and ends with a conversion specifier.
Keyboard and screen together called console. This is the behind the name of these functions. Console I/O functions further classified into
- Formatted Input/Output Functions
- Unformatted Input/Output Functions
Formatted Input/Output Functions in C
printf() and scanf() functions comes under this category. They provide the flexibility to receive the input in some fixed format and to give the output in desired format
sprintf() and sscanf() Function
These formatted console I/O functions works a bit different to printf() and scanf() functions. sprintf() function is quite similar to printf() function but instead of printing the output on screen, it stores it in the character array.
Consider below example to understand this.
1 2 3 4 5 6 7 8 9 10 11 12 | #include<stdio.h>
void main() { int j=32; char cha='p'; float a=123.2; char str[20]; sprintf(str,"%d %c %f",j,cha,a); printf("%sn",str);
} |
sscanf() is the counter part of sprintf() function. It allows the programmer to store the characters of string in some other variable. These two functions are used very rarely in C.
Unformatted Input/Output Functions in C
Functions like getch(), getche() and getchar() comes under this category. These functions store only one character. Till now we have used scanf() function to store values. Unfortunately we have to press enter key while using scanf() function to store the values in memory. In a condition when we have to store only one character these unformatted function comes very handy.
The header file used for these three functions is conio.h.
getch() function
This function is used to store only one character in memory. It does not echo or display that character on the screen while program execution.
getche() function
This function works similar to getch function. However it just echo or display that character on screen.
getchar() function
This function works entirely similar to getche function. It stores one character and display it on the screen. But we have to press the enter key to store one character while using this function.
Consider below example to understand these functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include<stdio.h> #include<conio.h>
void main() { char ch1,ch2,ch3; ch1=getch(); // it does not echo the character on screen ch2=getche(); //echo's character on screen ch3=getchar(); // Use Enter to store the value
printf("%c %c %cn",ch1,ch2,ch3);
} |
Output
- if Statements
This statement permits the programmer to allocate condition on the execution of a statement. If the evaluated condition found to be true, the single statement following the "if" is execute. If the condition is found to be false, the following statement is skipped. Syntax of the if statement is as follows
if (condition)
statement1;
statement2;
In the above syntax, “if” is the keyword and condition in parentheses must evaluate to true or false. If the condition is satisfied (true) then compiler will execute statement1 and then statement2. If the condition is not satisfied (false) then compiler will skip statement1 and directly execute statement2.
if-----else statement
This statement permits the programmer to execute a statement out of the two statements. If the evaluated condition is found to be true, the single statement following the "if" is executed and statement following else is skipped. If the condition is found to be false, statement following the "if" is skipped and statement following else is executed.
In this statement “if” part is compulsory whereas “else” is the optional part. For every “if” statement there may be or may not be “else” statement but for every “else” statement there must be “if” part otherwise compiler will gives “Misplaced else” error.
Syntax of the “if----else” statement is as follows
if (condition)
statement1;
else
statement2;
In the above syntax, “if” and “else” are the keywords and condition in parentheses must evaluate to true or false. If the condition is satisfied (true) then compiler will execute statement1 and skip statement2. If the condition is not satisfied (false) then compiler will skip statement1 and directly execute statement2.
Nested if-----else statements :
Nested “if-----else” statements are used when programmer wants to check multiple conditions. Nested “if---else” contains several “if---else” a statement out of which only one statement is executed. Number of “if----else” statements is equal to the number of conditions to be checked. Following is the syntax for nested “if---else” statements for three conditions
if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else
statement4;
In the above syntax, compiler first check condition1, if it trues then it will execute statement1 and skip all the remaining statements. If condition1 is false then compiler directly checks condition2, if it is true then compiler execute statement2 and skip all the remaining statements. If condition2 is also false then compiler directly checks condition3, if it is true then compiler execute statement3 otherwise it will execute statement 4.
Note:
If the test expression is evaluated to true,
• Statements inside the body of if are executed.
• Statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
• Statements inside the body of else are executed
• Statements inside the body of if are skipped from execution.
// Check whether an integer is odd or even
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
Program to relate two integers using =, > or < symbol
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
//checks if the two integers are equal.
if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
}
//checks if both test expressions are false
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
- Logical operators are used to compare logical values of two operands. Following are the list of logical operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
Sr. No. | Operator | Description | Example |
1. | && | This is logical AND, it returns true when both the values are non zero | Result of (A&&B) is true |
2. | || | This is logical OR, it returns true when any of two value is non zero | Result of (A||B) is true |
3. | ! | This is logical NOT operator, it is used to reverse the logical state of operand | Result of !(A&&B) is false |
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter two numbers");
scanf("%d %d",&a,&b);
printf("\n Result of logical and operator of %d and %d is %d",a,b,a&&b);
printf("\n Result of logical or operator of %d and %d is %d",a,b,a||b);
printf("\n Result of logical not operator of %d and and %d is %d",a,b,!(a&&b));
getch();
}
Output:
Enter two numbers
5
3
Result of logical and operator of 5 and 3 is 1
Result of logical or operator of 5 and 3 is 1
Result of logical not operator of 5 and 3 is 0
General Syntax of else if clause is given below.
if (condition)
{
Statement 1
Statement 2 and so on
}
else if (condition)
{
Statement 1
Statement 2 and so on
}
else if (condition)
{
Statement 1
Statement 2 and so on
}
else
{
Statement 1
Statememt 2 and so on
}
Bitwise OR operator :
The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
Syntax of a conditional operator
Expression1? expression2: expression3;
The pictorial representation of the above syntax is shown below:
Conditional Operator in C
Meaning of the above syntax.
In the above syntax, the expression1 is a Boolean condition that can be either true or false value.
If the expression1 results into a true value, then the expression2 will execute.
The expression2 is said to be true only when it returns a non-zero value.
If the expression1 returns false value then the expression3 will execute.
The expression3 is said to be false only when it returns zero value.
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional operator
return 0;
}
In the above code, we are taking input as the 'age' of the user. After taking input, we have applied the condition by using a conditional operator. In this condition, we are checking the age of the user. If the age of the user is greater than or equal to 18, then the statement1 will execute, i.e., (printf("eligible for voting)
otherwise, statement2 will execute, i.e., (printf("not eligible for voting")
References:
The C Programming Language. 2nd Edition Book by Brian Kernighan and Dennis Ritchie
C Programming: A Modern Approach Book by Kim N. King
C Programming Absolute Beginner’s Guide book by S.D Perry