Programming in C �Unit 1
ES-101/102
1
2
MODULE 1
LECTURE NOTE-1
A BEGINNER’S GUIDE
INTRODUCTION TO COMPUTERS
Any programming language is implemented on a computer. Right form its inception, to the present day, all computer system (irrespective of their shape & size) perform the following 5 basic operations. It converts the raw input data into information, which is useful to the users.
Based on these 5 operations, we can sketch the block diagram of a computer.
Fig 1: Block Diagram of a Computer
3
Fig 1: Block Diagram of a Computer
Department of Applied Science,
BVCOE New Delhi Subject: Programming In C , Instructor: Anu Yadav
4
Primary Storage: The primary storage, also called as the main memory, holds the data when the computer is currently on. As soon as the system is switched off or restarted, the information held in primary storage disappears (i.e. it is volatile in nature). Moreover, the primary storage normally has a limited storage capacity, because it is very expensive as it is made up of semiconductor devices.
Secondary Storage: The secondary storage, also called as the auxiliary storage, handles the storage limitation & the volatile nature of the primary memory. It can retain information even when the system is off. It is basically used for holding the program instructions & data on which the computer is not working on currently, but needs to process them later.
Arithmetic Logic Unit: The actual execution of the instructions (arithmetic or logical operations) takes place over here. The data & instructions stored in the primary storage are transferred as & when required. No processing is done in the primary storage. Intermediate results that are generated in ALU are temporarily transferred back to the primary storage, until needed later. Hence, data may move from the primary storage to ALU & back again to storage, many times, before the processing is done.
Control Unit: This unit controls the operations of all parts of the computer but does not carry out any actual data processing.It is responsible for the transfer of data and instructions among other units of the computer.It manages and coordinates all the
units of the system.It also communicates with Input/Output devices for transfer of data or results from the storage units.
Department of Electrical and Electronics Engineering, BVCOE New Delhi Subject: SUBJECT NAME , Instructor: INSTRUCTOR NAME
5
So when we talk about a computer, we actually mean 2 things:
Together, the hardware & software form the computer system.
This software is further classified as system software & application software.
System Software- System software are a set of programs, responsible for running the computer, controlling various operations of computer systems and management of computer resources. They act as an interface between the hardware of the computer & the application software. E.g.: Operating System
Application Software- Application software is a set of programs designed to solve a particular problem for users. It allows the end user to do something besides simply running the hardware. E.g.: Web Browser, Gaming Software, etc.
6
LECTURE NOTE-2
INTRODUCTION TO PROGRAMMING
A language that is acceptable to a computer system is called a computer language or programming language and the process of creating a sequence of instructions in such a language is called programming or coding. A program is a set of instructions, written to perform a specific task by the computer. A set of large program is called software. To develop software, one must have knowledge of a programming language.
Before moving on to any programming language, it is important to know about the various types of languages used by the computer. Let us first know what the basic requirements of the programmers were & what difficulties they faced while programming in that language.
COMPUTER LANGUAGES
Languages are a means of communication. Normally people interact with each other through a language. On the same pattern, communication with computers is carried out through a language. This language is understood both by the user and the machine. Just as every language like English, Hindi has its own grammatical rules; every computer language is also bounded by rules known as syntax of that language. The user is bound by that syntax while communicating with the computer system.
Computer languages are broadly classified as:
The low level languages are classified as:
Department of Electrical and Electronics Engineering, BVCOE New Delhi Subject: SUBJECT NAME , Instructor: INSTRUCTOR NAME
7
LECTURE NOTE -3
INTRODUCTION TO C
Brief History of C
(Basic Combined Programming Language – BCPL)
Department of Electrical and Electronics Engineering, BVCOE New Delhi Subject: SUBJECT NAME , Instructor: INSTRUCTOR NAME
8
Taxonomy of C Language
9
WHY IS C POPULAR
WHY TO STUDY C
programs, spreadsheets, compilers, and other products.
CHARECTERESTICS OF A C PROGRAM
High Level | Middle Level | Low Level |
High level languages provide almost everything that the programmer might need to do as already built into the language | Middle level languages don’t provide all the built-in functions found in high level languages, but provides all building blocks that we need to produce the result we want | Low level languages provides nothing other than access to the machines basic instruction set |
Examples: Java, Python | C, C++ | Assembler |
10
Structure oriented | Object oriented | Non structure |
In this type of language, large programs are divided into small programs called functions | In this type of language, programs are divided into objects | There is no specific structure for programming this language |
Prime focus is on functions and procedures that operate on the data | Prime focus is in the data that is being operated and not on the functions or procedures | N/A |
Data moves freely around the systems from one function to another | Data is hidden and cannot be accessed by external functions | N/A |
Program structure follows “Top Down Approach” | Program structure follows “Bottom UP Approach” | N/A |
Examples: C, Pascal, ALGOL and Modula-2 | C++, JAVA and C# (C sharp) | BASIC, COBOL, FORTRAN |
USES
The C programming language is used for developing system applications that forms a major portion of operating systems such as Windows, UNIX and Linux. Below are some examples of C being used:
11
STRUCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while writing a C program. The general basic structure of C program is shown in the figure below.
Based on this structure, we can sketch a C program.
Example:
/* This program accepts a number & displays it to the user*/
#include <stdio.h> void main(void)
{ int number;
printf( "Please enter a number: " ); scanf( "%d", &number );
printf( "You entered %d", number ); return 0;}
12
Stepwise explanation:
#include
<stdio.h>
void
main
(void)
13
{ (Brace)
; (semicolon)
scanf
printf
FILES USED IN A C PROGRAM
14
relocatable format machine code that is usually not directly executable. Object files are produced by an assembler, compiler, or other language translator, and used as input to the linker, which in turn typically generates an executable or library by combining parts of object files.
COMPLIATION & EXECUTION OF A C PROGRAM
15
ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with programming, we should be acquainted with the basic elements that build the language.
Character Set
Communicating with a computer involves speaking the language the computer understands. In C, various characters have been given to communicate.
Character set in C consists of;
Types | Character Set |
Lower case | a-z |
Upper case | A-Z |
Digits | 0-9 |
Special Character | !@#$%^&* |
White space | Tab or new lines or space |
Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer.
There are only 32 keywords available in C. Below figure gives a list of these keywords for your ready reference.
16
Identifier
In the programming language C, an identifier is a combination of alphanumeric characters, the first being a letter of the alphabet or an underline, and the remaining being any letter of the alphabet, any numeric digit, or the underline.
Two rules must be kept in mind when naming identifiers.
compiler.
Data Type
In the C programming language, data types refer to a domain of allowed values & the operations that can be performed on those values. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. There are 4 fundamental data types in C, which are- char, int, float &, double. Char is used to store any single character; int is used to store any integer value, float is used to store any single precision floating point number & double is used to store any double precision floating point number. We can use 2 qualifiers with these basic types to get more types.
There are 2 types of qualifiers-
Sign qualifier- signed & unsigned Size qualifier- short & long
The data types in C can be classified as follows:
Type | Storage size | Value range |
char | 1 byte | -128 to 127 |
unsigned char | 1 byte | 0 to 255 |
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 |
17
long | 4 bytes | -2,147,483,648 to 2,147,483,647 |
unsigned long | 4 bytes | 0 to 4,294,967,295 |
Type | Storage size | Value range | Precision |
float | 4 bytes | 1.2E-38 to 3.4E+38 | 6 decimal places |
double | 8 bytes | 2.3E-308 to 1.7E+308 | 15 decimal places |
long double | 10 bytes | 3.4E-4932 to 1.1E+4932 | 19 decimal places |
Constants
A constant is an entity that doesn’t change whereas a variable is an entity that may change.
C constants can be divided into two major categories:
18
Here our only focus is on primary constant. For constructing these different types of constants certain rules have been laid down.
Rules for Constructing Integer Constants:
An integer constant must have at least one digit.
Rules for Constructing Real Constants:
Real constants are often called Floating Point constants. The real constants could be written in two forms—Fractional form and Exponential form.
Rules for constructing real constants expressed in fractional form:
Rules for constructing real constants expressed in exponential form:
19
Rules for Constructing Character Constants:
Ex.: ‘M’, ‘6’, ‘+’
VARIABLES
Variables are names that are used to store values. It can take different values but one at a time. A data type is associated with each variable & it decides what values the variable can take. When you decide your program needs another variable, you simply declare (or define) a new variable and C makes sure you get it. You declare all C variables at the top of whatever blocks of code need them. Variable declaration requires that you inform C of the variable's name and data type. Syntax – datatype variablename;
Eg:
int page_no;
char grade; float salary; long y;
Declaring Variables:
There are two places where you can declare a variable:
After the opening brace of a block of code (usually at the top of a function)
Before a function name (such as before main() in the program) Consider various examples:
Suppose you had to keep track of a person's first, middle, and last initials. Because an initial is obviously a character, it would be prudent to declare three character variables to hold the three initials. In C, you could do that with the following statement:
main()
{
char first, middle, last;
// Rest of program follows
}
20
2. main()
{ char first; char middle; char last;
// Rest of program follows
}
When a variable is declared, it contains undefined value commonly known as garbage value. If we want we can assign some initial value to the variables during the declaration itself. This is called initialization of the variable.
Eg- int pageno=10;
char grade=’A’;
float salary= 20000.50;
Expressions
An expression consists of a combination of operators, operands, variables & function calls. An expression can be arithmetic, logical or relational. Here are some expressions:
a+b – arithmetic operation a>b- relational operation a
== b - logical operation func (a,b) – function call
4+21
a*(b + c/d)/20 q = 5*2 x =
++q % 3
q > 3
21
Department of Electrical and Electronics Engineering, BVCOE New Delhi Subject: SUBJECT NAME , Instructor: INSTRUCTOR NAME
22
Compound Statements (Blocks)
A compound statement is two or more statements grouped together by enclosing them in braces; it is also called a block. The following while statement contains an example:
while (years < 100)
{
wisdom = wisdom * 1.05; printf("%d %d\n", years, wisdom); years = years + 1;
}
If any variable is declared inside the block then it can be declared only at the beginning of the block. The variables that are declared inside a block can be used only within the block.
23
INPUT-OUTPUT IN C
When we are saying Input that means we feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to read given input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output the data on the computer screen.
Functions printf() and scanf() are the most commonly used to display out and take input respectively. Let us consider an example:
#include <stdio.h> int main()
{
//This is needed to run printf() function.
printf("C Programming"); //displays the content inside quotation return 0;
}
Output:
C Programming
Explanation:
Input- Output of integers in C
#include<stdio.h> int main()
{
int c=5;
24
printf("Number=%d",c); return 0;
}
Output
Number=5
Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this conversion format string matches with remaining argument, i.e, c in this case, value of c is displayed.
#include<stdio.h> int main()
{ int c;
printf("Enter a number\n"); scanf("%d",&c); printf("Number=%d",c); return 0;
}
Output
Enter a number 4
Number=4
The scanf() function is used to take input from user. In this program, the user is asked an input and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c and value is stored in that address.
Input- Output of floats in C
#include <stdio.h> int main()
{
float a;
printf("Enter value: "); scanf("%f",&a);
printf("Value=%f",a); //%f is used for floats instead of %d return 0;
}
25
26
return 0;
}
Output:
Enter character:
g
103
When, 'g' is entered, ASCII value 103 is stored instead of g.
You can display character if you know ASCII code only. This is shown by following example.
#include <stdio.h> int main()
{
int var1=69;
printf("Character of ASCII value 69: %c",var1); return 0;
}
Output
Character of ASCII value 69: E
The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b' is 98 and so on to 'z' is 122.
27
OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides the following types of operators:
Arithmetic operator:
These are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus.
Following table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:
Operator | Description | Example |
+ | Adds two operands | A + B will give 30 |
- | Subtracts second operand from the first | A – B will give -10 |
* | Multiplies both operands | A * B will give 200 |
/ | Divides numerator by de-numerator | B / A will give 2 |
28
% | Modulus Operator and remainder of after an integer division | B % A will give 0 |
++ | Increments operator increases integer value by one | A++ will give 11 |
-- | Decrements operator decreases integer value by one | A–will give 9 |
Relational Operators:
These operators are used to compare the value of two variables.
Following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20, then:
Operator | Description | Example |
== | Checks if the values of two operands are equal or not, if yes then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
Logical Operators:
These operators are used to perform logical operations on the given two variables.
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then:
29
Operator | Description | Example |
&& | Called Logical AND operator. If both the operands are nonzero, then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is true. |
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Bitwise operators are used in bit level programming. These operators can operate upon int and char but not on float and double.
Showbits( ) function can be used to display the binary representation of any integer or character value.
Bit wise operators in C language are; & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).
The truth tables for &, |, and ^ are as follows:
p | q | p & q | p | q | p ^ q |
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
30
The Bitwise operators supported by C language are explained in the following table. Assume variable A holds 60 (00111100) and variable B holds 13 (00001101), then:
Operator | Description | Example |
& | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) will give 12, which is 0000 1100 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) will give 61, which is 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) will give 49, which is 0011 0001 |
~ | Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits. | (~A ) will give -61, which is 1100 0011 in 2’s complement form. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 will give 240 which is 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 will give 15 which is 0000 1111 |
Assignment Operators:
In C programs, values for the variables are assigned using assignment operators. There are following assignment operators supported by C language:
Operator | Description | Example |
= | Simple assignment operator, Assigns values from right side operands to left side operand | C = A + B will assign value of A + B into C |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand | C += A is equivalent to C = C + A |
31
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand | C -= A is equivalent to C = C – A |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator | C &= 2 is same as C = C & 2 |
^= | bitwise exclusive OR and assignment operator | C ^= 2 is same as C = C ^ 2 |
|= | bitwise inclusive OR and assignment operator | C |= 2 is same as C = C | 2 |
32
INCREMENT AND DECREMENT OPERATOR
In C, ++ and – are called increment and decrement operators respectively. Both of these operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and – subtracts 1 to operand respectively. For example:
Let a=5 and b=10 a++; //a becomes 6 a--; //a becomes 5
++a; //a becomes 6
--a; //a becomes 5
When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then only increment it. This can be demonstrated by an example:
#include <stdio.h> int main()
{
int c=2,d=2;
printf(“%d\n”,c++); //this statement displays 2 then, only c incremented by 1 to 3.
Printf(“%d”,++c); //this statement increments 1 to c then, only c is displayed.
Return 0;
}
Output
2
4
33
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes different statements according to test condition whether it is either true or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is returned and if false expression2 is returned.
Let us understand this with the help of a few examples:
int x, y ;
scanf ( “%d”, &x ) ;
y = ( x> 5 ? 3 : 4 ) ;
This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y. The equivalent if statement will be,
if ( x > 5 )
y = 3 ;
else
y = 4 ;
Misc Operators:
There are few other operators supported by c language.
Operator | Description | Example |
sizeof() | It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc. | sizeof(a), where a is integer, will return 4. |
34
& | Returns the address of a variable. | &a; will give actual address of the variable. |
* | Pointer to a variable. | *a; will pointer to a variable. |
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
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 |
35
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |