0% found this document useful (0 votes)
15 views

PPS Notes Unit 1

Uploaded by

Nandini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

PPS Notes Unit 1

Uploaded by

Nandini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

B.

TECH FIRST YEAR (ODD SEMESTER)

SESSION 2024-25

Programming for Problem Solving (BCS 101)

UNIT-1 NOTES
Subject Teacher: Shashi Bhushan Singh Yadav

Department: Computer Science & Engineering


[[[

BABU BANARASI DAS


NORTHERN INDIA INSTITUTE OF TECHNOLOGY
LUCKNOW
5
INTRODUCTION TO ‘C’

What is C?
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and
written by Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like
PL/I, ALGOL, etc.

Features of C:
 C is a high level language having lesser number of keywords than Java or Pascal.
 C is a native language of UNIX, Linux & many of the Windows packages, database programs, graphics
libraries are written using C programs.
 C is portable since it provides standard set of libraries that work on the same way with all machines.
 C is modular, as it supports functions to divide the program into sub-programs.

Getting Started with C:


There is a close analogy between learning English language and learning C language. Following figure
shows this:

Alphabets Words Sentences Paragraphs

Constants /
Alphabets / Digits /
Variables / Instructions Program
Special symbols
Keywords

Character Sets in C:
A character denotes any alphabet, digit or special symbol used to represent information. Following
figure shows the valid alphabets, numbers and special symbols allowed in C.

Alphabets A, B, ….., Y, Z and


a, b, ……, y, z

Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special symbols ~‘!@#%^&*()_-+


=|\{}[]:;"'<>,.?/

 The alphabets, numbers and special symbols when properly combined form constants, variables and
keywords.
6
Structure of a C program:

 Comments: The comments are usually ignored by the compiler so this part is used only to inform about
the necessary descriptions of the program.

Comments are of two types:

(i) // Single line comment


(ii) /* —– Multi line comments ….*/

1. Preprocessor Directives

 Before the compiler runs, the preprocessing takes place.


 The preprocessors are prefix with a symbol #
 Some examples are: #include, #define, #ifdef, #pragma, etc.

2. Function Prototypes

 It is used to inform the compiler that the following functions are defined in this program.
 It specifies the name of the function, arguments or parameters and return type and it ends with a
semicolon.
 Example: int sum(int, int);

3. Global Variables

 Global variables are declared above all the functions


 As the name says, they are available to all the functions of that program

4. Main Function

 main() is the function which is main to the entire program


 Every C program must have a main() function
 When the main program returns nothing, i.e. void, syntax used is: void main() { }

5. User-defined Functions

 User defined functions are defined after the main() function as per the function prototype declared in the
program.
 These functions may also be defined above (before) the main function. In that case, there is no need for
function prototype. For example:

int sum(int a, int b)


{
int x;
x=a+b;
return x;
}
Basic structure of a C Program:

/* Program to display your name*/


#include <stdio.h> // including the standard IO functions like printf(),scanf()
void main() // main() function
{ // start of main() function
printf(“name”); // body of main() function
} // end of main() function

Basic Data Types in C: There are five atomic data types in C: character, integer,
floating-point, double floating-point and valueless (char, int, float, double, and void
respectively).
All other data types in C are based upon one of these types. The size and range of these
data types may vary between processor types and compilers. However, in all cases a character is
1 byte. The size of an integer is usually the same as the word length of the execution
environment of the program. For most 16-bit environments, such as DOS or Windows 3.1, an
integer is 16 bits. For most 32-bit environments, such as Windows NT, an integer is 32 bits.

Following table shows all data types defined by the ANSI/ISO C Standard:

Type Typical Size in Bits Range

char 8 −128 to +127

unsigned char 8 0 to 255

signed char 8 same as char

int 16 −32,768 to +32,767

unsigned int 16 0 to 65,535

signed int 16 same as int

short int 16 same as int

short unsigned int 16 same as unsigned int

short signed int 16 same as short int

long int 32 −2,147,483,648 to +2,147,483,647

long signed int 32 same as long int

long unsigned int 32 0 to 4,294,967,295


float 32 -3.4e38 to +3.4e38

double 64 -1.7e308 to +1.7e308

long double 80 -1.7e4932 to +1.7e4932

NOTE: The sizes & ranges of int, short & long are compiler dependent. Sizes in this table
are for 16-bit compiler.

Tokens in C: Tokens are classified as:


 Keywords
 Identifiers (Variables)
 Constants
 Special Symbols
 Operators

 Keywords in C:
 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.
 The keywords are also called ‘Reserved words’. There are only 32 keywords available in C.
following table lists all the keywords used in C:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

 Identifiers: Identifiers are the variable names declared inside the program.
Definition: A variable is an entity that may change whereas a constant is an entity that doesn’t
change.

Variables in C:
An entity that may vary during program execution is called a variable. Variable names
are names given to locations in memory. These locations can contain integer, real or character
constants. In any language, the types of variables that it can support depend on the types of
constants that it can handle. This is because a particular type of variable can hold only the same
type of constant.
For example, an integer variable can hold only an integer constant, a real variable can
hold only a real constant and a character variable can hold only a character constant.

NOTE:
1. The rules for constructing different types of constants are different. However, for
constructing variable names of all types the same set of rules apply.
2. These rules remain same for all the types of primary and secondary variables. The
‘type’ preceding the ‘variable names’ distinguishes them from each other.

 Rules for Constructing Variable Names


 A variable name is any combination of 1 to 31 alphabets, digits or underscores i.e. _.
Some compilers allow variable names whose length could be up to 247 characters.
 Do not create unnecessarily long variable names as it adds to your typing effort.
 The first character in the variable name must be an alphabet or underscore.
 No commas or blanks are allowed within a variable name.
 No special symbol other than an underscore (e.g. gross_salary) can be used in a variable
name.
 They are case sensitive i.e Var_name is different from var_name

Some valid identifiers are:


avg Value area_of_circle x1
x2 Chennai Sum1 abcd

Some invalid identifiers are:

123 % (value) 27th


1st ab-d Sum of total x&y
 Constants in C: C constants can be divided into two major categories:
1. Primary Constants:
 Integer Constant
 Real Constant
 Character Constant
2. Secondary Constants:
 Array
 Pointer
 Structure
 Union
 Enum, etc.
For constructing these different types of constants certain rules have been laid down. These rules are
as under:

 Rules for Constructing Integer Constants


 An integer constant must have at least one digit.
 It must not have a decimal point.
 It can 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 an integer constant.
 The allowable range for integer constants is -32768 to +32767.

Truly speaking, the range of an Integer constant depends upon the compiler. For a 16-bit compiler
like Turbo C or Turbo C++, this range is –32768 to +32767.

Examples of integer constants: 426, +782, -8000, -7605 etc.

 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.
Following rules must be observed while constructing real constants expressed in fractional form:
 A real constant must have at least one digit.
 It must have a decimal point.
 It could be either positive or negative.
 Default sign is positive.
 No commas or blanks are allowed within a real constant.

Examples of valid real constants (in fractional form): +325.34, 426.0, -32.76, -48.5792 etc.
The exponential form of representation of real constants is usually used if the value of the
constant is either too small or too large. In exponential form of representation, the real constant is
represented in two parts. The part appearing before ‘e’ is called mantissa, whereas the part following
‘e’ is called exponent.
Following rules must be observed while constructing real constants expressed in exponential
form:
 The mantissa part and the exponential part should be separated by a letter e.
 The mantissa part may have a positive or negative sign.
 Default sign of mantissa part is positive.
 The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is positive.
 Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

Examples of valid real constants (in exponential form): +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5 etc.

 Rules for Constructing Character Constants


 A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas.
 The maximum length of a character constant can be 1 character.

Examples of valid character constants: 'A', 'I', '5' '=', '+' etc.

 Special Symbols: Special symbols are the characters used other than alphabets &
digits such as:

~ ‘ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' < > , . ? / etc.

 Operators in C: To perform various operations, a large verity of operators is available


in C.

Arithmetic Operator Action Relational Operator Action

− Subtraction == Equal to
+ Addition != Not equal to
* Multiplication > Greater than
/ Division < Less than
% Modulus >= Greater than or equal to
<= Less than or equal to
Logical Operator Action Bitwise Operator Action

&& Logical AND & Bitwise AND


|| Logical OR | Bitwise OR
! Logical NOT ^ Bitwise XOR
~ One’s complement
<< Shift left
>> Shift right
Unary Operator Action

- Unary minus
++ Increment
–– Decrement

Assignment Operator Action

= “Assignment” of value on the right side of it to the variable on the left side.

Conditional operator Action

?: Condition test? True : false

e. g. x = (a>b)? a : b; means if the condition a> b is true then a is assigned to x, if


false then b is assigned to x.
The First C Program: Armed with the knowledge about the types of variables,
constants, keywords & operators, the next logical step is to combine them to form instructions.

Before we begin with our first C program, do remember the following rules that are applicable to
all C programs:

 Each instruction in a C program is written as a separate statement. Therefore a complete C


program would comprise of a series of statements.
 The statements in a program must appear in the same order in which we wish them to be
executed; unless of course the logic of the problem demands a deliberate ‘jump’ or transfer
of control to a statement, which is out of sequence.
 Blank spaces may be inserted between two words to improve the readability of the
statement. However, no blank spaces are allowed within a variable, constant or keyword.
 All statements should be entered in small case letters since C is a case sensitive language..
 C has no specific rules for the position at which a statement is to be written. That’s why it is
often called a “free-form language”.
 Every C statement must end with a semicolon (;). Thus ; acts as a statement terminator.

Let us now write down our first C program. It would simply calculate simple interest for
a set of values representing principle, number of years and rate of interest.

/* Calculation of simple interest */


main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n=3;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}

Now a few useful tips about the program...


1. Comment about the program should be enclosed within /* */. For example, the first
statement in our program is comment.
2. Though comments are not necessary, it is a good practice to begin a program with a
comment indicating the purpose of the program.
3. Any number of comments can be written at any place in the program. For example, a
comment can be written before the statement, after the statement or within the statement
as shown below:

/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;
4. Sometimes it is worthwhile mentioning the purpose of the statement (or a set of
statements) using a comment. e.g.

/* formula for simple interest */


si = p * n * r / 100 ;

5. main( ) is a collective name given to a set of statements. Technically speaking main( ) is


a function. Every C program must start with this function. Every function has a pair of
parentheses ( ) associated with it. All statements that belonging to a function are enclosed
within a pair of braces { } as shown below.

main( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}

6. Any variable used in the program must be declared before using it. e.g.,

int p, n ;
float r, si ;

7. Any C statement always ends with a ; For example,

float r, si;
r = 8.5;

8. In the statement,

si = p * n * r / 100 ;

* and / are the arithmetic operators. (The arithmetic operators available in C are +, -, *, /
and %).

9. Once the value of si is calculated it needs to be displayed on the screen. Unlike other
languages, C does not contain any instruction to display output on the screen. All output
to screen is achieved using readymade library functions such as printf( ).

 The general form of printf( ) function is:

printf ( "format strings", list of variables ) ;

Where format strings can contain format specifiers and/or other strings.
Format Specifiers:
 Format specifiers are used to input & output data types.
 The scanf() & printf() functions accepts a wide variety of format specifiers, some of
them are shown in the following table:

Data type Format Specifier


short signed int %d
short unsigned int %u
long singed int %ld
long unsigned int %lu
unsigned hexadecimal int %x
unsigned octal int %o
float %f
double %lf
signed character %c
unsigned character %c
string %s
Ques- If a five digit number( less than 32767 ) is input through the keyboard, write a program to reverse
this number.

Solution-
/* Program to reverse the 5-digit number*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int num,a;
long int rev=0; /*Initialised to zero otherwise it will contain garbage value*/
clrscr( );
printf(“Enter a five digit Number: ”);
scanf(“%d”,&num);

a=num%10; /*Last digit*/


num=num/10;
rev=rev*10+a;

a=num%10; /*4th digit*/


num=num/10;
rev=rev*10+a;

a=num%10; /*3rd digit*/


num=num/10;
rev=rev*10+a;

a=num%10; /*2nd digit*/


num=num/10;
rev=rev*10+a;

a=num%10; /*1st digit*/


rev=rev*10+a;

printf(“\n The reversed number is %ld ”, rev);


getch();
}

You might also like