SlideShare une entreprise Scribd logo
1  sur  55
C programming---basic 
1 Introduction to C 
2 C Fundamentals 
3 Formatted Input/Output 
4 Expression 
5 Selection Statement 
6 Loops 
7 Basic Types 
8 Arrays 
9 Functions 
10 Pointers 
11 Pointers and Arrays
Introduction to C 
Intended use and underlying philosophy 
1 C is a low-level language 
---suitable language for systems programming 
2 C is a small language 
---relies on a “library” of standard functions 
3 C is a permissive language 
---it assumes that you know what you’re doing, so it allows 
you a wider degree of latitude than many languages. It 
doesn’t mandate the detailed error-checking found in 
other language
Introduction to C 
Strengths: 
+ Efficiency: intended for applications where assembly language 
had traditionally been used. 
+ Portability: hasn’t splintered into incompatible dialects; small 
and easily written 
+ Power: large collection of data types and operators 
+ Flexibility: not only for system but also for embedded system 
commercial data processing 
+ Standard library 
+ Integration with UNIX
Introduction to C 
Weaknesses: 
+ error-prone 
+ difficult to understand 
+ difficult to modify
Similarities of C to java 
•/* Comments */ 
•Variable declarations 
•if / else statements 
•for loops 
•while loops 
•function definitions (like methods) 
•Main function starts program
Differences between C and java 
•C does not have objects 
There are “struct”ures 
•C is a functional programming language 
•C allows pointer manipulation 
•Input / Output with C 
Output with printf function 
Input with scanf function
C Fundamentals 
First program 
#include <stdio.h> 
main() 
{ 
printf(“To C, or not to C: that is the question”); 
}
C Fundamentals 
Compiling and Linking 
Preprocessing: the program is given to a preprocessor, 
which obeys commands that begin with #(directives) 
add things to the program and make modifications 
Compiling: modified programcompilerobject 
code 
Linking: add library functions to yield a complete 
executable program
C Fundamentals 
Compiler 
% cc –o pun pun.c 
% gcc –Wall –o pun pun.c
C Fundamentals 
Keywords 
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
Variable Type 
C has the following simple data types:
Variable Type 
Java has the following simple data types:
Basic Types 
Type (16 bit) Smallest Value Largest Value 
short int -32,768(-215) 32,767(215-1) 
unsigned short int 0 65,535(216-1) 
Int -32,768 32,767 
unsigned int 0 65,535 
long int -2,147,483,648(-231) 2,147,483,648(231-1) 
unsigned long int 0 4,294,967,295
Basic Types 
Type (32 bit) Smallest Value Largest Value 
short int -32,768(-215) 32,767(215-1) 
unsigned short int 0 65,535(216-1) 
Int -2,147,483,648(-231) 2,147,483,648(231-1) 
unsigned int 0 4,294,967,295 
long int -2,147,483,648(-231) 2,147,483,648(231-1) 
unsigned long int 0 4,294,967,295
Data Types 
• char, int, float, double 
• long int (long), short int (short), 
long double 
• signed char, signed int 
• unsigned char, unsigned int 
•1234L is long integer 
•1234 is integer 
•12.34 is float 
•12.34L is long float
Reading and Writing Integers 
unsigned int u; 
scanf(“%u”, &u); /* reads u in base 10 */ 
printf(“%u”, u); /* writes u in base 10 */ 
scanf(“%o”, &u); /* reads u in base 8 */ 
printf(“%o”, u); /* writes u in base 8 */ 
scanf(“%x”, &u); /* reads u in base 16 */ 
printf(“%x”, u); /* writes u in base 16*/ 
short int x; 
scanf(“%hd”, &x); 
printf(“%hd”, x); 
long int x; 
scanf(“%ld”, &x); 
printf(“%ld”, x);
Floating Types 
float single-precision floating-point 
double double-precision floating-point 
long double extended-precision floating-point 
Type Smallest 
Positive Value 
Largest Value Precision 
float 1.17*10-38 3.40*1038 6 digits 
double 2.22*10-308 1.79*10308 15 digits 
double x; long double x; 
scanf(“%lf”, &x); scanf(“%Lf”, &x); 
printf(“%lf”, x); printf(“%Lf”, x);
Character Types 
char ch; 
int i; 
i = ‘a’; /* i is now 97 */ 
ch = 65; /* ch is now ‘A’ */ 
ch = ch + 1; /* ch is now ‘B’ */ 
ch++; /* ch is now ‘C’ */ 
if(‘a’ <= ch && ch <= ‘z’) 
for(ch = ‘A’; ch <= ‘Z’; ch++)
Char Type 
‘a‘, ‘t’, ‘n’, ‘0’, etc. are character 
constants 
strings: character arrays 
− (see <string.h> for string functions) 
− "I am a string" 
− always null (‘0’) terminated. 
− 'x' is different from "x"
Type Conversion 
narrower types are converted into 
wider types 
− f + i int i converted to 
characters <---> integers 
<ctype.h> library contains 
conversion functions, e.g: 
− tolower(c) isdigit(c) etc. 
Boolean values: 
− true : >= 1 false: 0
Type Conversion 
long double 
double 
float 
Unsigned long int 
long int 
unsigned int 
int
Type Conversion 
char c; 
short int s; 
int i; 
unsigned int u; 
long int l; 
unsigned long int ul; 
float f; 
double d; 
long double ld; 
i = i + c; /* c is converted to int */ 
i = i + s; /* s is converted to int */ 
u = u +i; /* i is converted to unsigned int */ 
l = l + u; /* u is converted to long int */ 
ul =ul + l; /* l is converted to unsigned long int */ 
f = f + ul; /* ul is converted to float */ 
d = d + f; /* f is converted to double */ 
ld = ld + d; /* d is converted to long double */
Casting 
( type-name ) expression 
float f, frac_part; 
frac_part = f – (int) f; 
float quotient; 
int dividend, divisor; 
quotient = (float) dividend / divisor; 
short int i; 
int j = 1000; 
i = j * j; /* WRONG */
Type Definitions 
typedef int BOOL 
BOOL flag; /* same as int flag; */ 
typedef short int Int16 
typedef long int Int32 
typedef unsigned char Byte 
typedef struct {int age; char *name} person; 
person people;
Formatted Input/Output 
printf function 
printf(string, expr1, expr2, ……..) 
string: ordinary characters and conversion 
specifications (%) 
%d --- int %s --- string %f --- float 
printf(“i=%d, j=%d. x=%fn”, i, j, x);
Formatted Input/Output 
Conversion Specification 
%[-]m.pX 
m: specifies the minimum number of characters to print. 
%4d-- _123; %-4--123_ 
p: depends on the choice of X 
X: 
-d: decimal form 
-e: floating-point number in exponential format 
-f: floating-point number in “fixed decimal” format 
-g: either exponential format or fixed decimal format, 
depending on the number’s size
Formatted Input/Output 
main() 
{ 
int i = 40; 
float x = 839.21; 
printf(“|%d|%5d|%-5d|%5.3d|n”, i, i, i, i); 
printf(“|%10.3f|%10.3e|%-10g|n”, x, x, x); 
}
Formatted Input/Output 
Escape Sequence 
Enable strings to contain characters that would otherwise cause 
problems for the compiler 
alert a new line n ” “ 
backspace b horizontal tab t
Formatted Input/Output 
How scanf works: is controlled by the conversion specification 
In the format string starting from left to right. 
When called, it tries to locate an item of the appropriate type 
In the input data, skipping white-space characters(the space, 
Horizontal and vertical tab, form-feed, and new-line character) 
scanf(“%d%d%f%f”, &i, &j, &x, &y); 
input: 
___1 
-20___.3 
___-4.0e3 
___1*-20___.3*___-4.0e3* 
sss r s rrr sss rrs sss rrrrrr
Ordinary Characters in Format 
String 
White-space characters: one white-space character in 
the format string will match any number of white-space 
character in the input. 
Other characters: when it encounters a non-white-space 
character in a format string, scanf compares it with the 
next input character. If the two characters match, scanf 
discards the input character and continues processing 
the format string. Otherwise, scanf puts the offending 
character back into the input, then aborts without futher 
processing. 
%d/%d will match _5/_96, but not _5_/_96 
%d_/%d will match _5_/_96
Expressions 
Arithmetic operator: +, -, *, /, %, ++, --……… 
Relational operator: <, >, <=, >=, != 
Logical operator: &&, ||
Operator Precedence and Associativity 
highest: + - (unary) 
* / % 
lowest: + - (binary) 
-i * -j = (-i) * (-j) 
+i + j / k = (+i) + (j / k) 
left/right associative: it groups from left/right to right/left 
The binary arithmetic operators (*, /, %, + and -) are all left associative 
i – j – k = (i – j) – k i * j / k = (i * j) / k 
The unary arithmetic operators( + and -) are both right associative 
- + i = - ( +i )
Expression Evaluation 
Precedence Name Symbol(s) Associativity 
1 X++/X-- left 
2 ++X/--X 
unary +/- 
right 
3 multiplicative *, /, % left 
4 additive +, - left 
5 assignment =, *=, /=, +=, -= right
Expression Evaluation 
a = b += c++ - d + --e / -f 
a = b += (c++) - d + --e / -f 
a = b += (c++) - d + (--e) / -f 
a = b += (c++) - d + (--e) / (-f) 
a = b += (c++) - d + ((--e) / (-f)) 
a = b += ((c++) – d) + ((--e) / (-f)) 
a = b += (((c++) – d) + ((--e) / (-f))) 
a = (b += (((c++) – d) + ((--e) / (-f)))) 
(a = (b += (((c++) – d) + ((--e) / (-f)))))
Bitwise Operations 
• Applied to char, int, short, long 
– And & 
– Or | 
– Exclusive Or ^ 
– Left-shift << 
– Right-shift >> 
– one's complement ~
Example: Bit Count 
/* 
count the 1 bits in a number 
e.g. bitcount(0x45) (01000101 binary) returns 3 
*/ 
int bitcount (unsigned int x) { 
int b; 
for (b=0; x != 0; x = x >> 1) 
if (x & 01) /* octal 1 = 000000001 */ 
b++; 
return b; 
}
Conditional Expressions 
• Conditional expressions 
• expr1? expr2:expr3; 
• if expr1 is true then expr2 else expr3 
for (i=0; i<n; i++) 
printf("%6d %c",a[i],(i%10==9||i==(n-1))?'n':' ');
Control Flow 
• blocks: { ... } 
• if (expr) stmt; 
• if (expr) stmt1 else stmt2; 
• switch (expr) {case ... default } 
• while (expr) stmt; 
• for (expr1;expr2;expr3) stmt; 
• do stmt while expr; 
• break; continue (only for loops); 
• goto label;
Scope Rules 
• Automatic/Local Variables 
– Declared at the beginning of functions 
– Scope is the function body 
• External/Global Variables 
– Declared outside functions 
– Scope is from the point where they are declared 
until end of file (unless prefixed by extern)
Scope Rules 
• Variables can be declared within blocks too 
– scope is until end of the block 
{ 
int block_variable; 
} 
block_variable = 9; (wrong)
Scope Rules 
• Static Variables: use static prefix on functions 
and variable declarations to limit scope 
– static prefix on external variables will limit scope 
to the rest of the source file (not accessible in 
other files) 
– static prefix on functions will make them invisible 
to other files 
– static prefix on internal variables will create 
permanent private storage; retained even upon 
function exit
Hello, World 
#include <stdio.h> 
/* Standard I/O library */ 
/* Function main with no arguments */ 
int main () { 
/* call to printf function */ 
printf("Hello, World!n"); 
/* return SUCCESS = 1 */ 
return 1; 
} 
% gcc -o hello hello.c 
% hello 
Hello, World! 
%
Celsius vs Fahrenheit table 
(in steps of 20F) 
• C = (5/9)*(F-32); 
#include <stdio.h> 
int main() { 
int fahr, celsius, lower, upper, step; 
lower = 0; 
upper = 300; 
step = 20; 
fahr = lower; 
while (fahr <= upper) { 
celsius = 5 * (fahr - 32) / 9; 
printf("%dt%dn",fahr, celsius); 
fahr += step; 
} 
return 1; 
}
Celsius vs Fahrenheit table 
Remarks 
• 5/9 = 0 
• Primitive data types: int, float, char, short, 
long, double 
• Integer arithmetic: 0F = 17C instead of 17.8C 
• %d, %3d, %6d etc for formatting integers 
• n newline 
• t tab
New Version Using Float 
#include <stdio.h> 
int main() { 
float fahr, celsius; 
int lower, upper, step; 
lower = 0; 
upper = 300; 
step = 20; 
fahr = lower; 
while (fahr <= upper) { 
celsius = (5.0 / 9.0) * (fahr - 32.0); 
printf("%3.0f %6.1f n", fahr, celsius); 
fahr += step; 
} 
return 1; 
}
New Version Using Float 
Remarks 
• %6.2f 6 wide; 2 after decimal 
• 5.0/9.0 = 0.555556 
• Float has 32 bits 
• Double has 64 bits 
• Long Double has 80 to 128 bits 
– Depends on computer
Version 3 with “for” loop 
#include <stdio.h> 
int main() { 
int fahr; 
for (fahr=0; fahr <= 300; fahr += 20) 
printf("%3d %6.1f n", fahr, 
(5.0 / 9.0) * (fahr – 32.0)); 
return 1; 
}
Version 4 with Symbolic Constants 
#include <stdio.h> 
#define LOWER 0 
#define UPPER 300 
#define STEP 20 
int main() { 
int fahr; 
for (fahr=LOWER; fahr <= UPPER; fahr += STEP) 
printf("%3d %6.1f n", fahr, 
(5.0 / 9.0) * (fahr - 32.0)); 
return 1; 
}
Character I/O 
• c = getchar(); 
• putchar(c); 
Coyp file 
#include <stdio.h> 
int main() { 
char c; 
c = getchar(); 
while (c != EOF) { 
putchar(c); 
c = getchar(); 
} 
return 0; 
}
File Copying (Simpler Version) 
• c= getchar() != 0 is equivalent to 
c = (getchar() != EOF) 
• Results in c value of 0 (false) or 1 (true) 
#include <stdio.h> 
int main() { 
int c; 
c = getchar(); 
while ((c = getchar())!= EOF) 
putchar(c); 
return 0; 
}
Counting Characters 
• Remarks: nc++, ++nc, --nc, nc-- 
• %ld for long integer 
#include <stdio.h> 
int main () { 
long nc = 0; 
while (getchar() != EOF) 
nc++; 
printf("%ldn",nc); 
} 
#include <stdio.h> 
int main () { 
long nc; 
for (nc=0;getchar() != EOF;nc++); 
printf("%ldn",nc); 
}
Counting Lines 
#include <stdio.h> 
int main () { 
int c, nl=0; 
while ((c = getchar()) != ‘Z’) 
if (c == 'n') 
nl++; 
printf("%dn",nl); 
}
Counting Words 
#include <stdio.h> 
#define IN 1 
#define OUT 0 
int main () { 
int c, nl, nw, nc, state; 
state = OUT; 
nl = nw = nc = 0; 
while ((c = getchar()) != ‘Z’) { 
++nc; 
if (c == 'n') 
nl++; 
if (c == ' ' || c == 'n' || c == 't') 
state = OUT; 
else if (state == OUT) { 
state = IN; 
++nw; 
} 
} 
printf("%d %d %dn",nc, nw, nl); }
Notes about Word Count 
• Short-circuit evaluation of || and && 
• nw++ at the beginning of a word 
• use state variable to indicate inside or outside 
a word
Programming in C Basics

Contenu connexe

Tendances (20)

Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Function in C
Function in CFunction in C
Function in C
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Function in c
Function in cFunction in c
Function in c
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in C
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 

En vedette

Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGAbhishek Dwivedi
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02Wingston
 
Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Rumman Ansari
 
Steps for Developing a 'C' program
 Steps for Developing a 'C' program Steps for Developing a 'C' program
Steps for Developing a 'C' programSahithi Naraparaju
 
C programming basics
C  programming basicsC  programming basics
C programming basicsargusacademy
 
Object-Oriented Programming 2
Object-Oriented Programming 2Object-Oriented Programming 2
Object-Oriented Programming 2Warawut
 
Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)mujeeb memon
 
Introduction to programming with c,
Introduction to programming with c,Introduction to programming with c,
Introduction to programming with c,Hossain Md Shakhawat
 
My first program in c, hello world !
My first program in c, hello world !My first program in c, hello world !
My first program in c, hello world !Rumman Ansari
 
C Programing Solve Presentation -CSE
C Programing Solve Presentation -CSEC Programing Solve Presentation -CSE
C Programing Solve Presentation -CSEsalman ahmed
 
Semiconductors summary
Semiconductors summarySemiconductors summary
Semiconductors summaryradebethapi
 
The Basics of programming
The Basics of programmingThe Basics of programming
The Basics of programming692sfrobotics
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 

En vedette (20)

Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Basic c programming and explanation PPT1
Basic c programming and explanation PPT1Basic c programming and explanation PPT1
Basic c programming and explanation PPT1
 
Steps for Developing a 'C' program
 Steps for Developing a 'C' program Steps for Developing a 'C' program
Steps for Developing a 'C' program
 
C programming basics
C  programming basicsC  programming basics
C programming basics
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Object-Oriented Programming 2
Object-Oriented Programming 2Object-Oriented Programming 2
Object-Oriented Programming 2
 
Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)
 
Introduction to programming with c,
Introduction to programming with c,Introduction to programming with c,
Introduction to programming with c,
 
C ppt
C pptC ppt
C ppt
 
My first program in c, hello world !
My first program in c, hello world !My first program in c, hello world !
My first program in c, hello world !
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
C Programing Solve Presentation -CSE
C Programing Solve Presentation -CSEC Programing Solve Presentation -CSE
C Programing Solve Presentation -CSE
 
Semiconductors summary
Semiconductors summarySemiconductors summary
Semiconductors summary
 
C fundamentals
C fundamentalsC fundamentals
C fundamentals
 
Concept of c
Concept of cConcept of c
Concept of c
 
What is c
What is cWhat is c
What is c
 
The Basics of programming
The Basics of programmingThe Basics of programming
The Basics of programming
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 

Similaire à Programming in C Basics

2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt2. Data, Operators, IO.ppt
2. Data, Operators, IO.pptswateerawat06
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxLikhil181
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)Saifur Rahman
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxKrishanPalSingh39
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 
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
 
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
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingMOHAMAD NOH AHMAD
 
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 programmingAlpana Gupta
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 

Similaire à Programming in C Basics (20)

Cbasic
CbasicCbasic
Cbasic
 
Cbasic
CbasicCbasic
Cbasic
 
2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
dinoC_ppt.pptx
dinoC_ppt.pptxdinoC_ppt.pptx
dinoC_ppt.pptx
 
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
 
Cpu
CpuCpu
Cpu
 
C SLIDES PREPARED BY M V B REDDY
C SLIDES PREPARED BY  M V B REDDYC SLIDES PREPARED BY  M V B REDDY
C SLIDES PREPARED BY M V B REDDY
 
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
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
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
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 

Plus de Bharat Kalia

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
Groupware Technology Project Report
Groupware Technology Project ReportGroupware Technology Project Report
Groupware Technology Project ReportBharat Kalia
 
Extending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingExtending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingBharat Kalia
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingBharat Kalia
 
OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia Bharat Kalia
 
Mingle box - Online Job seeking System
Mingle box - Online Job seeking SystemMingle box - Online Job seeking System
Mingle box - Online Job seeking SystemBharat Kalia
 
Project report of OCR Recognition
Project report of OCR RecognitionProject report of OCR Recognition
Project report of OCR RecognitionBharat Kalia
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsBharat Kalia
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++ Bharat Kalia
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++Bharat Kalia
 

Plus de Bharat Kalia (10)

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Groupware Technology Project Report
Groupware Technology Project ReportGroupware Technology Project Report
Groupware Technology Project Report
 
Extending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingExtending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific Computing
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia
 
Mingle box - Online Job seeking System
Mingle box - Online Job seeking SystemMingle box - Online Job seeking System
Mingle box - Online Job seeking System
 
Project report of OCR Recognition
Project report of OCR RecognitionProject report of OCR Recognition
Project report of OCR Recognition
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++
 

Dernier

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 

Dernier (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 

Programming in C Basics

  • 1. C programming---basic 1 Introduction to C 2 C Fundamentals 3 Formatted Input/Output 4 Expression 5 Selection Statement 6 Loops 7 Basic Types 8 Arrays 9 Functions 10 Pointers 11 Pointers and Arrays
  • 2. Introduction to C Intended use and underlying philosophy 1 C is a low-level language ---suitable language for systems programming 2 C is a small language ---relies on a “library” of standard functions 3 C is a permissive language ---it assumes that you know what you’re doing, so it allows you a wider degree of latitude than many languages. It doesn’t mandate the detailed error-checking found in other language
  • 3. Introduction to C Strengths: + Efficiency: intended for applications where assembly language had traditionally been used. + Portability: hasn’t splintered into incompatible dialects; small and easily written + Power: large collection of data types and operators + Flexibility: not only for system but also for embedded system commercial data processing + Standard library + Integration with UNIX
  • 4. Introduction to C Weaknesses: + error-prone + difficult to understand + difficult to modify
  • 5. Similarities of C to java •/* Comments */ •Variable declarations •if / else statements •for loops •while loops •function definitions (like methods) •Main function starts program
  • 6. Differences between C and java •C does not have objects There are “struct”ures •C is a functional programming language •C allows pointer manipulation •Input / Output with C Output with printf function Input with scanf function
  • 7. C Fundamentals First program #include <stdio.h> main() { printf(“To C, or not to C: that is the question”); }
  • 8. C Fundamentals Compiling and Linking Preprocessing: the program is given to a preprocessor, which obeys commands that begin with #(directives) add things to the program and make modifications Compiling: modified programcompilerobject code Linking: add library functions to yield a complete executable program
  • 9. C Fundamentals Compiler % cc –o pun pun.c % gcc –Wall –o pun pun.c
  • 10. C Fundamentals Keywords 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
  • 11. Variable Type C has the following simple data types:
  • 12. Variable Type Java has the following simple data types:
  • 13. Basic Types Type (16 bit) Smallest Value Largest Value short int -32,768(-215) 32,767(215-1) unsigned short int 0 65,535(216-1) Int -32,768 32,767 unsigned int 0 65,535 long int -2,147,483,648(-231) 2,147,483,648(231-1) unsigned long int 0 4,294,967,295
  • 14. Basic Types Type (32 bit) Smallest Value Largest Value short int -32,768(-215) 32,767(215-1) unsigned short int 0 65,535(216-1) Int -2,147,483,648(-231) 2,147,483,648(231-1) unsigned int 0 4,294,967,295 long int -2,147,483,648(-231) 2,147,483,648(231-1) unsigned long int 0 4,294,967,295
  • 15. Data Types • char, int, float, double • long int (long), short int (short), long double • signed char, signed int • unsigned char, unsigned int •1234L is long integer •1234 is integer •12.34 is float •12.34L is long float
  • 16. Reading and Writing Integers unsigned int u; scanf(“%u”, &u); /* reads u in base 10 */ printf(“%u”, u); /* writes u in base 10 */ scanf(“%o”, &u); /* reads u in base 8 */ printf(“%o”, u); /* writes u in base 8 */ scanf(“%x”, &u); /* reads u in base 16 */ printf(“%x”, u); /* writes u in base 16*/ short int x; scanf(“%hd”, &x); printf(“%hd”, x); long int x; scanf(“%ld”, &x); printf(“%ld”, x);
  • 17. Floating Types float single-precision floating-point double double-precision floating-point long double extended-precision floating-point Type Smallest Positive Value Largest Value Precision float 1.17*10-38 3.40*1038 6 digits double 2.22*10-308 1.79*10308 15 digits double x; long double x; scanf(“%lf”, &x); scanf(“%Lf”, &x); printf(“%lf”, x); printf(“%Lf”, x);
  • 18. Character Types char ch; int i; i = ‘a’; /* i is now 97 */ ch = 65; /* ch is now ‘A’ */ ch = ch + 1; /* ch is now ‘B’ */ ch++; /* ch is now ‘C’ */ if(‘a’ <= ch && ch <= ‘z’) for(ch = ‘A’; ch <= ‘Z’; ch++)
  • 19. Char Type ‘a‘, ‘t’, ‘n’, ‘0’, etc. are character constants strings: character arrays − (see <string.h> for string functions) − "I am a string" − always null (‘0’) terminated. − 'x' is different from "x"
  • 20. Type Conversion narrower types are converted into wider types − f + i int i converted to characters <---> integers <ctype.h> library contains conversion functions, e.g: − tolower(c) isdigit(c) etc. Boolean values: − true : >= 1 false: 0
  • 21. Type Conversion long double double float Unsigned long int long int unsigned int int
  • 22. Type Conversion char c; short int s; int i; unsigned int u; long int l; unsigned long int ul; float f; double d; long double ld; i = i + c; /* c is converted to int */ i = i + s; /* s is converted to int */ u = u +i; /* i is converted to unsigned int */ l = l + u; /* u is converted to long int */ ul =ul + l; /* l is converted to unsigned long int */ f = f + ul; /* ul is converted to float */ d = d + f; /* f is converted to double */ ld = ld + d; /* d is converted to long double */
  • 23. Casting ( type-name ) expression float f, frac_part; frac_part = f – (int) f; float quotient; int dividend, divisor; quotient = (float) dividend / divisor; short int i; int j = 1000; i = j * j; /* WRONG */
  • 24. Type Definitions typedef int BOOL BOOL flag; /* same as int flag; */ typedef short int Int16 typedef long int Int32 typedef unsigned char Byte typedef struct {int age; char *name} person; person people;
  • 25. Formatted Input/Output printf function printf(string, expr1, expr2, ……..) string: ordinary characters and conversion specifications (%) %d --- int %s --- string %f --- float printf(“i=%d, j=%d. x=%fn”, i, j, x);
  • 26. Formatted Input/Output Conversion Specification %[-]m.pX m: specifies the minimum number of characters to print. %4d-- _123; %-4--123_ p: depends on the choice of X X: -d: decimal form -e: floating-point number in exponential format -f: floating-point number in “fixed decimal” format -g: either exponential format or fixed decimal format, depending on the number’s size
  • 27. Formatted Input/Output main() { int i = 40; float x = 839.21; printf(“|%d|%5d|%-5d|%5.3d|n”, i, i, i, i); printf(“|%10.3f|%10.3e|%-10g|n”, x, x, x); }
  • 28. Formatted Input/Output Escape Sequence Enable strings to contain characters that would otherwise cause problems for the compiler alert a new line n ” “ backspace b horizontal tab t
  • 29. Formatted Input/Output How scanf works: is controlled by the conversion specification In the format string starting from left to right. When called, it tries to locate an item of the appropriate type In the input data, skipping white-space characters(the space, Horizontal and vertical tab, form-feed, and new-line character) scanf(“%d%d%f%f”, &i, &j, &x, &y); input: ___1 -20___.3 ___-4.0e3 ___1*-20___.3*___-4.0e3* sss r s rrr sss rrs sss rrrrrr
  • 30. Ordinary Characters in Format String White-space characters: one white-space character in the format string will match any number of white-space character in the input. Other characters: when it encounters a non-white-space character in a format string, scanf compares it with the next input character. If the two characters match, scanf discards the input character and continues processing the format string. Otherwise, scanf puts the offending character back into the input, then aborts without futher processing. %d/%d will match _5/_96, but not _5_/_96 %d_/%d will match _5_/_96
  • 31. Expressions Arithmetic operator: +, -, *, /, %, ++, --……… Relational operator: <, >, <=, >=, != Logical operator: &&, ||
  • 32. Operator Precedence and Associativity highest: + - (unary) * / % lowest: + - (binary) -i * -j = (-i) * (-j) +i + j / k = (+i) + (j / k) left/right associative: it groups from left/right to right/left The binary arithmetic operators (*, /, %, + and -) are all left associative i – j – k = (i – j) – k i * j / k = (i * j) / k The unary arithmetic operators( + and -) are both right associative - + i = - ( +i )
  • 33. Expression Evaluation Precedence Name Symbol(s) Associativity 1 X++/X-- left 2 ++X/--X unary +/- right 3 multiplicative *, /, % left 4 additive +, - left 5 assignment =, *=, /=, +=, -= right
  • 34. Expression Evaluation a = b += c++ - d + --e / -f a = b += (c++) - d + --e / -f a = b += (c++) - d + (--e) / -f a = b += (c++) - d + (--e) / (-f) a = b += (c++) - d + ((--e) / (-f)) a = b += ((c++) – d) + ((--e) / (-f)) a = b += (((c++) – d) + ((--e) / (-f))) a = (b += (((c++) – d) + ((--e) / (-f)))) (a = (b += (((c++) – d) + ((--e) / (-f)))))
  • 35. Bitwise Operations • Applied to char, int, short, long – And & – Or | – Exclusive Or ^ – Left-shift << – Right-shift >> – one's complement ~
  • 36. Example: Bit Count /* count the 1 bits in a number e.g. bitcount(0x45) (01000101 binary) returns 3 */ int bitcount (unsigned int x) { int b; for (b=0; x != 0; x = x >> 1) if (x & 01) /* octal 1 = 000000001 */ b++; return b; }
  • 37. Conditional Expressions • Conditional expressions • expr1? expr2:expr3; • if expr1 is true then expr2 else expr3 for (i=0; i<n; i++) printf("%6d %c",a[i],(i%10==9||i==(n-1))?'n':' ');
  • 38. Control Flow • blocks: { ... } • if (expr) stmt; • if (expr) stmt1 else stmt2; • switch (expr) {case ... default } • while (expr) stmt; • for (expr1;expr2;expr3) stmt; • do stmt while expr; • break; continue (only for loops); • goto label;
  • 39. Scope Rules • Automatic/Local Variables – Declared at the beginning of functions – Scope is the function body • External/Global Variables – Declared outside functions – Scope is from the point where they are declared until end of file (unless prefixed by extern)
  • 40. Scope Rules • Variables can be declared within blocks too – scope is until end of the block { int block_variable; } block_variable = 9; (wrong)
  • 41. Scope Rules • Static Variables: use static prefix on functions and variable declarations to limit scope – static prefix on external variables will limit scope to the rest of the source file (not accessible in other files) – static prefix on functions will make them invisible to other files – static prefix on internal variables will create permanent private storage; retained even upon function exit
  • 42. Hello, World #include <stdio.h> /* Standard I/O library */ /* Function main with no arguments */ int main () { /* call to printf function */ printf("Hello, World!n"); /* return SUCCESS = 1 */ return 1; } % gcc -o hello hello.c % hello Hello, World! %
  • 43. Celsius vs Fahrenheit table (in steps of 20F) • C = (5/9)*(F-32); #include <stdio.h> int main() { int fahr, celsius, lower, upper, step; lower = 0; upper = 300; step = 20; fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr - 32) / 9; printf("%dt%dn",fahr, celsius); fahr += step; } return 1; }
  • 44. Celsius vs Fahrenheit table Remarks • 5/9 = 0 • Primitive data types: int, float, char, short, long, double • Integer arithmetic: 0F = 17C instead of 17.8C • %d, %3d, %6d etc for formatting integers • n newline • t tab
  • 45. New Version Using Float #include <stdio.h> int main() { float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; fahr = lower; while (fahr <= upper) { celsius = (5.0 / 9.0) * (fahr - 32.0); printf("%3.0f %6.1f n", fahr, celsius); fahr += step; } return 1; }
  • 46. New Version Using Float Remarks • %6.2f 6 wide; 2 after decimal • 5.0/9.0 = 0.555556 • Float has 32 bits • Double has 64 bits • Long Double has 80 to 128 bits – Depends on computer
  • 47. Version 3 with “for” loop #include <stdio.h> int main() { int fahr; for (fahr=0; fahr <= 300; fahr += 20) printf("%3d %6.1f n", fahr, (5.0 / 9.0) * (fahr – 32.0)); return 1; }
  • 48. Version 4 with Symbolic Constants #include <stdio.h> #define LOWER 0 #define UPPER 300 #define STEP 20 int main() { int fahr; for (fahr=LOWER; fahr <= UPPER; fahr += STEP) printf("%3d %6.1f n", fahr, (5.0 / 9.0) * (fahr - 32.0)); return 1; }
  • 49. Character I/O • c = getchar(); • putchar(c); Coyp file #include <stdio.h> int main() { char c; c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } return 0; }
  • 50. File Copying (Simpler Version) • c= getchar() != 0 is equivalent to c = (getchar() != EOF) • Results in c value of 0 (false) or 1 (true) #include <stdio.h> int main() { int c; c = getchar(); while ((c = getchar())!= EOF) putchar(c); return 0; }
  • 51. Counting Characters • Remarks: nc++, ++nc, --nc, nc-- • %ld for long integer #include <stdio.h> int main () { long nc = 0; while (getchar() != EOF) nc++; printf("%ldn",nc); } #include <stdio.h> int main () { long nc; for (nc=0;getchar() != EOF;nc++); printf("%ldn",nc); }
  • 52. Counting Lines #include <stdio.h> int main () { int c, nl=0; while ((c = getchar()) != ‘Z’) if (c == 'n') nl++; printf("%dn",nl); }
  • 53. Counting Words #include <stdio.h> #define IN 1 #define OUT 0 int main () { int c, nl, nw, nc, state; state = OUT; nl = nw = nc = 0; while ((c = getchar()) != ‘Z’) { ++nc; if (c == 'n') nl++; if (c == ' ' || c == 'n' || c == 't') state = OUT; else if (state == OUT) { state = IN; ++nw; } } printf("%d %d %dn",nc, nw, nl); }
  • 54. Notes about Word Count • Short-circuit evaluation of || and && • nw++ at the beginning of a word • use state variable to indicate inside or outside a word