CP Notes CHPTR 3
CP Notes CHPTR 3
3.1 Fundamental of C
Program is a set of instructions
to interact with computer. The
programs are written in
programing language. C is a
procedural programming
language developed at AT &
T’s Bell Laboratories of USA in
1972. It was designed and
written by a man named Dennis
Ritchie.
3.3 Keywords
Keywords are the predefined reserved (built-in) words whose meaning has already been defined
to the c compiler. A programmer can’t use the keywords for other task than the task for which it
has been defined. For example: a programmer can’t use the keyword for variable names.
3.5 Constants
Constant in C refers to fixed values
that do not change during execution
of a program.
a. Integer Constants: It refers to the sequence of digits with no decimal points. The three
kinds of integer constants are:
Decimals: Decimal numbers are set of digits from 0 to 9 with leading +ve or –ve
sign. For example: 121, -512 etc.
Octals: Octal numbers are any combination of digits from set 0 to 7 with leading 0.
For example: 0121, 0375 etc.
Hexadecimals: Hexadecimal numbers are the sequence of digits preceding 0X or
0x. For example: 0xAB23, 0X787 etc.
b. Real or Floating point Constants: They are the numeric constants with decimal points.
The real constants are further categories as:
Fractional Real constant: They are the set of digits from 0 to 9 with decimal
points. For example: 394.7867, 0.78676 etc.
Exponential Real constants: In the exponential form, the constants are
represented in two form: Mentissia E exponent; Where, the Mentissia is
either integer or real constant but the exponent is always in integer form. For
example: 21565.32 = 2.156532 E4, where E4 = 104.
c. Character constant: Character constant are the set of alphabets. Every character has some
integer value known as American Standard Code for Information Interchange (ASCII).
The character constants are further categories as:
Single character constant: It contains a single character enclosed with in a pair of
single cade mark (‘ ’). Thus, ‘X’, ‘5’ are characters but X, 5 are not.
String constant: String constants are a sequence of characters enclosed in double
quotes marks (“ ”). The character may be letters, numbers, special symbols or
blank spaces. For example: “Hello”, “X+Y”. Note: ‘x’ ≠ “x”
In the C programming language, a data type refers to an extensive system used for declaring
variables or functions of different types. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted.
Type Qualifiers
Data type qualifiers add additional information to the data types. They are: short, long, signed or
unsigned. A number of qualifiers or modifiers may be assigned to any basic data type to vary the
number of bits utilized and the range of values represented by that data type. Here, short int may
require less space than an int or it may require the same amount of memory. Similarly, a long int
may require the same amount of memory as an int or it may require more memory, never less
than int. For example, int = 2 bytes, short int may be 1 byte or 2 bytes, int = 2 bytes, long int may
be 2 bytes or 4 bytes. The actual number of bytes used in the internal storage for these data types
depends on the machine being used.
Type casting
When an operator is used to manipulate operands of different data type then each operand should
have same data type to take operation because the final result must be in one data type. For
example, the given expression is: z = int x + float y; then the data type of z must be
only one. To handle such type of problems, the type conversion and type casting are introduced.
C provides two types of type conversions:
Implicit type conversion: In implicit type conversion, if the operands of an expression
are of different types, the lower data type is automatically converted to the higher data
type before the operation evaluation. The result of the expression will be of higher data
type. The data types of the operand are changed according as the rule – CIFDL
Explicit type conversion: In explicit type conversion, the user has to enforce the
compiler to convert one data type to another data type by using typecasting operator. This
method of typecasting is done by prefixing the variable name with the data type enclosed
within parenthesis.
Syntax: (data type) variable/expression/value;
3.6 Variables
A constant is a quantity (fixed value) that does not change during program
execution. A constant always remains fixed. Constant supplied by the user is
stored in block of memory by the help of variable. A variable is a quantity
whose value may change during program execution. Consider an expression:
2*x + 3*y = 5. In this expression the quantities x and y are variable. A
variable is a named location in memory that is used to hold a constant value.
Declaring variable
After defining suitable variable name, we must declare them before used in our program. The
declaration deals with two things:
It tells the compiler what the variable name is.
It specifies what type of data the variable can hold.
A. Arithmetic operators: Arithmetic operators are used for performing most common
arithmetic (mathematical) operations such as addition, multiplication, division and modulus.
For example: Assume variable A holds 10 and variable B holds 20 then:
Operator Name Example
+ Addition A + B will give 30
- Subtraction A - B will give -10
* Multiplication A * B will give 200
/ Division B / A will give 2
% Modulo division B % A will give 0
++ Increment A++ will give 11
-- Decrement A-- will give 9
Note: The increment or decrement operator may be pre increment (++k) or post increment
(k++). Similar the pre decrement (--k) or post decrement (k--).
B. Logical operators
Expressions which use logical operators are evaluated to either true or false. For example:
Assume variable A holds 1 and variable B holds 0 then:
D. Relational operators
These operators are used to form relational expressions, which evaluates to either true or
false. (True – 1, false – 0). Assume variable A holds 10 and variable B holds 20 then:
F. Special operators
Operator Name Example
sizeof() Sizeof sizeof(a), where a is integer, will return 2.
& address of &a; will give actual address of the variable.
* Pointer *a; will pointer to a variable.
?: Conditional If (Condition) ? TRUE case : FALSE case
Example: big = (a>b)? a: b;
Preprocessor directives
3.8 The first C program
main()
The C is a procedural (function) oriented programming {
language. A function is a block of statements to perform Statement 1;
a given task. Each function would have a series of Statement 2;
statements equipped with the variables, constants, ……………………………
keywords and operators. Each instruction in C program is Statement n;
regarded and written as a separate statement. The general }
structure of C program would be of following types.
1. Comments
A comment is a descriptive sentence written in a program. Although a comment is not
compulsory in a program but it is good practice as it makes a program simpler to understand
the logic, more readable, correcting the future errors, and enhancements features. A
comments are not executable statements therefore the compilers ignore the comments.
Comments in C can be written in two ways:
Single line comment: The comment starts with //. For e.g. main() // start the
program
Multiline comment: The comment starts with /* and end with */.
For e.g. main() /* Main function
start the program */
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 7
stdio.h (standard input output header file) used for standard function like
o printf() – output function used to print a message or value of a variable on the
screen.
o scanf() – input function used to input a value through the keyboard.
o putchar() – output function used to print a single character
o getchar() – input function used to input a single character
o fprintf() – output function used to print a file
o fscanf() – input function used to input a file
string.h: Includes the string functions like
o puts() –output function used to print a string
o gets() – input function used to input a string
o strlen() – find the length of given sting
o strcpy() – cppy string from variable to another
math.h: Includes the mathematical functions like
o sqrt() – to find the square root of a number
o pow() – to calculate a value raised to power
o abs() – to find the absolute value of an integer
o log() – to calculate the natural logarithm, etc.
conio.h (console input output header file) used for display controlling function like
o getch(); – Function used to hold the output value of program until pressing any
key. It doesn’t echo character.
o getche(); – It echoes (show)the character.
o clrscr(); – Function used to clear the screen holding the previous values.
Console: A user typically interacts with a console application using only a keyboard and
display screen, as opposed to GUI applications, which normally require the use of a mouse or
other pointing device.
3. main( )
C program may consist of more than one function. If a program consists only one function it
must be main() that shows the beginning of a program. It is not possible to write a program
without main() because program execution always starts with this function. The main( ) is not
followed by comma or semicolon.
The function main( ) encloses all the statements within a pairs of braces {…..}. Each line
written between the braces is a statement. Every statement is terminated by semicolon. The
semicolon at the end of a statement separates one statement from other. More than one
statement can be written on the same line by separating them with individual semi column.
However, it is good practice to write one statement per line.
Example:
scanf (“%c %d %f”, &ch, &i, &x);
scanf (“%[^\n]s”, str); /*accepts all inputs including space. Stops when it
encounters new line.*/
scanf (“%d=%d”, &a, &b); /*delimiter between two input is = (10=20)*/
scanf (“%2d%5d”,&a,&b); /*if the input is 12345 & 10, a=12 & b=345 if the
input is 12 & 3456, a= 12 & b=3456*/
scanf (“%d%d”, &a,&b); /*if the input is 12345 & 10, a=12345 & b=10*/
printf(): The library function printf () is used to output the values. This function can be
used in variety of form as described below:
a. Character that will be printed on the screen as they appeared
Syntax: printf (“control string”, arg1, ..argn);
Example: printf (“Enter name of student”);
b. Format specification that define the output format for display of each item
Syntax: printf (“control string”);
Example: printf (“%d”, a);
c. Escape sequence character such as new line (\n), tab (\t) bell (\b) etc.
Example: printf (“\t”);
3. If a number is input through the keyboard. WAP to find its square root.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main( )
{
int n, z;
clrscr( );
printf(“enter a number”);
scanf(“%d”, &n);
z=sqrt(n);
printf(“\nthe square root of %d is %d”, n, z);
getch( );
}
4. Three quantities principle, time and rate are input through the keyboard. WAP to find
simple interest.
#include<stdio.h>
#include<conio.h>
main( )
{
float p, t, r, si;
clrscr( );
printf(“enter the principle, time and rate”);
scanf(“%f%f%f”, &p, &t, &r);
si=(p*t*r)/100;
printf(“\n the simple interest=%f”,si);
getch( );
}
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 11
void main()
{
float p,t,r, a, i;
printf("ENTER PRINCIPAL, RATE:");
scanf("%f%f",&p,&r);
printf("ENTER THE TIME IN YEAR:");
scanf("%f",&t);
a = p * pow(((100+r)/100),t);
i = a - p;
printf("\n THE AMOUNT IN TIME :%f Year is: %f",t, a);
printf("\n The interest is: %f",i);
getch();
}
6. Two numbers are input through the keyboard. WAP to find addition, subtraction,
multiplication, quotient and remainder after division.
#include<stdio.h>
#include<conio.h>
main( )
{ int x, y, z1, z2, z3, z4, z5;
clrscr( );
printf(“Enter two numbers”);
scanf(“%d %d”, &x, &y);
z1=x+y;
z2=x-y;
z3=x*y;
z4=x/y;
z5=x%y;
printf(“summation=%d, difference=%d, multiplication=%d,
quotient=%d and remainder=%d”, z1, z2, z3, z4, z5);
getch( );
}
7. Temperature of a city in centigrade is input through the keyboard. WAP to convert this
temperature into Fahrenheit degree.
#include<stdio.h>
#include<conio.h>
main( )
{
float c, f;
clrscr( );
printf(“enter the temperature in centigrade”);
scanf(“%f”, &c);
f=1.8*c+32;
printf(“the temperature in Fahrenheit = %f”, f);
getch( );
}
9. Write a program to find the area & perimeter of a rectangle and area & circumference of
a circle.
#include<stdio.h>
#include<conio.h>
#include<math.h> /*for function pow( )*/
main( )
{
float l, b, area1, perimeter, rad, area2, cir;
clrscr( );
printf(“Enter length, breadth of a rectangle:”);
scanf(“%f%f”, &l, &b);
printf(“Enter radius of a circle:”);
scanf(“%f”, &rad);
area1 = l*b;
perimeter = 2*(l+b);
area2 = 3.14*pow(rad, 2);
cir = 2*3.14*rad;
printf(“Results of rectangle:”);
printf(“\nAarea = %f m2\n”,area1);
printf(“ Perimeter = %f”, perimeter);
printf(“\nResults of circle:”);
printf(“\nArea = %f”, area2);
printf(“\nCircumference = %f”, cir);
getch();
}
10. If a 4 digit number is input through the keyboard. WAP to find reverse.
#include<stdio.h>
#include<conio.h>
main( )
{
int n, d1, d2, d3, d4, rev=0;
clrscr( );
printf(“Enter a 4 digit number”);
scanf(“%d”, &n);
d1=n%10;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 13
n=n/10;
d2=n%10;
rev=rev*10+d2;
n=n/10;
d3=n%10;
rev=rev*10+d3;
n=n/10;
rev=rev*10+n;
printf(“reverse=%d”, rev);
getch( );
}
11. The baic salary of an employee is input through the keyboard. WAP to determine his gross
salary if his dearness allowence is 40% of his basic salary, houserent allowness is 20% of
his basic salary.
#include<stdio.h>
#include<conio.h>
void main()
{
float bs,da,hr,gs;
printf(“ENTER THE BASIC SALARY:”);
scanf(“%f”,&bs);
ds=(40/100)*bs;
hr=(20/100)*bs;
gs=bs+ds+hr;
printf(“THE BASIC SALARY OF THE EMPLYOEE IS %f”,gs);
getche();
}
12. Write a Program to find the area of triangle when three sides of a triangle are given.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,s,area;
printf ("\nENTER THE THREE SIDES OF A TRINAGLE:");
scanf ("%f%f%f",&a,&b,&c);
s = (a+b+c)/2;
area = sqrt((s* (s-a)*(s-b)*(s-c)));
printf("\n Sides of triangle are: \na=%f\nb=%f\nc=%f",a,b,c);
printf("\n The area of triangle is:%f sq units",area);
getch();
}