SlideShare a Scribd company logo
1 of 29
Download to read offline
Programming in C
Part – 1: Introduction
Resources:
1. Stanford CS Education Library URL:
http://cslibrary.stanford.edu/101/
2. Programming in ANSI C, E Balaguruswamy,
Tata McGraw-Hill
PROGRAMMING IN C
A computer program is a collection of instructions for performing some specified
task(s) with the computer.
• C is the offspring of Basic Combined Programming Language (‘B’)
developed in 1960s by Cambridge University
• ‘B’ was Modified by Dennis Ritchie at Bell Laboratories in 1972, and was
named ‘C’.
• Pros and cons:
• Programmers language. Gets in programmers way as little possible.
• You need to know exactly what you are doing !! Can be Irritating and
confusing for beginners .
• Structure of Programs
• A C program is a collection of functions.
• Execution starts at the main() function.
Documentation Section
__________________________
Link Section
__________________________
Definition Section
__________________________
Globel Decleration Section
__________________________
Function Section
Main()
{
____DECLERATION PART____
____EXECUTABLE PART_____
}
___________________________
Subprogram Section
Function 1
Function 2
..
..
General structure of a C Program
/*This is my First program*/
#include<stdio.h> /*link */
void main()
{
printf(“This my first C progn“);
}
Documentation Section
__________________________
Link Section
__________________________
Definition Section
__________________________
Globel Decleration Section
__________________________
Function Section
Main()
{
____DECLERATION PART____
____EXECUTABLE PART_____
}
___________________________
Subprogram Section
Function 1
Function 2
..
..
General structure of a C Program
/*this is my second program*/
#include<stdio.h> /*link */
#define pi 3.14 /*definition*/
float area; /*global */
void main()
{
float r; /*Declaration*/
r=1.0;
area=pi*r*r;
printf(“area is %d n“,area);
}
Writing and executing a C Program in LINUX
Create a c program
cd to your directory of choice, and write the c-program using some text editors (eg.
vi,vim)
e.g. cd ~/Cprog
vim firstprog.c
Compiling and linking
use an existing compiler (gcc, cc etc) to compile your program an make an
executable
e.g. cc filename
gcc filename1, filename2, filename3 ………
Common options:
–lm : library math
-c : Compiles without linking. binaries are saved as "filename.o"
-o exename: compiled binary with specified filename. (a.out default)
gcc –o myprog firstprog.c
Execute the program
./filename will execute the program. (Should have the “x” flag on !)
C variables and Data Types
Keywords:
#include <stdio.h>
#define PI 3.14
float area;
void main()
{
double r;
r=1.0;
area=PI*r*r;
printf(“Area is %d n“,area);
}
Keywords Serves as Basic building blocks of the programs.
Backslash character constants:
#include <stdio.h>
#define PI 3.14
float area;
void main()
{
double r;
r=1.0;
area=PI*r*r;
printf(“Area is %d n“,area);
}
Variables
/*This is my second program*/
#include "stdio.h" /*link */
#define PI 3.14 /*definition*/
float area;
void main()
{
double r;
r=1.0;
area=PI*r*r;
printf(“Area is %d n“,area);
}
• C puts the type first followed by the
name.
• They begin with a letter
• Upto 31 characters (ANSI)
• Case Sensitive
• Must not be a keyword
• Should not conflict with built-
in functions
• No while spaces
• Retains random values unless set.
a variable declaration reserves and
names an area in memory at run
time to hold a value of particular
type.
Integers
All behave like integers and can be mixed with one another.: e.g. int, short,
long , char
Floating Point:
float(~6 digit precision), double(~15 digit precision), long double
Data Types
8 bit = 1 byte (Note: Actual byte/ datatype may vary from machine to machine)
Declaration syntax
data-type v1,v2,…..vn;
Variables are separated by commas.
Statement ends with a semicolon(;).
Example:
int count;
int a=5, b=2, c;
double ratio;
/*This is my second program*/
#include "stdio.h" /*link */
#define PI 3.14 /*definition*/
float area;
void main()
{
double r;
r=1.0;
area=PI*r*r;
printf(“Area is %d n“,area);
}
%i ,
%d
%u
%6d
Integer(decimal, hexa or octa decimal) Decimal
integer.
Unsigned decimal integer.
decimal integer, at least 6 characters wide.
%f
%6f
%.2f
%6.2f
print as floating point
floating point, at least 6 characters wide
floating point, 2 characters after decimal point
floating point, at least 6 wide and 2 after decimal
point
%o Octal
%x Hexadecimal
%c or %s Character / String
%% For printing %
%e,%E Exponential notation
printf(“Area is %d n“,area);
Format Specifies
• The integral types may be mixed together in arithmetic expressions since they are all
basically just integers with variation in their width.
• For example, char and int can be combined in arithmetic expressions such as ('b' + 5).
• In such a case, the compiler "promotes" the smaller type (char) to be the same size as
the larger type (int) before combining the values.
• Promotions are determined at compile time based purely on the types of the values in
the expressions.
• Promotions do not lose information -- they always convert from a type to compatible,
larger type to avoid losing information.
• Overflow:
TYPE COMBINATION AND PROMOTION
TRUNCATION
• The opposite of promotion, truncation moves a value from a type to a smaller
type.
• The compiler just drops the extra bits. (May or may not generate a compile time
warning of the loss of information).
Assigning from an integer to a smaller
integer (e.g.. long to int, or int to
char) drops the most significant bits.
char ch;
int i;
i = 321;
ch = i;
//int  char (ch is now 65)
Assigning from a floating point type to an
integer drops the fractional part of the number.
double pi;
int i;
pi = 3.14159;
i = pi;
// floatint (i is now 3)
scale the unit test marks in the range 0 - 20 to the range 0 -100.
Divide the marks by 20, and then multiply by 100 to get the scaled marks.
MORE EXAMPLES
#includestdio.h
main()
{
int score;
scanf(“enter the marks: %d” score);
score = (score / 20) * 100;
printf(“revised marks= %d“,score);
}
score = ((double)score / 20) * 100;
Operators and Expressions
THE ASSIGNMENT OPERATORS
= Assignment operator (copies the value
from its right hand side to the variable
on its left hand side)
The assignment also acts as an
expression which returns the newly
assigned value
i = i +3;
(means
i  i +3)
y = (x = 2 * x);
Other Assignment operators besides the “ = “ operator are as follows:
+= , -= Increment or decrement by RHS i+=3
*= , /= Multiplication or division by RHS i/=3
is equivalent to
i=i/3
= , = Bitwise Right/Left Shift by RHS
(divide/Multiply by 2n)
=,|=,^= Bitwise AND,OR,XOR by RHS.
MATHEMATICAL OPERATORS
C supports the following operation
+ Addition
- Subtraction
/ Division
* Multiplication
% Remainder (mod)
• use parenthesis to avoid any bugs due to a misunderstanding of
precedence.
• For example, A division (/) with two integer arguments will do integer
division. If either argument is a float, it does floating point division. So
(10/4) evaluates to 2 while (10/4.0) evaluates to 2.5.
SIMPLE CONVERSIONS
(1)y = m*x*x;
(2)y = 1.0E-4*exp(-pow(sin(x),2)/5.0);
(3)y = (a+b*x)/(x*sin(x*x));
(4)y = sqrt(sigma(1+x*x)/fabs(1-x)*sqrt(log10(1+p*p))+6)-x;
or
a = sqrt(log10(1+p*p);
b = sigma(1+x*x)/fabs(1-x);
y = sqrt(a*b+6)-x;
x
p
x
x
y
x
x
bx
a
y
e
y
mx
y x
−
+
+








−
+
=
+
=
=
= −
−
6
)
1
(
log
1
1
)
4
(
)
sin(
)
3
(
10
)
2
(
)
1
(
2
10
2
2
5
/
)
sin(
4
2 2
σ
Increment (++) and decrement(--) operators
UNARY OPERATORS
The increment (decrement) operator increases (decreases) the value of the
variable by 1.
Operation Example Equivalent to
var++ (post increment) j=(i++ + 10); j = i+10;
i= i+1;
j is52
++var (pre increment) j= (++i +10); i= i+1;
j= i+10;
j is53
Var-- (post decrement) j=(i-- + 10); j = i+10;
i = i-1;
j is52
--var (pre decrement) j=(--i + 10); i= i-1;
j= i+10;
j is51
int i=42, j;
RELATIONAL OPERATORS
These operate on integer or floating point values and return a 0 or 1 boolean
value.
Operator Meaning
== Equal
!= Not equal
 Greater Than
 Less Than
= Greater or Equal
= Less or Equal
= ASSIGNMENT operator (does not belong to
this class)
LOGICAL OPERATORS
Logical operators take 0 as false and anything else to be true
BOOLEAN operators
Op Meaning
! Boolean NOT
 Boolean AND
|| Boolean OR
BITWISE OPERATORS
(Manipulates data at BIT level)
Op Meaning
~ Bitwise Negation
 Bitwise AND
| Bitwise OR
^ Bitwise XOR
 Right shift (divide
by power of 2)
 Left shift (divide
by power of 2)
Bitwise operators have higher
precedence over Boolean
operators.
basic housekeeping functions are available to a C program in form of standard
library functions. To call these, a program must #include the appropriate .h file
STANDARD LIBRARY FUNCTIONS
stdio.h file input and output
math.h mathematical functions such as sin() and cos()
conio.h/
cursers.h
time.h date and time
ctype.h character tests
string.h string operations
stdlib.h utility functions such as malloc() and rand()
assert.h the assert() debugging macro
stdarg.h support for functions with variable numbers of arguments
setjmp.h support for non-local flow control jumps
signal.h support for exceptional condition signals
limits.h, float.h constants which define type range values such as INT_MAX
http://www.cplusplus.com/reference/cmath/
(only important contents shown, for all contents search the web)
math.h contents
Trigonamitric/ hyperbolic: cos, sin, tan, acos, asin, atan, cosh,
sinh, tanh
Exponential and logarithmic functions: exp,log, log10
Power functions: pow, sqrt
Rounding and remainder etc: ceil, floor, fmod, fabs
stdio.h contents
Formatted input/output: fprintf, fscanf, printf, scanf, sprintf,
sscanf.
File access: fclose, fopen, fread, fwrite.
Character i/o: fgetc, getc, getchar, gets, putc, putchar, puts.
http://www.cplusplus.com/reference/cmath/
(only important contents shown, for all contents search the web)
Stdlib.h contents
Pseudo-random sequence generation: rand, srand
Dynamic memory management (DMA): calloc, free, malloc, realloc
Environment: abort, exit, getenv, system
string.h contents
strcpy, strcat, strcmp, strchr, strlen
time.h contents
Clock, difftime, time
ctype.h contents
isalnum, isalpha, isblank, iscntrl, isdigit, islower, isupper
• The Preprocessor is a program that processes the C code before it is
processed by the compiler.
• Preprocessor Directives are placed before the main()
• Common Directives: #define, #include, #undef, #ifdef, #endif,
#ifndef, # if, # else
THE C PREPROCESSOR
#define
Sets up symbolic textual replacements
in the source.
#include
Brings in texts from different files
during compilation.
#define PI 3.14
#define Test if(xy)
#define cube(x) x*x*x
#includefile1.h // System
#include “file1.h” //user
(c)
(d)
z
y
x bc
ax
c
b
ax
−
+
f
d
bc
a
−
+
x
y
x
x
−
+
−






−
+
6
1
1
1
σ
kT
m
x
e
kT
)
(
2
2
1 −
σ
π
α
(a) (b)
(e)
1. Convert to equivalent C statement
ASSIGNMENT –I
TO BE SUBMITTED BY 19-08-2013.
THIS IS A PART OF CONTINUOUS ASSESSMENT, AND WILL CARRY MARKS
SUBMIT THEM IN A SHEET BY 19-08-2013. WRITE:
YOUR NAME, LEVEL (MSC / NANO/ IMSC ETC) AND ROLL NO
(2) Write Programs to,
a. Display your name.
b. add two given nos (c=a+b) and display the results
c. Read two integers and display the result of their division(c=a/b).
d. Calculate radius of a circle, given its area. Display your result only
upto 3 decimal places.
e. write a program to display various numbers associated with the ASCII
characters.
PRACTICE THEM DURING LAB ON TUESDAY (AND
OTHER DAYS AS WELL) TO ENSURE THE CORRECTNESS OF THE
PROGRAM SUBMITTED.
ASSIGNMENT–I (CONTD..)

More Related Content

Similar to C-PPT.pdf

comp 122 Chapter 2.pptx,language semantics
comp 122 Chapter 2.pptx,language semanticscomp 122 Chapter 2.pptx,language semantics
comp 122 Chapter 2.pptx,language semanticsfloraaluoch3
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structuresPradipta Mishra
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubeykiranrajat
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2Don Dooley
 
CP c++ programing project Unit 1 intro.pdf
CP c++ programing project  Unit 1 intro.pdfCP c++ programing project  Unit 1 intro.pdf
CP c++ programing project Unit 1 intro.pdfShivamYadav886008
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures Pradipta Mishra
 
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...RSathyaPriyaCSEKIOT
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingMOHAMAD NOH AHMAD
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2Tekendra Nath Yogi
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxKrishanPalSingh39
 

Similar to C-PPT.pdf (20)

comp 122 Chapter 2.pptx,language semantics
comp 122 Chapter 2.pptx,language semanticscomp 122 Chapter 2.pptx,language semantics
comp 122 Chapter 2.pptx,language semantics
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structures
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2
 
C programming
C programmingC programming
C programming
 
CP c++ programing project Unit 1 intro.pdf
CP c++ programing project  Unit 1 intro.pdfCP c++ programing project  Unit 1 intro.pdf
CP c++ programing project Unit 1 intro.pdf
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures
 
C language
C language C language
C language
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
 
C programming
C programming C programming
C programming
 
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. AnsariBasic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 

Recently uploaded

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxCeline George
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Celine George
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonhttgc7rh9c
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 

Recently uploaded (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 

C-PPT.pdf

  • 1. Programming in C Part – 1: Introduction Resources: 1. Stanford CS Education Library URL: http://cslibrary.stanford.edu/101/ 2. Programming in ANSI C, E Balaguruswamy, Tata McGraw-Hill
  • 2. PROGRAMMING IN C A computer program is a collection of instructions for performing some specified task(s) with the computer. • C is the offspring of Basic Combined Programming Language (‘B’) developed in 1960s by Cambridge University • ‘B’ was Modified by Dennis Ritchie at Bell Laboratories in 1972, and was named ‘C’. • Pros and cons: • Programmers language. Gets in programmers way as little possible. • You need to know exactly what you are doing !! Can be Irritating and confusing for beginners . • Structure of Programs • A C program is a collection of functions. • Execution starts at the main() function.
  • 3. Documentation Section __________________________ Link Section __________________________ Definition Section __________________________ Globel Decleration Section __________________________ Function Section Main() { ____DECLERATION PART____ ____EXECUTABLE PART_____ } ___________________________ Subprogram Section Function 1 Function 2 .. .. General structure of a C Program /*This is my First program*/ #include<stdio.h> /*link */ void main() { printf(“This my first C progn“); }
  • 4. Documentation Section __________________________ Link Section __________________________ Definition Section __________________________ Globel Decleration Section __________________________ Function Section Main() { ____DECLERATION PART____ ____EXECUTABLE PART_____ } ___________________________ Subprogram Section Function 1 Function 2 .. .. General structure of a C Program /*this is my second program*/ #include<stdio.h> /*link */ #define pi 3.14 /*definition*/ float area; /*global */ void main() { float r; /*Declaration*/ r=1.0; area=pi*r*r; printf(“area is %d n“,area); }
  • 5. Writing and executing a C Program in LINUX Create a c program cd to your directory of choice, and write the c-program using some text editors (eg. vi,vim) e.g. cd ~/Cprog vim firstprog.c Compiling and linking use an existing compiler (gcc, cc etc) to compile your program an make an executable e.g. cc filename gcc filename1, filename2, filename3 ……… Common options: –lm : library math -c : Compiles without linking. binaries are saved as "filename.o" -o exename: compiled binary with specified filename. (a.out default) gcc –o myprog firstprog.c Execute the program ./filename will execute the program. (Should have the “x” flag on !)
  • 6. C variables and Data Types
  • 7. Keywords: #include <stdio.h> #define PI 3.14 float area; void main() { double r; r=1.0; area=PI*r*r; printf(“Area is %d n“,area); } Keywords Serves as Basic building blocks of the programs.
  • 8. Backslash character constants: #include <stdio.h> #define PI 3.14 float area; void main() { double r; r=1.0; area=PI*r*r; printf(“Area is %d n“,area); }
  • 9. Variables /*This is my second program*/ #include "stdio.h" /*link */ #define PI 3.14 /*definition*/ float area; void main() { double r; r=1.0; area=PI*r*r; printf(“Area is %d n“,area); } • C puts the type first followed by the name. • They begin with a letter • Upto 31 characters (ANSI) • Case Sensitive • Must not be a keyword • Should not conflict with built- in functions • No while spaces • Retains random values unless set. a variable declaration reserves and names an area in memory at run time to hold a value of particular type.
  • 10. Integers All behave like integers and can be mixed with one another.: e.g. int, short, long , char Floating Point: float(~6 digit precision), double(~15 digit precision), long double Data Types 8 bit = 1 byte (Note: Actual byte/ datatype may vary from machine to machine)
  • 11. Declaration syntax data-type v1,v2,…..vn; Variables are separated by commas. Statement ends with a semicolon(;). Example: int count; int a=5, b=2, c; double ratio; /*This is my second program*/ #include "stdio.h" /*link */ #define PI 3.14 /*definition*/ float area; void main() { double r; r=1.0; area=PI*r*r; printf(“Area is %d n“,area); }
  • 12. %i , %d %u %6d Integer(decimal, hexa or octa decimal) Decimal integer. Unsigned decimal integer. decimal integer, at least 6 characters wide. %f %6f %.2f %6.2f print as floating point floating point, at least 6 characters wide floating point, 2 characters after decimal point floating point, at least 6 wide and 2 after decimal point %o Octal %x Hexadecimal %c or %s Character / String %% For printing % %e,%E Exponential notation printf(“Area is %d n“,area); Format Specifies
  • 13.
  • 14. • The integral types may be mixed together in arithmetic expressions since they are all basically just integers with variation in their width. • For example, char and int can be combined in arithmetic expressions such as ('b' + 5). • In such a case, the compiler "promotes" the smaller type (char) to be the same size as the larger type (int) before combining the values. • Promotions are determined at compile time based purely on the types of the values in the expressions. • Promotions do not lose information -- they always convert from a type to compatible, larger type to avoid losing information. • Overflow: TYPE COMBINATION AND PROMOTION
  • 15. TRUNCATION • The opposite of promotion, truncation moves a value from a type to a smaller type. • The compiler just drops the extra bits. (May or may not generate a compile time warning of the loss of information). Assigning from an integer to a smaller integer (e.g.. long to int, or int to char) drops the most significant bits. char ch; int i; i = 321; ch = i; //int char (ch is now 65) Assigning from a floating point type to an integer drops the fractional part of the number. double pi; int i; pi = 3.14159; i = pi; // floatint (i is now 3)
  • 16. scale the unit test marks in the range 0 - 20 to the range 0 -100. Divide the marks by 20, and then multiply by 100 to get the scaled marks. MORE EXAMPLES #includestdio.h main() { int score; scanf(“enter the marks: %d” score); score = (score / 20) * 100; printf(“revised marks= %d“,score); } score = ((double)score / 20) * 100;
  • 18. THE ASSIGNMENT OPERATORS = Assignment operator (copies the value from its right hand side to the variable on its left hand side) The assignment also acts as an expression which returns the newly assigned value i = i +3; (means i  i +3) y = (x = 2 * x); Other Assignment operators besides the “ = “ operator are as follows: += , -= Increment or decrement by RHS i+=3 *= , /= Multiplication or division by RHS i/=3 is equivalent to i=i/3 = , = Bitwise Right/Left Shift by RHS (divide/Multiply by 2n) =,|=,^= Bitwise AND,OR,XOR by RHS.
  • 19. MATHEMATICAL OPERATORS C supports the following operation + Addition - Subtraction / Division * Multiplication % Remainder (mod) • use parenthesis to avoid any bugs due to a misunderstanding of precedence. • For example, A division (/) with two integer arguments will do integer division. If either argument is a float, it does floating point division. So (10/4) evaluates to 2 while (10/4.0) evaluates to 2.5.
  • 20. SIMPLE CONVERSIONS (1)y = m*x*x; (2)y = 1.0E-4*exp(-pow(sin(x),2)/5.0); (3)y = (a+b*x)/(x*sin(x*x)); (4)y = sqrt(sigma(1+x*x)/fabs(1-x)*sqrt(log10(1+p*p))+6)-x; or a = sqrt(log10(1+p*p); b = sigma(1+x*x)/fabs(1-x); y = sqrt(a*b+6)-x; x p x x y x x bx a y e y mx y x − + +         − + = + = = = − − 6 ) 1 ( log 1 1 ) 4 ( ) sin( ) 3 ( 10 ) 2 ( ) 1 ( 2 10 2 2 5 / ) sin( 4 2 2 σ
  • 21. Increment (++) and decrement(--) operators UNARY OPERATORS The increment (decrement) operator increases (decreases) the value of the variable by 1. Operation Example Equivalent to var++ (post increment) j=(i++ + 10); j = i+10; i= i+1; j is52 ++var (pre increment) j= (++i +10); i= i+1; j= i+10; j is53 Var-- (post decrement) j=(i-- + 10); j = i+10; i = i-1; j is52 --var (pre decrement) j=(--i + 10); i= i-1; j= i+10; j is51 int i=42, j;
  • 22. RELATIONAL OPERATORS These operate on integer or floating point values and return a 0 or 1 boolean value. Operator Meaning == Equal != Not equal Greater Than Less Than = Greater or Equal = Less or Equal = ASSIGNMENT operator (does not belong to this class)
  • 23. LOGICAL OPERATORS Logical operators take 0 as false and anything else to be true BOOLEAN operators Op Meaning ! Boolean NOT Boolean AND || Boolean OR BITWISE OPERATORS (Manipulates data at BIT level) Op Meaning ~ Bitwise Negation Bitwise AND | Bitwise OR ^ Bitwise XOR Right shift (divide by power of 2) Left shift (divide by power of 2) Bitwise operators have higher precedence over Boolean operators.
  • 24. basic housekeeping functions are available to a C program in form of standard library functions. To call these, a program must #include the appropriate .h file STANDARD LIBRARY FUNCTIONS stdio.h file input and output math.h mathematical functions such as sin() and cos() conio.h/ cursers.h time.h date and time ctype.h character tests string.h string operations stdlib.h utility functions such as malloc() and rand() assert.h the assert() debugging macro stdarg.h support for functions with variable numbers of arguments setjmp.h support for non-local flow control jumps signal.h support for exceptional condition signals limits.h, float.h constants which define type range values such as INT_MAX
  • 25. http://www.cplusplus.com/reference/cmath/ (only important contents shown, for all contents search the web) math.h contents Trigonamitric/ hyperbolic: cos, sin, tan, acos, asin, atan, cosh, sinh, tanh Exponential and logarithmic functions: exp,log, log10 Power functions: pow, sqrt Rounding and remainder etc: ceil, floor, fmod, fabs stdio.h contents Formatted input/output: fprintf, fscanf, printf, scanf, sprintf, sscanf. File access: fclose, fopen, fread, fwrite. Character i/o: fgetc, getc, getchar, gets, putc, putchar, puts.
  • 26. http://www.cplusplus.com/reference/cmath/ (only important contents shown, for all contents search the web) Stdlib.h contents Pseudo-random sequence generation: rand, srand Dynamic memory management (DMA): calloc, free, malloc, realloc Environment: abort, exit, getenv, system string.h contents strcpy, strcat, strcmp, strchr, strlen time.h contents Clock, difftime, time ctype.h contents isalnum, isalpha, isblank, iscntrl, isdigit, islower, isupper
  • 27. • The Preprocessor is a program that processes the C code before it is processed by the compiler. • Preprocessor Directives are placed before the main() • Common Directives: #define, #include, #undef, #ifdef, #endif, #ifndef, # if, # else THE C PREPROCESSOR #define Sets up symbolic textual replacements in the source. #include Brings in texts from different files during compilation. #define PI 3.14 #define Test if(xy) #define cube(x) x*x*x #includefile1.h // System #include “file1.h” //user
  • 28. (c) (d) z y x bc ax c b ax − + f d bc a − + x y x x − + −       − + 6 1 1 1 σ kT m x e kT ) ( 2 2 1 − σ π α (a) (b) (e) 1. Convert to equivalent C statement ASSIGNMENT –I TO BE SUBMITTED BY 19-08-2013. THIS IS A PART OF CONTINUOUS ASSESSMENT, AND WILL CARRY MARKS SUBMIT THEM IN A SHEET BY 19-08-2013. WRITE: YOUR NAME, LEVEL (MSC / NANO/ IMSC ETC) AND ROLL NO
  • 29. (2) Write Programs to, a. Display your name. b. add two given nos (c=a+b) and display the results c. Read two integers and display the result of their division(c=a/b). d. Calculate radius of a circle, given its area. Display your result only upto 3 decimal places. e. write a program to display various numbers associated with the ASCII characters. PRACTICE THEM DURING LAB ON TUESDAY (AND OTHER DAYS AS WELL) TO ENSURE THE CORRECTNESS OF THE PROGRAM SUBMITTED. ASSIGNMENT–I (CONTD..)