Unit-i Introduction to Programming
Unit-i Introduction to Programming
INTRODUCTION TO PROGRAMMING
CONTENT
UNIT- I
Terminal Symbol
Start The oval shape symbol always begins and ends the flowchart
The Start symbol have only one flow line but not entering flow line
Stop
The stop symbol have an entering flow line but not exit flow line
Process symbol
Decision Symbol
Yes The diamond symbol is used in a flowchart to indicate the point at
which a decision has to be made and a branch of two or more
alternatives are possible
There are always two exits from a decision symbol - one is labeled
No Yes or True and other labeled No or False.
Connector Symbol
A connector symbol is represented by a circle with a letter or digit
n inside to specify the link.
Used if the flowchart is big and needs continuation in next page
n
Let us take a small problem and see how can we write an algorithm using natural
language and draw flowchart for the same.
Illustration
Consider the problem of finding the largest number in a given set of three numbers.
Algorithm
1. Get three numbers from the user
2. Compare the first two numbers
3. The larger of the first two numbers is compared with the third number
4. The larger number obtained as a result of the above execution is the largest number
5. Print the that number as output
Start
Yes Yes
If (a>b) If (a>c) Print ‘a’ as the largest
No No
Yes
Stop
Fig 1. Flow chart for the program-finding the largest of 3 given no. s
A brief history
C is a programming language developed at “AT & T’s Bell Laboratories” of USA in 1972.
It was written by Dennis Ritchie (Fig 2).
Features of C
Portability
Modularity
Extensible
Speed
Flexibility
Rich Library
Advantages of C
1. C programming is the building block for many other high level programming
languages existing today
5. Since C is a structured language, we can split any big problem into several sub
modules. Collection of these modules makes up a complete program. This modular
concept makes the testing and debugging easier
Structure of a C program
Documentation Section
Preprocessor Section
Definition Section
main()
{
Declaration Section
Execution Section
}
Sub Program Section
{
}
Prepared By: Shashi Bhushan Singh Yadav Page | 5
Documentation Section:
Preprocessor Section:
It is used to link system library files, for defining the macros and for defining the
conditional inclusion
Eg: #include<stdio.h>, #include<conio.h>, #define MAX 100, etc.,
The variables that are used in more than one function throughout the program are
called global variables
Should be declared outside of all the functions i.e., before main().
main():
Every ‘C’ program must have one main() function, which specifies the starting of a ‘C’ program.
It contains the following two parts
Declaration Part:
This part is used to declare the entire variables that are used in the executable part of
the program and these are called local variables
Execution Part:
Sub programs are basically functions are written by the user (user defined functions)
They may be written before or after a main () function and called within main ()
function
This is optional to the programmer
Example Program
/* addition.c – To find the average of two numbers and print them out
together with their average */
#include <stdio.h>
void main( )
{
int first, second;
float avg;
printf("Enter two numbers: ");
scanf("%d %d", &first, &second);
printf("The two numbers are: %d, %d", first, second);
avg = (first + second)/2;
printf("Their average is %f", avg);
}
Type the program and edit it in standard ‘C’ editor and save the program with .c as an
extension.
This is the source program
This is the process of converting the high level language program to Machine level
Language (Equivalent machine instruction) -> Compiler does it!
Errors will be reported if there is any, after the compilation
Otherwise the program will be converted into an object file (.obj file) as a result of the
compilation
After error correction the program has to be compiled again
Before executing a c program, it has to be linked with the included header files and
other system libraries -> Done by the Linker
This is the process of running (Ctrl + F9) and testing the program with sample data. If
there are any run time errors, then they will be reported.
Compilation
and Linking
C Tokens
C tokens, Identifiers and Keywords are the basic elements of a C program. C tokens are the
basic buildings blocks in C. Smallest individual units in a C program are the C tokens. C tokens
are of six types. They are,
1. Keywords
Keywords are those words whose meaning is already defined by Compiler. They cannot be
used as Variable Names. There are 32 Keywords in C. C Keywords are also called
as Reserved words. There are 32 keywords in C. They are given below:
do if static while
2. Identifiers
Identifiers are the names given to various program elements such as variables , arrays &
functions. Basically identifiers are the sequences of alphabets or digits.
3. Constants
The constants refer to fixed values that the program may not change or modify during
its execution. Constants can be of any of the basic data types like an integer constant, a
floating constant and a character constant. There is also a special type of constant called
enumeration constant.
Eg:
4. Strings
The symbols other than alphabets, digits and white spaces for example - [] () {} , ; : * … = #
are the special symbols.
6. Operators
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
Arithmetic Operators
1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
1. C allows only one variable on left hand side of = eg. c=a*b is legal, but a*b=c is not
legal.
2. Arithmetic operations are performed on the ASCII values of the characters and not on
characters themselves
3. Operators must be explicitly written.
4. Operation between same type of data yields same type of data, but operation between
integer and float yields a float result.
Example Program
#include <stdio.h>
int main()
{
int m=40,n=20, add,sub,mul,div,mod;
add = m+n;
sub = m-n;
mul = m*n;
div = m/n;
mod = m%n;
Addition of m, n is : 60
Subtraction of m, n is : 20
Multiplication of m, n is : 800
Division of m, n is : 2
Modulus of m, n is : 0
Relational Operators
Relational Operators are used to compare two or more operands. Operands may
be variables, constants or expression
5 == is equal to m == n
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf(“m and n are equal”);
}
else
{
printf(“m and n are not equal”);
}
}
Output
Logical Operators
Logical Operators are used to combine the results of two or more conditions. It is
also used to test more than one condition and make decision.
#include <stdio.h>
int main()
{
int a=40,b=20,c=30;
if ((a>b )&& (a >c))
{
printf(“ a is greater than b and c”);
}
else
if(b>c)
printf(“b is greater than a and c”);
else
prinf(“c is greater than a and b”);
}
Output
Conditional Operator
It itself checks the condition and executed the statement depending on the condition.
Syntax:
Condition? Exp1:Exp2
Example:
X=(a>b)?a:b
The ‘?:’ operator acts as ternary operator. It first evaluate the condition, if it is true then
exp1 is evaluated, if condition is false then exp2 is evaluated. The drawback of
Assignment operator is that after the ? or : only one statement can occur.
#include <stdio.h>
int main()
{
int x,a=5,b=3;
x = (a>b) ? a : b ;
printf(“x value is %d\n”, x);
}
Output
x value is 5
Bitwise Operators
Bitwise Operators are used for manipulation of data at bit level. It operates on integer
only.
Output
Special operators:
sizeof () operator:
#include<stdio.h>
int main()
{
int ivar = 100;
char cvar = 'a';
float fvar = 10.10;
printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}
Output :
214
In the above example we have passed a variable to size of operator. It will print the value of
variable using sizeof() operator.
#include<stdio.h>
int main()
{
printf("%d", sizeof(int));
printf("%d", sizeof(char));
printf("%d", sizeof(float));
return 0;
}
Output :
214
printf("%d", sizeof(10));
printf("%d", sizeof('A'));
printf("%d", sizeof(10.10));
return 0;
}
Output :
214
In this example we have passed the constant value to a sizeof operator. In this case sizeof
will print the size required by variable used to store the passed value.
Comma(,) Operator:
1. Comma Operator has Lowest Precedence i.e it is having lowest priority so it is evaluated
at last.
2. Comma operator returns the value of the rightmost operand when multiple comma
operators are used inside an expression.
3. Comma Operator Can acts as –
Operator : In the Expression
Separator: Function calls, Function definitions, Variable declarations and Enum
declarations
Example:
#include<stdio.h>
void main()
{
int num1 = 1, num2 = 2;
int res;
res = (num1, num2);
printf("%d", res);
}
Output
2
In this case value of rightmost operator will be assigned to the variable. In this case value of
num2 will be assigned to variable res.
i:1
Explanation:
i = 1,2,3;
#include<stdio.h>
int main()
{
int i;
i = (1,2,3);
printf("i:%d\n",i);
return 0;
}
Output:
i:3
Explanation:
i = (1,2,3);
1. Bracket has highest priority than any operator.
2. Inside bracket we have 2 comma operators.
3. Comma operator has associativity from Left to Right.
4. Comma Operator will return rightmost operand
i = (1,2,3) Assign 3 to variable i.
#include<stdio.h>
#include< conio.h>
void main()
Output:
Computer
You might feel that answer of this statement should be “Programming” because comma
operator always returns rightmost operator, in case of printf statement once comma is read
then it will consider preceding things as variable or values for format specifier.
#include<stdio.h>
#include< conio.h>
void main()
{
int choice = 2 ;
switch(choice)
{
case 1,2,1:
printf("\nAllas");
break;
case 1,3,2:
printf("\nBabo");
break;
case 4,5,3:
printf("\nHurray");
break;
}
}
Output :
Babo
#include<stdio.h>
int main()
{
int i,j;
for(i=0,j=0;i<5;i++)
{
printf("\nValue of J : %d",j);
j++;
}
return(0);
}
Output:
Value of J : 0
Value of J : 1
Value of J : 2
Value of J : 3
Value of J : 4
#include<stdio.h>
int main()
{
int num1,num2;
int a=10,b=20;
return(0);
}
Note : Use of comma operator for multiple declaration in same statement.
Variable:
C has a concept of 'data types' which are used to define a variable before its use. The
definition of a variable will assign storage for the variable and define the type of data that will be
held in the location.
int
float
double
char
Scope of a variable
A scope in any programming is a region of the program where a defined variable can have
its existence and beyond that variable cannot be accessed. There are three places where
variables can be declared in C programming language:
Local Variables
Variables that are declared inside a function or block are called local variables. They
can be used only by statements that are inside that function. Local variables are not known to
functions outside their own. Following is the example using local variables. Here all the
variables a, b and c are local to main() function.
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
}
Global Variables
Global variables are defined outside of a function, usually on top of the program. The global
variables will hold their value throughout the lifetime of your program and they can be
accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for
use throughout your entire program after its declaration. Following is the example using global
and local variables:
#include <stdio.h>
/* global variable declaration */
int g;
main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
}
If an arithmetic expression is given, there are some rules to be followed to evaluate the
value of it. These rules are called as the priority rules. They are also called as the hierarchy
rules. According to these rules, the expression is evaluated as follows;
Rule 1 :- If an expression contains parentheses , the expression within the parentheses will be
performed first. Within the parentheses , the priority is to be followed.
Rule 2 :- If it has more than parentheses , the inner parenthesis is performed first.
Rule 3:- If more than one symbols of same priority , it will be executed from left to right.
Type conversion is the method of converting one type of data into another data type.
2. Type casting
float a,b,c;
a=10,b=3;
c=a/b
output= > c= 3.3 {4 bytes(float) (All the variables are same datatype}
Eg.2
int a,b,c;
a=10,b=3;
c=a/b;
Eg.3
int a;
float b,c;
a=10,b=3;
c=a/b;
Type casting
This method is used,when user wants to change the type of the data.
(datatype)operand
Eg.1
z=(float)x/y;(ie z=10.0/3;)
output=>z=3.3(float)
Eg:2
int x=10,y=3;
z=x/(float)y;(ie z=10/3.0;)
output=>3.3(float)
Prepared By: Shashi Bhushan Singh Yadav Page | 29
The type of the x is not changed, only the type of the value can be changed
Since the type of conversion is done explicitly, this type conversion is called as
explicittype conversion
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
In ‘c’ language several functions are available for input/output operations. These
functions are collectively known as the standard I/O library.
Example:
Syntax: putchar(charvariable);
char x; putchar(x);
#include<stdio.h>
main()
{
char scientist[40];
puts("Enter name");
gets(scientist);
puts("Print the Name");
puts(scientist);
}
output:
Enter Name:Abdul Kalam
Print the Name:Abdul Kalam
Output Function : To print the value on the screen or to store the value on the file, the output
functions are used. printf() is the function which is use to display the output on the screen.
The General format of the printf() function is
printf(“control string”,variable1,variable2,…..);
Example
Formatted Output of Integer: Similar to formatted input , there is a formatted output also to
have the output in a format manner.
In this control string consists of three types of items.
Characters that will be printed on the screen as they appear
Format specification that define the output format for display of each item
Escape sequence characters such as
\n – new line
printf(“%-6d”,9876);
output:
1 2 3 4 5 6
9 8 7 6
printf(“%06”,9876);
output:
1 2 3 4 5 6
0 0 9 8 7 6
scanf(“%2.1f %5.2f”,&num1,&num2);
data line is 50.1 31425.20
output:
1 2 3 4 5 6 7
9 8 . 7 6
printf(“%-7.2f ”,y);
output:
1 2 3 4 5 6 7
9 8 . 7 6
where,
%s – A sequence of characters can be displayed.
%c – A single character can be displayed.
The character will be displayed right-justified in the field of w, left-justified by placing
a minus sign before the integer w.
Example:
Char x = ‘a’;
Char name[20] = “anil kumar gupta”;
Printf(“%c”, x); // output: a
Printf(“%s”,name); // output: anil kumar gupta
Printf(“%20s”, name);
Output:
1 2 3 4 5 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20
a n i l k u m a r g u p t a
Printf(“%-20.10s”, name);
Output:
1 2 3 4 5 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20
a n i l k u m a r
Printf(“%.5s”, name);
Output:
g u p t a
1. Write the algorithm a) to calculate the average of three numbers. b) to check whether an
entered number is odd or even.
2. Draw flowchart to find whether the given number is a prime number.
3. Write a program in ‘C’ to display your details like Name, Regno, Branch, 10 th marks, 12th
marks and your native state.
4. Write a program in ‘C’ to get two numbers as input from the user and then swap them.
5. Write a program in ‘C’ to print the numbers from 1 to 10 and their squares
6. Find the value for the following expression with a=10,b=5 and c=1
i) a>9 && b!=3
ii) a==5 || b!=3
iii) !(a>14)
iv) !(a>9 && y!=23)
v) % &&b != 8|| 0
vi) 3<<2
vii) 4>>3
7. What will be output of the following program?
#include<stdio.h>
int main()
{
printf("%d %d %d",sizeof(3.14),sizeof(3.14f),sizeof(3.14L));
return 0;
}
8. What will be output of the following program?
#include<stdio.h>
int main()
{
int a;
a=sizeof(!5.6);
printf("%d",a);
return 0;
}
9. Write a c program to find the grade of a student using operators.
10. Write a c program to perform calculator operation using operators.
11. Write a c program to find the roots of the Quadratic Equation.