Professional Documents
Culture Documents
Introduction - Algorithms, Pseudo code, flow charts, Introduction to C Language - Identifiers, Basic
data types, Variables, Constants, Input / Output, Operators. Expressions, Precedence and Associativity,
Type conversions, Simple C Programming examples. Selection Statements – if and switch statements,
Repetition statements – while, for, do-while statements, Loop examples, other statements related to
looping – break, continue.
INTRODUCTION TO COMPUTER
A Computer is an electronic device which performs operations such as accepts data as an input, store the
data, manipulate or process the data and produce the result as an output.
COMPUTER LANGUAGES:
To write a program (tells what to do) for a computer, we must use a computer language. Over the years
computer languages have evolved from machine languages to natural languages. The following is the
summary of computer languages
1940’s -- Machine Languages
1950’s -- Symbolic Languages
1960’s -- High Level Languages
1. Machine Language:
In the earliest days of computers, the only programming languages available were machine languages.
Each computer has its own machine language which is made of streams of 0’s and 1’s. The instructions
in machine language must be in streams of 0’s and 1’s. This is also referred as binary digits. These are
so named as the machine can directly understood the programs
Advantages:
1) High speed execution
2) The computer can understood instructions immediately
3) No translation is needed.
Disadvantages:
1) Machine dependent
2) Programming is very difficult
3) Difficult to understand
4) Difficult to write bug free programs
5) Difficult to isolate an error
Example: Addition of two numbers
2 0010
+ 3 0011
--- ---------------
5 0101
--- ---------------
3. HIGH-LEVEL Languages:
The symbolic languages greatly improved programming efficiency they still required programmers to
concentrate on the hardware that they were using working with symbolic languages was also very
tedious because each machine instruction had to be individually coded. The desire to improve
programmer efficiency and to change the focus from the computer to the problems being solved led to
the development of high-level 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.
C A systems implementation Language
C++ C with object oriented enhancements
JAVA Object oriented language for internet and general applications using basic C syntax
Advantages:
1) Easy to write and understand
2) Easy to isolate an error
3) Machine independent language
4) Easy to maintain
5) Better readability
6) Low Development cost
7) Easier to document
8) Portable
Disadvantages:
1) Needs translator
2) Requires high execution time
3) Poor control on hardware
4) Less efficient
Example: C language
#include<stdio.h>
void main()
{
int a,b,c;
scanf("%d%d%",&a,&b);
c=a+b;
printf("%d",c);
}
LANGUAGE TRANSLATORS
These are the programs which are used for converting the programs in one language into machine
language instructions, so that they can be executed by the computer.
1) Compiler: It is a program which is used to convert the high level language programs into machine
language
2) Assembler: It is a program which is used to convert the assembly level language programs into
machine language
3) Interpreter: It is a program, it takes one statement of a high level language program, translates it into
machine language instruction and then immediately executes the resulting machine language instruction
and so on.
Pseudo code
Pseudo code is a simpler version of a programming code in plain English which uses short phrases to
write code for a program before it is implemented in a specific programming language. Pseudo code is
an informal way of writing a program. It is not exactly a computer program. It represents the algorithm
of the program in natural language and mathematical notations. Usually, there is no particular code
syntax to write a pseudo code. Therefore, there is no strict syntax as a usual programming language. It
uses simple English language.
Examples:
1. Pseudo code for addition of 2 numbers:
Begin
Declare num1,num2,Sum
WRITE “Please enter two numbers to add”
READ num1, num2
Sum = num1+num2
WRITE Sum
End
4. Pseudo code to find the sum of individual digits of a given positive integer
Begin
Declare num and Set sum=0, dig=0
Read num
While num>0 then
dig = num % 10
sum = sum + dig
num = num/10
End while
Write sum
End
Flow chart
A flowchart is a schematic representation of an algorithm or the diagrammatic representation of way to
solve the given problem.
Flowcharts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals and
small circles. These symbols are connected by arrows called flow lines.
Flowcharts can be used to describe all sorts of processes: business, educational, personal and of course
algorithms.
So, flowcharts are often used as a program planning tool to visually organize step-by-step process of a
program.
The following are the most common symbols used in drawing flowcharts:
Examples:
1. Flow chart to find the sum of two numbers
2. Flow chart to convert temperature Fahrenheit to Celsius
WHY WE LEARN C?
C language is the most commonly used programming language.
It is used for writing operating systems.
UNIX was the first operating system written in C.
Later Microsoft Windows, Mac OS X, and GNU/Linux were all written in C.
Not only is C the language of operating systems, it is the precursor and inspiration for almost all of
the most popular high-level languages available today.
In fact, Perl, PHP, Python and Ruby are all written in C.
FEATURES OF C LANGUAGE
1. Simple: C is a simple language in the sense that it provides a structured approach (to break a problem
into parts), the rich set of library functions, data types, etc.
2. Machine Independent or Portable: Unlike assembly language, c programs can be executed on
different machines with some machine specific changes. Therefore, C is a machine independent
language.
3. Mid-level programming language: Although, C is intended to do low-level programming. It is used
to develop system applications such as kernel, driver, etc. It also supports the features of a high-level
language. That is why it is known as mid-level language.
4. Structured programming language: C is a structured programming language in the sense that we
can break the program into parts using functions. So, it is easy to understand and modify. Functions also
provide code reusability.
5. Rich Library: C provides a lot of inbuilt functions that make the development fast.
6. Memory Management: It supports the feature of dynamic memory allocation. In C language, we can
free the allocated memory at any time by calling the free() function.
7. Speed: The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
8. Pointer: C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.
9. Recursion: In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.
10. Extensible: C language is extensible because it can easily adopt new features.
STRUCTURE OF A C-PROGRAM
KEYWORDS
Keywords are reserved words of the C language.
There are 32 keywords in C. All the keywords are in small case.
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
An Identifier is a sequence of letters and digits, but must start with a letter. Identifiers are case sensitive.
Identifiers specifies the names to the particular entity such as name of variables, functions etc.
Valid identifiers: Root, _getchar, __sin, x1, x2, x3, x_1, If
Invalid identifiers: 324, short, price$, My Name
VARIABLES
Variable indicates the name of the data value. We can store data in a memory space and name it, so that
it becomes easier to access memory space. The naming of an address is known as variable. Unlike
constant, variables are changeable; we can change value of a variable during execution of a program.
Rules to name a variable:
• The name of a variable can be composed of letters, digits, and the underscore character.
• Variable name must not start with a digit.
• Blank spaces are not allowed in variable name.
• Keywords are not allowed as variable name.
• C is case-sensitive, so it is suggested to keep the variable names in lower case.
Declaration of variables must be done before they are used in the program.
Syntax of variable declaration:
datatype variable;
Single variable declaration:
Ex: int a;
Multiple variables declaration of same data type
Ex: float b, c;
String Literals: A sequence of characters enclosed in double quotes as “…”. For example “13” is a
string literal and not number 13. ‘a’ and “a” are different.
Ex: “GfG”, “hello world” etc.,
White Spaces: Spaces, new lines, tabs. These are used to separate the adjacent identifiers, keywords and
constants.
ERROR
Error is an unexpected output. Error is an illegal operation which results in abnormal working of the
program. It is also known as bug. For the successful execution of the programs, it is necessary to remove
all types of errors.
Debugging: It is the process of finding and removing errors from the program.
Types of Error:
1. Syntax errors
• Reason: It occurs due to the violation of writing C syntax rules, such as missing statement
terminator(;), missing parenthesis({,}), misspelled Keyword.
• Detector: Compiler detects during compilation. It can easily specifies the location and type of error.
Easy to locate and remove them.
• Outcome: The program having syntax error cannot be compiled/translated.
Example: C program to illustrate syntax error
#include<stdio.h>
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}
Output: error: expected ';' before '}' token
2. Runtime errors
• Reason: Occurs due to performing an illegal operation. Such as, Number when divided by zero or
Accessing memory that is not available
• Detector: Computer detects errors at the time of running the program. These types of error are hard
to find as the compiler doesn’t point to the line at which the error occurs.
• Outcome: Running program is stopped or crashed and a diagnostic message is displayed on screen
causing that error
• Example: C program to illustrate run-time error
#include<stdio.h>
void main()
{
int n = 9, div = 0;
// wrong logic number is divided by 0,
// so this program abnormally terminates
div = n/0;
printf("resut = %d", div);
}
Output: warning: division by zero [-Wdiv-by-zero] div = n/0
3. Logical errors
• Reason: Occurs due to following a faulty algorithm. provide incorrect output but appears to be error
free
• Detector: Programmer find their errors by checking the whole program statement by statement.
Comparatively difficult to detect this error
• Outcome: Running program does not stop or crash but the wrong output is generated.
Example: Program to find modulus
#include<stdio.h>
int main()
{
int a=10,b=2;
int mod;
mod = a/b; // Logical Error. Correct statement “mod=a%b;”
return 0;
}
Output: 5
Expected 0, Output which you were expecting will not be shown.
OPERATORS IN C
• C operators are symbols that are used to perform mathematical or logical manipulations. The C
programming language is rich with built-in operators. Operators take part in a program for
manipulating data and variables and form a part of the mathematical or logical expressions.
• C programming language offers various types of operators having different functioning capabilities.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations.
Relational Operators
• They are used to compare or check the relationship between two values.
• Every relational operator has two results TRUE or FALSE.
• Relational operators are used to define conditions and take decisions in a program.
Logical Operators
• The logical operators are used to combine multiple conditions into one condition.
Conditional operator
• It is also called as ternary operator. This operator is used for decision making.
• Syntax: Condition? TRUE Part : FALSE Part ;
• In this operator,
– First it verifies a condition
– If the condition is TRUE the first option is performed,
– If the condition is FALSE the second option is performed.
Example: C program to find largest of 2 different numbers
#include<stdio.h>
main()
{
int i,j,large;
printf("Enter two numbers ");
scanf("%d%d",&i,&j);
large=(i>j)?i:j;
printf("Largest = %d",large);
}
Output:
Enter two numbers 25 36
Largest 36
Bitwise Operators
• This operator perform bit level operations.
• The operations are performed based on the binary values.
• For example: A = 25 (11001) and B = 20 (10100)
Special operators
1. sizeof operator: This operator is used to find the size of the memory (in bytes) allocated for a
variable. This operator is used with the following syntax...
Syntax: sizeof(variableName);
Example:
int A;
printf(“%d”, sizeof(A));
Output: 2
2. Comma operator (,): This operator is used to separate variables while they are declaring, separate the
expressions in function calls etc.
Example: float a=2.5,b;
3. Pointer operator (*): This operator is used to define pointer variables in c programming language.
Example: int *p;
4. Dot operator (.): This operator is used to access members of structure or union.
Example: printf(“%d”, emp.num);
TYPE CONVERSION
• Type Conversion: Conversion from one data type to another.
• Two ways of type conversion are:
Implicit Type Conversion
Explicit Type Conversion
Sample C programs:
Program 1: C program to swap 2 values with 3rd variable
#include<stdio.h>
void main()
{
int a,b,temp;
printf("Enter 2 values:");
scanf("%d %d",&a,&b);
printf("Before swapping:\n");
printf("a=%d and b=%d\n",a,b);
temp=a;
a=b;
b=temp;
printf("After swapping:\n");
printf("a=%d and b=%d\n",a,b);
}
Output:
Program 2: C program to swap 2 values without 3rd variable
#include<stdio.h>
void main()
{
int a,b,temp;
printf("Enter 2 values:");
scanf("%d %d",&a,&b);
printf("Before swapping:\n");
printf("a=%d and b=%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After swapping:\n");
printf("a=%d and b=%d\n",a,b);
}
Output:
Selection Statements
if statement
The if statement checks whether the text expression inside parenthesis () is true or not. If the
test expression is true, statement/s inside the body of if statement is executed but if test is false,
statement/s inside body of if is ignored.
Syntax is,
if (test_expression)
{
Staements to be executed if test expression is true;
}
Flow of if statement
Example :
Program to check whether the given number is lessthan 0 or not
#include<stdio..h>
#include<conio.h>
void main()
{
int num;;
printf(“\n enter a number to check : ”);
scanf(“%d”,&num);
if(num<0) /* checking whether number is less than 0 or not. */
{
printf(“\n Number =%d”,num);
}
/*If test condition is true, statement above will be executed, otherwise it
will not be executed */
printf(“The if statement in C programing is easy “);
getch();
}
Output 1
Enter a number to check.
-2
Number = -2
Output 2
Enter a number to check.
5
if – else statement
The if...else statement is used if the programmer wants to execute some statement/s
when the test expression is true and execute some other statement/s if the test expression is
false.
Syntax is,
if (test expression)
{
statements to be executed if test expression is true;
}
else
{
statements to be executed if test expression is false;
}
Flow chart of if-else statement
Example:
Output 1
Enter two integers to check. 5
3
Result: 5 > 3
Output 2
switch Statement
Decision making are needed when, the program encounters the situation to choose a
particular statement among many statements. If a programmer has to choose one block of
statement among many alternatives, nested if...else can be used but, this makes programming
logic complex. This type of problem can be handled in C programming using switch
statement.
Syntax of switch statement is,
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
# include <stdio.h>
int main(){
char o;
float num1,num2;
printf("Select an operator either + or - or * or / \n");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o)
{
case'+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case'-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case'*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case'/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return0;
}
Output
Enter operator either + or - or * or /
*
Enter two operands: 2.3 4.5
2.3 * 4.5 = 10.3
The break statement at the end of each case cause switch statement to exit. Ifbreak statement is
not used, all statements below that case statement are also executed.
There may be a situation, when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.Programming languages provide various control structures that
allow for more complicated execution paths.A loop statement or repetitive statement allows us to
execute a statement or group of statements multiple times.
C programming language provides the following types of loop to handle looping requirements.
Click the following links to check their detail.
do...while loop Like a while statement, except that it tests the condition at the
end of the loop body
nested loops You can use one or more loop inside any another while, for or
do..while loop.
while loop
The while loop checks whether the test expression is true or not. If it is true, code/s
inside the body of while loop is executed,that is, code/s inside the braces { } are executed. Then
again the test expression is checked whether test expression is true or not. This process
continues until the test expression becomes false.
Syntax of while loop,
while (test expression)
{
statement/s to be executed.
}
Flow of while loop,
Example :
Write a C program to find the factorial of a number, where the number is enteredby user.
(Hints: factorial of n = 1*2*3*...*n
Output
Enter a number. 5
Factorial=120
do-while loop
In C, do...while loop is very similar to while loop. Only difference between thesetwo
loops is that, in while loops, test expression is checked at first but, in do...while loop code is
executed at first then the condition is checked. So, the code are exec uted atleast once in
do...while loops.
Syntax of do-while loop is,
do
{
some code/s;
}while (test expression);
At first codes inside body of do is executed. Then, the test expression is checked. If
it is true, code/s inside body of do are executed again and the process continues until test
expression becomes false(zero).
Example
Write a C program to add all the numbers entered by a user until user enters 0.
/*C program to demonstrate the working of do...while statement*/
#include<stdio.h>
int main(){
int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return0;
}
Output
Enter a number 3
Enter a number
-2
Enter a number 0
sum=1
In this C program, user is asked a number and it is added with sum. Then, only the
test condition in the do...while loop is checked. If the test condition is true,i.e, num is
not equal to 0, the body of do...while loop is again executed until num equals to
zero.
for loop
For loop is also used for the similar purpose like while & do-while. It has three statements.
(i) initialization statements (ii) condition statements (iii) update statements.
The initialization statement is executed only once at the beginning of the for loop. Then
the test expression is checked by the program. If the test expression is false, for loop is
terminated. But if test expression is true then the code/s inside body of for loop is executed and
then update expression is updated. This process repeats until test expression is false.
Example,
Write a program to find the sum of first n natural numbers where n is entered by user.
Note: 1,2,3... are called natural numbers.
#include<stdio.h> int
main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
return0;
Output
Enter the value of n. 19
Sum=190
In this program, the user is asked to enter the value of n. Suppose you entered
19 then, count is initialized to 1 at first. Then, the test expression in the for loop,i.e.,
(count<= n) becomes true. So, the code in the body of for loop is executed which makes sum
to 1. Then, the expression ++count is executed and again the test expression is checked, which
becomes true. Again, the body of for loop is executed which makes sum to 3 and this process
continues. When count is 20, the test condition becomes false and the for loop is terminated .
break
break;
The break statement can be used in terminating all three loops for, while and do...while loops.
The figure below explains the working of break statement in all three type of loops.
Example:
printf("Average=%.2f",average);
return0;
}
Output
Maximum no. of inputs4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07
In this program, when the user inputs number less than zero, the loop is
terminated using break statement with executing the statement below it i.e., without
executing sum=sum+num.
In C, break statements are also used in switch...case statement. You will study
it in C switch… case statement chapter.
continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases,
continue statements are used.
Syntax is,
continue;
For better understanding of how continue statements works in C programming. Analyze the
figure below which by passes some code/s inside loops using continue statement.
Example:
Write a C program to find the product of 4 integers entered by a user. If user enters0 skip it.
Output
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30
goto statement
goto label;
.............
.............
.............
label:
statement;
Example
/* C program to demonstrate the working of goto statement. */
/* This program calculates the average of numbers entered by user. */
/* If user enters negative number, it ignores that number andcalculates
the average of number entered before it.*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program moves to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
Output
Maximum no. of inputs: 4
Though, using goto statement give power to jump to any part of program, using
goto statement makes the logic of the program complex and tangled. In modern
programming, goto statement is considered a harmful construct and a bad programming
practice.
The goto statement can be replaced in most of C program with the use of
break and continue statements. In fact, any program in C programming can be perfectly
written without the use of goto statement. All programmer should try to avoid goto
statement as possible as they can.