Revision C - Intro

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 73

Migrating to ‘C’

Why did We Learn Python?


• Easy to learn
• Language with simple rules
• Good for beginners
• Code is readable
• Less development time
• No memory management
• Great support for building web apps
• Dynamic language and no type checking
Why to learn more languages?
• Similar to why a carpenter has more than just a hammer in
his/her toolbox
• Every programming language has its positive and negative
points
• One language cannot do everything
• That is why there are many languages; some are fantastic for
some things
– Eg: C/C++ is typically the benchmark for speed and memory
usage, and some languages provide strengths elsewhere (Eg:
Python is very easy to pick up)
Transiting from Python to C/C++
• Will not be so hard
• There are quite a few syntax differences
between the two languages
• Only way to learn a new programming
language is by writing programs in it
– Dennis Ritchie
History of C
• Born at AT & T Bell Laboratory of USA in 1972
• Many of C’s principles and ideas were derived
from the earlier language B
• Ken Thompson was the developer of B Language
• C was written by Dennis Ritchie
C language was created for a specific purpose i.e
designing the UNIX operating system (which is
currently base of many UNIX based OS)
• Quickly spread beyond Bell Labs in the late 70’s
because of its strong features
About Dennis Ritchie
• Born September 9, 1941
• Known for ALTRAN, B, BCPL, C, Multics, Unix
• Won Turing Award in 1983
• Developed C language which is widely used
developing, operating systems, compiler, and
embedded system development, Assemblers,
Text editors, Print Spoolers, Network drivers
databases etc and its influence is seen in most
modern programming languages
• Died on October 12, 2011
 Features of C language
• Portability - C Programs can run on any compiler
with little or no modification
• Low level features: C provides low level features and
is closely related to lower level assembly Languages
• Modular programming - software design technique
that increases the extent to which software is
composed of separate parts, called modules
• Has many successor languages which are designed
to look like C, e.g., C++, C#, Objective-C, Java,
JavaScript, PHP and Perl.
C is a structured programming language

• Divides the large problem in to smaller


modules called functions or procedures
• Each function or module handles the particular
task and the collection of all the functions is
called a program, which solves the large
problem
• Easier to modify and debug
Difference between Python and C
• C programs – Compiled

• Python programs – Interpreted

Compiler Interpreter
Takes entire program as Takes instruction by
input and generate a output instruction as input and
file with object code gives an output. But does
not generate a file
Errors are displayed after Errors are displayed for
entire program is checked every instruction
interpreted (if any)
Variable Declaration in C
• In C, it is mandatory to do variable declaration
• We say variable's type, whether it is an integer
(int), floating-point number (float), character
(char) etc
• Syntax is type of variable, white space, name
of variable semicolon
• Eg: int number;
White spaces and Indentation
• No problem of difference between white space and
tab in C
• Block of code in C need not be indented as in Python
• In C, Curly braces are used for giving a block of code
Eg: Block of code in ‘C’
{
-----
}
Problem
• Little Bob loves chocolate, and he goes to a
store with Rs. N in his pocket. The price of
each chocolate is Rs. C. The store offers a
discount: for every M wrappers he gives to the
store, he gets one chocolate for free. This offer
is available only once. How many chocolates
does Bob get to eat?
PAC For Chocolate Problem
Input Processing Output

Amount in Number of Chocolates Total number of


hand, N P = Quotient of N / C chocolates got by
Price of one Free chocolate F = Bob
chocolate, C Quotient of P/M
Number of
wrappers for
a free
chocolate, M
Pseudocode
• READ N and C
• COMPUTE num_of_chocolates as N/C
• CALCULATE returning_wrapper as number of
chocolates/m
• TRUNCATE decimal part of returning_wrapper
• COMPUTE Chocolates_recieved as
num_of_chocolates + returning_wrapper
• PRINT Chocolates_recieved
Knowledge Required
• Following knowledge is required in C to write
a code to solve the above problem
• Read input from user
• Data types in Python
• Perform arithmetic calculations
• Write output
Python Program for Bob Problem
Layout of a C program
pre-processor directives – Preceded by a ‘#’
global declarations – Optional and not a good
programming practice
main() - standard start for all C programs 
{
local variables to function main ; - all variables used in the
function must be declared in the beginning
statements associated with function main ;
}
void f1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
Components of a C program

A C program consists of the following parts:


• Comments
• Variables
• Preprocessor Commands
• Functions
•Statements & Expressions
Comments in C

Two types of comments


Single line and multi line comment
Single Line Comment is double forward slash
‘//’ and can be Placed Anywhere
Multiline Comments in C

• Multi line comment can be placed anywhere


• Multi line comment starts with /*
• Multi line comment ends with */
• Any symbols written between '/*’ and '*/‘
are ignored by Compiler
Types of C Constants
Data types in C
Basic Arithmetic types - further classified into: (a)
integer types and (b) floating-point types

Enumerated types - arithmetic types that are used


to define variables that can be assigned only certain
discrete integer values throughout the program

Type void - indicates that no value is available

Derived types - They include (a) Pointer types, (b)


Array types, (c) Structure types, (d) Union types
Broad Classification of Data Types
• Numerical data types are broadly classified into
– Signed
– Unsigned
• Signed can store zero, positive and negative
values
• Unsigned can store only zero and positive values
• Char and bool are unsigned data types
• Some applications use unsigned data types only
Eg: age
Integer Types
Floating Point Types
Keywords
• 32 keywords available in C

Compiler vendors (like Microsoft, Borland, etc.)


provide their own keywords
Valid and Invalid variable names
• BASICSALARY
•_basic
• basic-hra
• #MEAN
• group.
• 422
• population in 2006
• FLOAT
• hELLO
I/O in C
• Basic operation in any language
• Input is got through a function scanf which is
equivalent to input or raw_input in Python
• Syntax of scanf
• scanf( *format, ...) 
• Basically one or more arguments
• First format string, followed by address of variables
that are going to hold values entered by user
I/O in C
• printf( *format, ...)
• contains one or more arguments
• first argument is the format string
printf and scanf format codes
code type format
d int decimal (base ten) number
o int octal number (no leading '0'
supplied in printf)
hexadecimal number (no leading '0x'
supplied in printf; accepted if
x int present in scanf) (for printf, 'X'
makes it use upper case for the
digits ABCDEF)
decimal number ('l' can also be
ld long applied to any of the above to
change the type from 'int' to 'long')
printf and scanf format codes
code type format
u Unsigned int decimal number
lu unsigned long decimal number
c char [footnote] single character
s char pointer string
number with six digits
f float [footnote]
of precision

lf double [footnote] number with six digits


of precision
Address of a variable
• Address of a variable can be obtained by putting a
‘&’ before the variable name
Example 1
#include<stdio.h>
void main()
{
int a = 27;
int b = 25;
int c = a -b;
printf("%d",c);
}
Output 1
2
Example 2
#include<stdio.h>
void main()
{
char a = 273;
char b = 25;
int c = a%b;
printf("%d",c);

}
Output 2
warning: overflow in implicit constant conversion [-
Woverflow]

17

Character – range is 0 to 255

256 is 0
257 is 1 and so on
Example 3
#include<stdio.h>
void main()
{
char a = 27;
char b = 25;
char c = a -b;
printf("%c",c);

}
Output 3
A special character
Arithmetic Operators in C
Operator Description
+ Adds two operands
− Subtracts second operand from the first.
∗ Multiplies both operands
∕ Divides numerator by denominator
% Modulus Operator and remainder of after
an integer division.
++ Increment operator increases the integer
value by one
-- Decrement operator decreases the integer
value by one
Precedence of Operators in C
++, -- Post increment Operators
++, -- Pre increment Operators

Parenthesis can be used to override default precedence


Example 4
#include<stdio.h>
main()
{
int a, b,c;
a = 4;
b = 2;

c = -a+--b;

printf ( "c = %d", c) ;


}
Output 4
c = -3
Example 5
#include<stdio.h>
main()
{
int a, b,c;
a = 4;
b = 2;

c = -a+ b--;

printf ( "c = %d", c) ;


printf ( "b = %d", b) ;
}
Output 5
c = -2
b=1
Associativity of Operators in C
When precedence of two operators are same then
associativity of operator is considered for evaluation
Automatic Type Conversion in C
Convert a variable from one data type to another data
type
When the type conversion is performed automatically by
the compiler without programmers intervention, such
type of conversion is known as implicit type
conversion or type promotion.

The compiler converts all operands into the data type of


the largest operand.
Rules for Implicit Type Conversion in C
• Sequence of rules that are applied while
evaluating expressions are given below:
• All short and char are automatically converted to
int, then,
• If either of the operand is of type long double,
then others will be converted to long double and
result will be long double.
• Else, if either of the operand is double, then
others are converted to double.
• Else, if either of the operand is float, then others
are converted to float.
Rules for Type Conversion in C
• Else, if either of the operand is unsigned long int, then
others will be converted to unsigned long int.
• Else, if one of the operand is long int, and the other is
unsigned int, then
• if a long int can represent all values of an unsigned int,
the unsigned int is converted to long int.
• otherwise, both operands are converted to unsigned
long int.
• Else, if either operand is long int then other will be
converted to long int.
• Else, if either operand is unsigned int then others will be
converted to unsigned int.
Example 9
#include<stdio.h>
void main()
{
char a = 65;
char b = 100;
int c = a%b;
printf("%c",c);

}
Output 9
A
Example 10
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
int c = a/b;
printf("%d",c);

}
Output 10
1
Example 11
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
float c = a/b;
printf("%f",c);

}
Output 11
1.000000
Example 13
#include<stdio.h>
void main()
{
int a = 165;
float b = 100;
float c = a/b;
printf("%f",c);

}
Output 13
1.650000
Explicit Type Conversion
Type conversion performed by the programmer is known
as explicit type conversion
Explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type)expression;
where, data_type is any valid c data type,
and expression may be constant, variable or an expression
For example, x=(int)a+b*d;
Explicit Type Conversion
The following rules have to be followed while converting
the expression from one type to another to avoid the loss
of information:
• All integer types to be converted to float.
• All float types to be converted to double.
• All character types to be converted to integer.
Example 14
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
float c = (float)(a/b);
printf("%f",c);

}
Output 14
1.000000
Example 15
#include<stdio.h>
void main()
{
int a = 165;
int b = 100;
float c = (float) a/b;
printf("%f",c);

}
Output 15
1.650000
Assignment
• Students have to check all operators for all types of
operands, also work on to understand precedence of
operators
Declaration and Definition of Variables in C
• Declaration – Information to compiler about the
variable
• Definition – Memory is allocated for the variable
according to type
• For all storage classes declaration and definition are
same except for extern
• When a keyword extern precedes, its only a
declaration and the compiler waits for definition
without raising error
Problem
ABC company Ltd. is interested to computerize the pay calculation of their
employee in the form of Basic Pay, Dearness Allowance (DA) and House Rent
Allowance (HRA). DA and HRA are calculated as certain % of Basic pay(For
example, DA is 80% of Basic Pay, and HRA is 30% of Basic pay). They have the
deduction in the salary as PF which is 12% of Basic pay. Propose a
computerized solution for the above said problem.

Input : Basic Pay


Process : Calculate Salary
( Basic Pay + ( Basic Pay * 0.8) + ( Basic Pay * 0.3 - ( Basic Pay * 0.12)
-----------allowances -------------- --- deductions----
Output : Salary
Problem
• Find the average runs scored by a batsman in 4
matches
• Area of a circle
Exercise
An university is setting up a new lab at their premises.
Design an algorithm and write Python code to determine the
approximate cost to be spent for setting up the lab. Cost for
setting the lab is sum of cost of computers, cost of furnitures
and labour cost. Use the following formulae for solving the
problem:

Cost of computer = cost of one computer * number of


computers

Cost of furniture = Number of tables * cost of one table +


number of chairs * cost of one chair

Labour cost = number of hours worked * wages per hour

You might also like