PPS 1st Unit
PPS 1st Unit
PPS 1st Unit
me/jntuh
LECTURE NOTES
FOR
Problem Solving Through Programming (in C)
UNIT – I
1. Introduction to Computers:
2: Computer System
3. Computing Environment
4. Computer Languages
6. Compiler
7. Error in C
9. Introduction to C
13. Operators
Introduction to Computers:
Computer Systems:
Computer Hardware
Input device:
Data or instruction are entered into the computer with the help of input devices.
Ex: keyboard, Mouse, Scanner.
Output device :
The result given by the computer after processing data is called as output. the
output device shows or plays the result after the input has been proceed.
Ex: Monitor, Printer, Speaker are output devices .
Computer Memory:
Computer memory is any physical device capable of storing information temporarily or
permanently.
Primary Memory
• Primary memory is computer memory that a computer accesses directly.
• Primary memory is a volatile storage mechanism.
• It may be random access memory (RAM), cache memory or data buses.
• primarily associated with RAM.
• Primary memory is considered faster than secondary memory
Fig3: Ram
Processor
Computer Software
System software:
• System software manages the computer resources .It provides the interface
between the hardware and the users.
• These programs are divided into three classes: the operating system, system
support, and system development.
• The operating system provides services such as a user interface, file and
database access, and interfaces to communication systems such as Internet
protocols.
• System support software provides system utilities and other operating services.
Examples of system utilities are sort programs and disk format programs.
• The language translators converts user programs into machine language for
execution, debugging tools to ensure that the programs are error free and
computer –assisted software engineering (CASE) systems.
Application software
• Application software, on the other hand is directly responsible for helping users
solve their problems.
Computing Environments:
• In the early days of computers, there was only one environment: the main frame
computer hidden in a central computing department. With the advent of mini
computers and personal computers, the environment changed, resulting in
computers on virtually every desktop.
• In 1971, Marcian E.Hoff, working for Intel, combined the basic elements of the
central processing unit into the microprocessor.
• The first computer on a chip was the Intel 4004. If we are using a personal
computer, all of the computer hardware components are tied together in our
personal computer (PC).
2 Time-Sharing Environment:
3 Client/Server Environment
4 Distributed Computing
Computer Languages:
• To write a program for a computer, we must use a computer language. Over the
years computer languages have evolved from machine languages to natural
languages.
Machine Languages
• Instructions in machine language must be in streams of 0’s and 1’s because the
internal circuits of a computer are made of switches transistors and other
electronic devices that can be in one of two states: off or on. The off state is
represented by 0 , the on state is represented by 1.
Symbolic Languages:
• The early programming languages simply mirror to the machine languages using
symbols of mnemonics to represent the various machine language instructions
because they used symbols, these languages were known as symbolic
languages.
• High level languages are portable to many different computers, allowing the
programmer to concentrate on the application problem at hand rather than the
intricacies of the computer.
• High-level languages are designed to relieve the programmer from the details of
the assembly language.
• High level languages share one thing with symbolic languages; they must be
converted into machine language.
• The process of converting them is known as compilation.
The first widely used high-level languages, FORTRAN (FORmula TRANslation) was
created by John Backus and an IBM team in 1957;it is still widely used today in
scientific and engineering applications. After FORTRAN was COBOL (Common
Business-Oriented Language). Admiral Hopper was played a key role in the
development of the COBOL Business language. C is a high-level language used for
system software and new application code.
Compiling Programs:
• The code in a source file stored on the disk must be translated into machine
language; this is the job of the compiler.
• The ‘c’ compiler is two separate programs. The preprocessor and the translator.
• The code generated after compilation is called object code.
The preprocessor reads the source code and prepares it for the translator. While
preparing the code, it scans for special instructions known as preprocessor
commands.
After the preprocessor has prepared the code for compilation, the translator
convert the program into machine language and generate the object code that is,not
executable because it does not have the required C and other functions included.
Linking Programs:
Executing Programs:
In a typical program execution, it reads data for processing, either from the user or
from a file. After the program processes the data, it prepares the output. At output can
be to the user’s monitor or to a file. When the program has finished its job, it tells the
operating system, which then removes the program from memory.
Interpreter Vs Compiler
Interpreter Compiler
Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.
It takes less amount of time to analyze It takes large amount of time to analyze
the source code but the overall the source code but the overall
execution time is slower. execution time is comparatively faster.
Continues translating the program It generates the error message only after
until the first error is met, in which scanning the whole program. Hence
case it stops. Hence debugging is easy. debugging is comparatively hard.
Errors in C
• Error is an illegal operation performed by the user which results in abnormal
working of the program.
• Programming errors often remain undetected until the program is compiled or
executed.
• Some of the errors restrict the program from getting compiled or executed. Thus
errors should be removed before compiling and executing.
Types of Error
1. Syntax errors:
• Errors that occur when you violate the rules of writing C syntax are known as
syntax errors.
• This compiler error indicates something that must be fixed before the code can
be compiled.
• All these errors are detected by compiler and thus are known as compile-time
errors.
2. Run-time Errors :
• Errors which occur during program execution(run-time) after successful
compilation are called run-time errors.
• One of the most common run-time error is division by zero also known as
Division error.
• These types of error are hard to find as the compiler doesn’t point to the line at
which the error occurs.
3. Logical Errors :
• On compilation and execution of a program, desired output is not obtained
when certain input values are given.
• These types of errors which provide incorrect output but appears to be error free
are called logical errors.
• These are one of the most common errors done by beginners of programming.
ALGORITHM:
Step 1: Start
Step 2: Read the two numbers in to a,b
Step 3: c=a+b
Step 4: write/print c
Step 5: Stop.
PSEUDOCODE:
FLOW CHART:
symbols such as Rectangles, Diamonds, Ovals and small circles. These symbols are
connected by arrows called flow lines.
(Or)
The diagrammatic representation of way to solve the given problem is called flow chart.
The following are the most common symbols used in drawing flowcharts:
start
Read A and B
value
C=A+B
Print C
Stop
❖ Reliability
❖ Portability
❖ Flexibility
❖ Interactivity
❖ Modularity
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.
❖ Database systems
❖ Graphics packages
❖ Word processors
❖ Spreadsheets
❖ Operating system development
❖ Compilers and Assemblers
❖ Network drivers
❖ Interpreters
Structure of C program
➢ Documentation section
➢ Link Section
➢ Definition Section
➢ Global declaration section
➢ Function prototype declaration section
➢ Main function
Tokens in C
OPERATORS
SPECIAL
STRINGS
TOKENS
C CONSTANTS
IDENTIFIERS
KEY WORDS
Identifiers
In C language identifiers are the names given to variables, constants, functions and
user-define data. This identifier is defined against a set of rules.
• An Identifier can only have alphanumeric characters (a-z, A-Z, 0-9) and
underscore (_).
• identifier should not start with a number and other special characters (except
underscore).
• Identifiers are also case sensitive in C. For example name and Name are two
different identifier in C.
• Keywords are not allowed to be used as Identifiers.
• No special characters are permitted, such (, , : ,. . %, #, ! )
• No space is allowed in between the Identifiers.
• Maximum number of characters allowed for an identifier is 63(31).
Keywords:
do if static while
Character set: In C language characters are grouped into the following categories:
DATA TYPES:
Data types in c refer 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.
The types in C can be classified as follows –
Basic Types: They are arithmetic types and are further classified into: (a) integer types
and (b) floating-point types
Enumerated types: They are again arithmetic types and they are used to define
variables that can only assign certain discrete integer values throughout the program
The type void: The type specifier void indicates that no value is available.
Derived types : They include (a) Pointer types, (b) Array types, (c) Structure types, (d)
Union types and (e) Function types.
storage
S.No C Data types Range
Size
Array, pointer, structure and union are called derived data type in C language.
C – Variable
Local variable
Global variable
Local variable in C:
Global variable in C:
• The scope of global variables will be throughout the program. These variables
can be accessed from anywhere in the program.
• This variable is defined outside the main function. So that, this variable is
visible to main function and all other sub functions.
C – Constants
• C Constants are also like normal variables. But, only difference is, their values
cannot 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.
Types of C constant:
/* starts with 0
3 Octal constant int 13 */
/* starts with 0x
4 Hexadecimal constant int 0×90 */
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14;
const char letter = ‘A’; /*char constant*/
const char letter_sequence[10] = “ABC”; /*string constant*/
Input : In any programming language input means to feed some data into program.
This can be given in the form of file or from command line.
Output : In any programming language output means to display some data on screen,
printer or in any file.
• C programming treats all the devices as files. So devices such as the display are
addressed in the same way as files and the following three files are automatically
opened when a program executes to provide access to the keyboard and screen.
• The int getchar(void) function reads the next available character from the
screen and returns it as an integer. This function reads only single character at
a time.
• The int putchar(int c) function puts the passed character on the screen and
returns the same character. This function puts only single character at a time.
#include <stdio.h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
• The char *gets(char *s) function reads a line from stdin into the buffer pointed
to by s until either a terminating newline or EOF (End of File).
• The int puts(const char *s) function writes the string 's' and 'a' trailing newline
to stdout.
#include <stdio.h>
int main( )
{
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
return 0;
}
• The int scanf(const char *format, ...) function reads the input from the
standard input stream stdin and scans that input according to the
formatprovided.
• The int printf(const char *format, ...) function writes the output to the
standard output stream stdout and produces the output according to the format
provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc.,
to print or read strings, integer, character or float respectively.
#include <stdio.h>
main( )
{
char str[100]; int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
C – Operators
• The symbols which are used to perform logical and mathematical operations in a
C program are called C operators.
Types of C operators:
+ Addition Operator 10 + 20 = 30
- Subtraction Operator 20 – 10 = 10
/ Division Operator 20 / 10 = 2
% Modulo Operator 20 % 6 = 2
Relational operators:
• In C Programming we can compare the value stored between two variables and
depending on the result we can follow different blocks using Relational Operator
in C.
• Each operator compares their left side with their right side.It evaluates to 0 if
the condition is false and 1 if it is true.
Truth Table
P Q P&&Q P||Q !P
d )Assignment Operators:
Identifier=expression;
C <<= 2 is same as
<<= Left shift AND assignment operator C=C<<2
(It assigns the result of
of the right shift of c by 2) the right shift of c by 2)
C >>= 2 is same as C = C
>>= Right shift AND assignment operator >> 2(It assigns the result
of the right shift of c by 2)
C &= B is same as C = C
& B(It assigns the result
&= Bitwise AND assignment operator
of the Bitwise AND
between B & C)
C ^= B is same as C = C ^
B
^= bitwise exclusive OR and assignment operator (It assigns the result of
the Bitwise Exclusive OR
between B & C)
C |= B is same as C = C |
B
|= bitwise inclusive OR and assignment operator (It assigns the result of
the Bitwise Inclusive OR
between B & C)
• Bitwise operators are special types of operators that are used in programming
the processor. In processor, mathematical operations like: addition, subtraction,
addition and division are done using the bitwise operators which makes
processing faster and saves power.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
• The increment (++) and decrement (--) operator are unary operators because
they operate on a single operand. the increment operator increment the value of
the variable by 1,while decrement operator decrement the value of the variable
by 1.
• These operator should be used only with variables, They can not be used with
constant or expressions.
Prefix-Increment/decrement Operator
• Here first the value of the variable is Incremented or decremented then the new
value is used in the operation
X= X+1;
Y=X;
Now value of X=4 and Y=4
X= X-1;
Y=X;
Now value of X=3 and Y=3
#include<stdio.h>
Int main(void)
{
Int x=8;
Printf(“x=%d”,x);
Printf(“x=%d”,++x);
Printf(“x=%d”,x);
Printf(“x=%d”,--x);
Printf(“x=%d”,x);
Return (0);
}
Output:
x=8 x=9 x=9 x=8 x=8
Postfix-Increment/decrement Operator
Here first the value of the variable is used in the operation and then value
Incremented or decremented is performed.
The statement Y=X++; Means first the value of X is assigned to Y and then X is
incremented. This single statement is equivalent to these two statements
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Y=X;
X= X+1;
Now value of X=4 and Y=3
The statement Y=X--; Means first the value of X is assigned to Y and then X is
incremented. This single statement is equivalent to these two statements
Y=X;
X= X-1;
Now value of X=3 and Y=4
The conditional expression can be used as shorthand for some if-else statements. It is
a ternary operator. This operator consists of two symbols: the
EXPRESSIONS:
TYPE CONVERSION:
In an expression that involves two different data types , such as multiplying an integer
and a floating point number to perform these evaluations ,one of the types must be
converted.
IMPLICIT TYPE CONVERSION: When the types of the two operands in a binary
expression are different automatically converts one type to another .This is known as
implicit type conversion.
EXPLICIT TYPE CONVERSION: Explicit type conversion uses the unary cast operator
,to convert data from one type to another. To cast data from one type to another ,we
specify the new type in parentheses before the value we want converted.
For example ,to convert an integer ,a , to a float, we code the expression like (float) a
We have a number of situations where we may have to change the order of execution
of statements based on certain conditions or repeat a group of statements until certain
specified conditions are met.
The if statement is a two way decision statement and is used in conjunction with
an expression. It takes the following form
If the test expression is true then the statement block after if is executed otherwise it
is not executed
Simple if:
if (test expression)
statement block;
statement–x ;
If your have another set of statement to be executed if condition is false then if-else is
used
if (test expression)
{
statement block1;
else
statement block2;
statement –x ;
1.Write Algorithm, Program and draw a flowchat for Roots of quadratic equation.
if(text cond1)
{
if (test expression2
{
statement block1;
}
else
{
statement block 2;
}
}
else
{
statement block2;
}
statement-x ;
if else ladder:
• The nesting of if-else depends upon the conditions with which we have to deal.
• This statement is similar to switch statement.
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;
switch(expression)
{.
case value-1:
block-1
break;
case value-2:
block-2
break;
--------
--------
default:
default block;
break;
}
statement–x;
before entering the statement block called entry control. The other in which condition
is checked at exit called exit controlled loop.
First initialization is done once, then condition is evaluated and if it is true then
body of loop is executed. After execution of body the control goes to
increment/ decrement part then condition is once again evaluated and if true body is
executed once again. This goes on until test condition becomes false.
WHILE STATEMENT:
while(test condition)
DO WHILE STATEMENT:
The while loop does not allow body to be executed if test condition is false. The do
while is an exit controlled loop and its body is executed at least once.
do
body
}while(test condition);
1. Write a program for printing a multiplication table for given number using
all loops(while, do-while, for loop)
OTHER STATEMENTS:
BREAK STATEMENT:
CONTINUE STATEMENT:
• This statement meaning is “Skip the following statements and do the next
iteration”.
• Executing a continue starts the next iteration of the loops like do, while or for
statement immediately.
• The use of continue is largely restricted to the top of loops, where a decision has
to be made whether or not to execute the rest of the body of the loop.
#include <stdio.h>
#include <stdlib.h>
main(){
int i;
for(i = -10; i < 10; i++)
{
if(i == 0)
Continue;
printf("%f\n", 15.0/i);
GOTO STATEMENT :
• In C, it is used to escape from multiple nested loops
• You will need a label when you use goto statement.
goto L1;
/* whatever you like here */
L1: /* anything else */
#include <stdio.h>
int main()
{
int sum=0,;
for(int i = 0; i<=10; i++){
sum = sum+i;
if(i==5){
goto addition;
}
}
addition:
printf("%d", sum);
}
Output:
Linux is built being able to run instructions from the command line using switches to
create the output.One of the ways to make use of this is by using the three special file
descriptors - stdin, stdout and stderr
stdin
Generally standard input, referred to as "stdin", comes from the keyboard.When you
type stuff or data, you're typing it on stdin (a standard input terminal). A standard
input device, which is usually the keyboard, but Linux also allows you take standard
input from a file.
stdout
Standard output, as created at process creating time, goes to the console, your
terminal or an X terminal. Exactly where output is sent clearly depends on where the
process originated.Our console or terminal should be the device that is accepting the
output. Running the command:
stderr
The final component in this dialog of file descriptors is standard error.Every command
could send it's output to one of two places: a) it could be valid output or b) it could be
an error message.It does the same with the errors as it does with the standard output;
it sends them directly to your terminal screen.
• Argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.
#include <stdio.h>
return 0;
}
Output:
Storage Classes
Depending on the behaviour and storage area storage classes are classified into 2
types.
1. Automatic Storage class
2. Static storage class
• Under automatic storage class we are having 2 types of storage class specifies
1. Auto
2. Register
Code Properties:
Note:
By default any kind of variable storage class specifier is auto.
In C- Programming language there are 4 – types of scope are available i.e. body,
function, program and file scope.
Int a;
Short int a;
Signed short int a;
Auto signed short int a;
| | | | |
| | | | |
Storage Sign Size Type Variable
Register Variables:
It is a special kind of variable which stores in CPU register.
The advantage of register variables are faster than remaining variables.
Limitations:
When we are working with register variable we can’t create ‘n’ number of register
variables. i.e., depending upon CPU capacity 4.6 are maximum variables.
In TC.3.0 we can’t access the address of register variables.
Pointer or pointer related concepts are not applied to register variables.
Examples:
Void main()
{
Register int a=10;
++a;
Printf(“\n value of a:%d”,a);
Printf(“Enter a value:”);
Scanf(“%d”,&a);
--a;
Printf(“value of a:%d”,a);
Getch();
}
Output: Error
Number System:
When we type some letters or words, the computer translates them in numbers as
computers can understand only numbers. A computer can understand the positional
number system where there are only a few symbols called digits and these symbols
represent different values depending on the position they occupy in the number.
The value of each digit in a number can be determined using −
• The digit
• The position of the digit in the number
• The base of the number system (where the base is defined as the total number
of digits available in the number system)
• In decimal number system, the successive positions to the left of the decimal
point represent units, tens, hundreds, thousands, and so on.
Example: the decimal number 1234 consists of the digit 4 in the units position, 3 in
the tens position, 2 in the hundreds position, and 1 in the thousands position. Its
value can be written as