SlideShare una empresa de Scribd logo
1 de 131
Descargar para leer sin conexión
C Language
Syed Zaid Irshad
Outline
– Program, Language, & Programming Language
– Object Oriented Programming vs Procedure Oriented Programming
– About C
– Why still Learn C?
– Basic Terms
– C Stuff
– C Syntax
– C Program
Program, Language, &
Programming Language
– Program
– A series of coded software instructions to control the operation of a computer or
other machine.
– Language
– A system of symbols and rules for writing programs or algorithms.
– Programming Language
– A programming language is a vocabulary and set of grammatical rules for instructing
a computer or computing device to perform specific tasks. The term programming
language usually refers to high-level languages, such as BASIC, C, C++, COBOL, Java,
FORTRAN, Ada, and Pascal.
Object Oriented Programming vs
Procedure Oriented Programming
– Object oriented Programming
– Object-oriented programming (OOP) is a computer programming model that
organizes software design around data, or objects, rather than functions and logic. An
object can be defined as a data field that has unique attributes and behavior.
– Procedure Oriented Programming
– A procedural language is a computer programming language that follows, in order, a
set of commands.
Object Oriented Programming vs
Procedure Oriented Programming
Parameter POP OOP
Focus Procedures Data
Approach Top-down Bottom-up
Program Decomposition Into Functions Into Objects
Access Modes No modes Private, Public, & Protected
Data Hiding No Hiding Support Hiding
Data Movement Function to function Only with member function
Example C, COBOL, FORTRAN C++, Java, SmallTalk
About C
– Introduction
– Applications/Products that use C
– Features of C
– Drawbacks of C
Introduction
– C is a general-purpose, Mid-level, procedure-oriented programming language
development by Dennis Ritchie in 1972 at Bell Telephone Laboratories (AT&T
Bell Laboratories).
– Previous languages BCPL and B from C is evolved are type less languages. C
introduced the concept of data types and other features.
– C language uses complier (it converts code into binary language).
– In 2011 C11 was released and in 2018 the refined version called C18 was
introduced.
Applications/Products that use C
– Operating Systems
– Unix OS, and Linux Kernel
– Mobile Operating System
– Some parts of Android OS
– Databases
– Some Portion of Oracle, and MySQL
– Programming Languages
– C++, Java, C#, Python, Ruby initially implemented in C.
Features of C
– General-Purpose Programming Language
– Can develop various applications of different domain
– Portable Language
– Program can be run on other computers having same environment
– Block-Structured Language
– It allows a large program to be divide into small sections called functions
– Mid-level Language
– It contains both high and low level language features
Features of C
– Extensible
– We can add more functionality to C
– Reliable
– It is more reliable (good in quality and performance) that its evolved versions
– Typed Language
– It uses the data types and strong data definition
– Powerful Operator Support
– It supports vast number of operators
Features of C
– Vast Built-in Library
– C contains huge built-in library to support functionality
– Hardware Interaction
– C can directly interact with hardware for faster execution
– Graphical Application
– It also support graphical programming
– Relation with Assembly
– C can be used to directly write assembly code
Drawbacks of C
– C does not support OOP
– C does not support runtime checking (RTC)
– Detect runtime errors, such as memory access errors and memory leak, in a native
code application during the development phase.
– C is not a strictly typed language
– C does not provide any data security
– C does not have the concept of namespace
– Namespaces are used to organize code into logical groups and to prevent name
collisions that can occur especially when your code base includes multiple libraries.
Why still Learn C?
– All modern programming languages are influenced by C.
– C++, Java, Python all have same basic structure like C.
– If you can fully absorb C you can easily learn any programming language.
– Also C has a variety of offerings like:
– You can program a microcontroller that can perform a simple task like switching
on/off a light or a medical device that can give you heart rate.
– Can develop an OS kernel or whole software for a supercomputer.
Basic Terms
– Source Code
– Source code is a code which is written by programmer in a human-readable form with
proper programming syntaxes.
– Executable code
– Executable code is the machine-readable code which can be executed directly by the
machine.
– Compiler
– A compiler is a software module that converts source code of the program into executable
code.
– Compile Time
– The time required for the compilation of the source code of a program.
Basic Terms
– Run Time
– The time takin by the program during execution.
– Object code
– When dealing large program, it gets divided into subprograms. These subprograms create
object code after compilation.
– Linker
– Linker links all the object codes to produce executable code.
– Loader
– Part of a compiler which is responsible for loading the executable code in main memory
for execution.
Basic Terms
– Built-in Library
– It is a collection of predefined functions available to help the programmers to write a
good and efficient program
– Header files
– A file that contains declaration of library functions, global variables and Marco
definition
C Stuff
– Basic Structure
– Processor Directive
– Tokens
– Semicolon
– Comments
– Character Set
– Keywords
– Whitespace
C Stuff
– Literal
– Escape Sequence
– Variable
– Constant
– Data Type
– Type Qualifier
– Input/Output
– Operator Precedence & Associativity
C Stuff
– Types of Errors
– Selection Control
– Iteration Control
– Function
– Array
– Strings
– Structure
– Union
C Stuff
– Pointer
– Data Files
C Basic Structure
/* Comments */
Preprocessor Directives
Global Declaration
Function Main()
{
------------------------------
------------------------------
}
User-define Function
C Basic Structure
#include<...> //Header File
#include<...> //Header File
void main(void) //Main Function
{ //Start of Function
statement 1; //Function Body
statement 2; //Function Body
...
} //End of Function
C Pre-processor Directive
– Pre-processor directive is a keyword or statement which tells the compiler to
adjust or make addition to the written code for proper execution.
– Directive start with # (Hash) and does not end with : (semicolon).
– Some directives are:
– #include
– #include <filename.h> or #include “filename.extention”
– #define
– #define variableName value
– #if etc.
C Pre-processor Directive
– #include<filename.h>
– #include<stdio.h>
– Functions like prinft(), scanf(), getc(), putc(), fopen(), fclose(), remove(), fflush()
– #include<conio.h>
– Functions like clrscr(), getch(), getche(), textcolor(), textbackground()
– #include<math.h>
– Functions like sin(), cos(), tan(), pow(), sqrt(), cbrt(), exp(), log(), etc.
C Pre-processor Directive
– #define <VARIABLENAME> <value>
– #define PI 3.14
– Making a constant name PI having the value of 3.14
– #define FIRSTLETTER ‘a’
– Constant FIRSTLETTER that contains a
– #define CATCHPHRASE “I will be back.”
– A constant string stored in CATCHPHRASE
C Tokens
– A token is either a keyword, an identifier, a constant, a string literal, an operator
or a symbol.
– i.e. void main(void)
– Contains five (4) Tokens
– Token 1: void
– Token 2: main
– Token 3: (
– Token 4: )
C Semicolons
– Like in English language the period (.) symbol shows the end of the sentence in
C language semicolon (;) does the same.
– Semicolon is also called statement terminator.
– i.e. statement1;
– Here ; indicates that statement has ended
C Comments
– Comments are like helping text in your C program and they are ignored by the
compiler.
– There are two types of comments support by C
– Multiline Comments
– /* … …
– text
– … … */
– Single line Comments
– //text
C Character Set
– Set of alphabets, letters and some special characters that are valid in C
language.
– Alphabets
– A, B, C, …, Z
– a, b, c, …, z
– Digits
– 0, 1, 2, …, 9
– Symbols
– !, “, %, +, _, -, ., ?, /, #, ‘, @, ;, :, …
C Keywords
– Keywords are the reserved words whose meaning are already known to the
complier.
– Other name of Keywords is Reserved words.
– They cannot be used as Identifiers in program.
– There are 32 in total keywords in C.
C Keywords
Keyword Description
auto Define a local variable
break Pass the control out of iteration statement and switch
case Use in switch statement
char Data type for characters
const Unmodifiable variable
continue Used to skip certain statement in loop
default Used in switch case
do Do-while loop (iteration statement)
double Data type floating numbers double precision
else Decision making statement
C Keywords
Keyword Description
enum Define enumerated type data
extern Tell complier that variable declared somewhere else
float Data type for fraction numbers
for For loop (iteration statement)
goto Unconditional jump
if Decision making statement
int Data type for integer numbers
long Type modifier
register Store data in CPU register
return Return the flow of control back to calling function
C Keywords
Keyword Description
short Type modifier
signed Type modifier
sizeof Size of variable
static Variable that stay live till end of program
struct Collection of different data types
switch Decision making statement
typedef Define a new type
union Collection of different data types, that share common storage space
unsigned Type Modifier
void Means nothing
C Keywords
Keyword Description
volatile Used to indicate a volatile enity
while While loop (iteration statement)
C Whitespace
– Whitespace is the term used in C to describe blanks, tabs, newline characters
and comments.
– Whitespace separates one part of a statement from another and enables the
compiler to identify where one element ends in a statement.
– Whitespace also increases the readability of the text.
– i.e.
– Without whitespace intfloatchar
– With whitespace int float char
C Literal
– Literals are data used for representing fixed values.
– Integer
– 4, 99, 300002
– Floating
– 8.54, 67.32, 0.000019
– Character
– ‘a’, ‘R’, ‘h’, ‘P’
– String
– “C Program”, “Bell Telephone”, “Pakistan”
C Escape Sequence
– Sometimes, it is necessary to use characters that cannot be typed or has special
meaning in C programming.
Escape Sequence Character Escape Sequence Character
’ Single Quotation Mark ”
Double Quotation
Mark
? Question Mark  Backslash
0 Null Character b Backspace
f Form Feed n Newline
r Return t Horizontal Tab
v Vertical Tab
C Variable
– A variable is the name of the memory location, that is used to store data.
– Value in a variable can be changed, and can be reused many times.
– Rules of defining variable:
– A variable can have alphabets, digits, and underscore (_)
– A variable name either start with the alphabet, or underscore only.
– No whitespace is allowed within the variable name.
– If variable name has two different names the second name may start with capital.
– A variable name must not be any reserved word or keyword, i.e. int, goto, etc.
_salary, fatherName, table3.
C Variable
– Types of Variables
– Local/Automatic variable
– Variable declared with in function (keyword: auto)
– Global variable
– Variable declared outside the function
– Static variable
– Variable has the ability to retain the value in multiple function (keyword: static)
– External variable
– Variable that are declared in other files (keyword: extern)
C Variable
– Storage Classes
– It specify scope and lifetime of a variable within a program or function.
– Scope: as the region of a program in which a variable is available for use.
– Lifetime: duration of time in which a variable exists in the memory during execution.
Automatic Register Static External
Keyword auto register static extern
Scope Used within the function to which it belong Globally
Lifetime Same as the function’s lifetime Same as the program’s lifetime
Default value Initialized with garbage value Initialized with 0
C Constant
– Variable that cannot change its value throughout the program is called constant.
– There are two ways to make a variable constant.
– #define VARIABLENAME value
– const VARIABLENAME = value;
– #define is always a global constant where as const can be local or global.
– i.e.
– #define PI 3.14
– const PI = 3.14;
C Data Types
– Basic Data Types
– Int, float, double, char
– Extended Data Types
– Basic data types with short, long, signed, unsigned
– Other Data Types
– Bool, Enumerated, Complex, Derived
– Conversion of Data Types
– Type Casting
C Data Type
– Data types are declarations for variables. This determines the type and size of data
associated with variables.
– int Range: -32768 to 32767
– float Range: 3.4 e -38 to 3.4 e 38, double Range: 1.7 e -308 to 1.7 e 308
– char Range: -128 to 127
Data Type Size Description Example
int 2 byte Integer values int _table = 4;
float 4 byte Floating point value float temp = 36.9;
double 8 byte Double precision floating point values double test = 56.42349823;
char 1 byte Single character char letter4 = ‘d’;
C Data Type
– Format Specifier tells the compiler which type of data is about to display on
screen or should be taken from the user.
Data Type Format Specifier Example Format Specifier Example
int %d 3 %2d _3
float %f 45.000000 %.2f 45.00
double %lf 7.000000 %.3lf 7.000
char %c a %2c _a
C Type Qualifier
– Type qualifiers are used to declare the variables along with the data types.
– There are four (4) type qualifiers in C.
– long
– Increase the length of value
– short
– Default or decrease the length of value
– signed
– Both positive and negative values
– unsigned
– Only positive values
– Complex
– Only imaginary part.
– Header file: complex.h
– data_type complex variable_name = -1
C Data Type
– Extended Data Types
Data Type Range Size FS
long double at least 10, usually 12 or 16 %Lf
long int -2,147,483,648 to 2,147,483,647 at least 4, usually 8 %li
long long int at least 8 %lli
short int -32,768 to 32,767 2 usually %hd
signed char -128 to 127 1 %c
unsigned char 0 to 255 1 %c
unsigned int 0 to 65535 at least 2, usually 4 %u
unsigned long int 0 to 4,294,967,295 at least 4 %lu
unsigned long long int at least 8 %llu
unsigned short int 0 to 65,535 2
C Data Types
– Other Data Types
– Bool
– Only two possible values true or false.
– Header file: stdbool.h
– bool variable_name = true; or bool variable_name = false;
– Enumerated
– It is a user-define data type which restrict the user to have a set of defined values for a
variable.
– enum variable_name{const1, const2, ....... };
C Data Types
– Other Data Types
– Derived
– These data types are defined by user itself.
– These include Arrays, Structures,, Union, Pointers etc.
C Data Type
– Conversion of Data Types
First Operand Second Operand Result First Operand Second Operand Result
char char char char int int
char long int long int char float float
char double double int int int
int long int long int int float float
int double double long int float float
long int double double float float float
float double double double double double
C Data Type
– Type Casting
– Implicit
– Implicit conversions do not require any operator for converted. They are automatically
performed when a value is copied to a compatible type in the program.
– i.e. int a; float b; b = a;
– Explicit
– Many conversions, especially those that imply a different interpretation of the value, require
an explicit conversion. We have already seen two notations for explicit type conversion.
– i.e. int a; short b; b = (short) a;
C Input/Output
– Input
– scanf() is one of the commonly used functions to take input from the user. The scanf()
function reads formatted input from the standard input such as keyboards.
– scanf(“format Specifier”, &variable);
– Example:
– scanf(“%d”, &tableNo);
– scanf(“%f”, &temperature);
– scanf(“%c”, &eighthLetter);
C Input/Output
– Output
– printf() is one of the main output functions. The function sends formatted output to
the screen.
– printf(“Format_Specifier/String”, variable(s));
– Example:
– printf(“This is C Language Class”);
– printf(“Table no %d”, tableNo);
– printf(“%f current room Temperature”, temperature);
– printf(“D E F G %c I J K L”, eighthLetter);
C Program
A01, A02
#include<stdio.h>
void main( )
{
printf("Hello world");
}
#include<stdio.h>
void main( )
{
printf("Hellonworld");
}
C Program
A03
#include<stdio.h>
void main( )
{
int x=82;
float y=11.1;
char z='Z';
printf("x=%dny=%fnz=%c", x, y, z);
}
C Program
A04
#include<stdio.h>
void main( )
{
int x;
float y;
char z;
printf("Enter Integer, Floating-point and a character ");
scanf("%d %f %c", &x, &y, &z);
printf("x=%dny=%fnz=%c", x, y, z);
}
C Program
A05
#include<stdio.h>
void main( )
{
int x, y, z;
printf("Enter two Integer A and B: ");
scanf("%d %d", &x, &y);
z=x;
x=y;
y=z;
printf("A=%d B=%d", x, y);
}
C Operator Precedence &
Associativity
– Operator Precedence
– It describes the way in which the operations are evaluated. When we have several
operations in an expression, each part is evaluated are resolved in a predetermined
order decided by the operator precedence.
– Higher precedence operators always solved first.
– Associativity
– It defines the way in which the operator having some precedence are evaluated.
C Operator Precedence &
Associativity
Rank Operator Meaning Associativity
1
() Function Call Left to Right
[] Array Element Left to Right
-> Indirect Member Selection Left to Right
. Direct Member Selection Left to Right
2
! Logical Negation Right to Left
~ Bitwise Complement Right to Left
+ Unary Plus Right to Left
- Unary Minus Right to Left
++ Increment Right to Left
-- Decrement Right to Left
C Operator Precedence &
Associativity
Rank Operator Meaning Associativity
2
& Address of Operator Right to Left
* Pointer Reference Right to Left
sizeof Size of Object Right to Left
(type) Type Casting Right to Left
3
* Multiply Left to Right
/ Divide Left to Right
% Modulus Left to Right
4
+ Addition Left to Right
- Subtraction Left to Right
5 << Left Shift Left to Right
C Operator Precedence &
Associativity
Rank Operator Meaning Associativity
5 >> Right Shift Left to Right
6
< Less than Left to Right
<= Less than Equal Left to Right
> Greater than Left to Right
>= Greater than Equal Left to Right
7
== Equal Left to Right
!= Not Equal Left to Right
8 & Bitwise AND Left to Right
9 ^ Bitwise Exclusive OR Left to Right
10 | Bitwise OR Left to Right
C Operator Precedence &
Associativity
Rank Operator Meaning Associativity
11 && Logical AND Left to Right
12 || Logical OR Left to Right
13 ?: Conditional Operator Left to Right
14
= Assignment Operator Right to Left
*= Multiply Assignment Right to Left
/= Divide Assignment Right to Left
%= Modulus Assignment Right to Left
+= Addition Assignment Right to Left
-= Subtraction Assignment Right to Left
&= Bitwise AND Assignment Right to Left
C Operator Precedence &
Associativity
Rank Operator Meaning Associativity
14
^= Bitwise Exclusive OR Assignment Right to Left
|= Bitwise OR Assignment Right to Left
<<= Left Shift Assignment Right to Left
>>= Right Shift Assignment Right to Left
15 , Comma (Separator) Right to Left
C Operator Precedence &
Associativity
Operator Expression Output Operator Expression Output
!
a = 0;
a == 0;
!a == 0;
True
False
--
a = 1;
--a;
a--;
0
1
~
a=1;
~a; -2
* 1 * 2; 2
+
a = 1;
+a; +1
/ 4 / 2; 2
-
a = 1;
-a; -1
% 4 % 3; 1
++
a = 1;
++a;
a++;
2
1
+ 4 + 5; 9
C Operator Precedence &
Associativity
Operator Expression Output Operator Expression Output
- 6 – 4; 2
<=
4 <= 5
4 <= 4
5 <= 4
True
True
False
<< 3 << 2
0 0 1 1
1 1 _ _
12
>
5 > 4
4 > 5
True
False
>> 3 >> 2
0 0 1 1
_ _ 0 0
0
>=
5 >= 4
5 >=5
4 >=5
True
True
False
<
4 < 5
5 < 4
True
False
==
4 == 4
4 == 5
True
False
C Operator Precedence &
Associativity
Operator Expression Output Operator Expression Output
!=
4 != 5
4 != 4
True
False
|
12 | 5
1 1 0 0
0 1 0 1
1 1 0 1
13
&
12 & 5
1 1 0 0
0 1 0 1
0 1 0 0
4
&&
4 == 4 && 5 == 5
4 == 4 && 5 != 5
True
False
^
12 ^ 5
1 1 0 0
0 1 0 1
1 0 0 1
9
||
4 == 4 || 5 == 5
4 == 4 || 5 != 5
4 != 4 || 5 != 5
True
True
False
C Operator Precedence &
Associativity
Operator Expression Output Operator Expression Output
?:
4 == 4 ? 1 : 2
4 != 4 ? 1 : 2
1
2
-=
a -= 4; -2
= a = 2; 2 &= a &= 1; 0
*= a *= 4; 8 ^= a ^= 1; 3
/= a /= 2; 1 |= a |= 1; 3
%= a %= 4; 2 <<= a <<= 1; 4
+= a += 4; 6 >>= a >>= 1; 1
C Program
A06
#include<stdio.h>
void main( )
{
int x, y, sum, sub, mul, div, mod;
printf("Enter two Integer A and B: ");
scanf("%d %d", &x, &y);
sum=x+y;
sub=x-y;
mul=x*y;
div=x/y;
C Program
A06
mod=x%y;
printf("Sum of Two Integer is %d", sum);
printf("nDifference of Two Integer is %d", sub);
printf("nProduct of Two Integer is %d", mul);
printf("nDivision of Two Integer is %d", div);
printf("nRemainder of Two Integer is %d", mod);
}
C Program
A07
#include<stdio.h>
void main( )
{
int x;
int y;
printf("Enter an Integer A: ");
scanf("%d", &x);
y=++x;
printf("Pre-Increment %d", y);
C Program
A07
y=x++;
printf("nPost-Increment %d", y);
printf("nEnter an Integer B: ");
scanf("%d", &x);
y=--x;
printf("nPre-Decrement %d", y);
y=x--;
printf("nPost-Decrement %d", y);
}
C Types of Errors
– Error is an illegal operation performed by the user which results in the abnormal
working of the program.
– Programming errors often remain undetected until the program is compiled or
executed.
– The most common errors can be broadly classified as follows:
– Syntax
– Run Time
– Linker
– Logical
– Semantic
C Types of Errors
– Syntax
– Errors that occur when programmer violate the rules of writing C syntax are known as
syntax errors.
– These errors indicates something that must be fixed before the code can be compiled.
– All these errors are detected by the compiler and thus also known as compile-time errors.
– Run Time
– Errors which occur during program execution(run-time) after successful compilation are
called run-time errors.
– One of the most common run-time errors is division by zero also known as Division error.
– These types of error are hard to find as the compiler doesn’t point to the line at which the
error occurs.
C Types of Errors
– Linker
– These errors occur when after compilation we link the different object files with
main’s object using Ctrl+F9 key (RUN).
– These are errors generated when the executable of the program cannot be
generated.
– This may be due to wrong function prototyping, incorrect header files.
– One of the most common linker errors is writing Main() instead of main().
C Types of Errors
– Logical
– On compilation and execution of a program, the desired output is not obtained when
certain input values are given. These types of errors which provide incorrect output
but appears to be error-free are called logical errors.
– These are one of the most common errors done by beginners.
– These errors solely depend on the logical thinking of the programmer.
– Semantic
– This error occurs when the statements written in the program are not meaningful to
the compiler.
C Selection Control
– Selection control is way in programming language to control which statement should execute
or stop it/them from executing.
– There the three (3) main selection control in C:
– if
– Basic if
– Nested if
– if else
– Basic if else
– if else ladder
– Nested if else
– switch
C Selection Control
if
– Basic if
if (test expression)
{
// statements to be executed if the test
expression is true
}
– Nested if
if (test expression)
{
// statements to be executed if the
test expression is true
if (test expression)
{
// statements to be executed if the
test expression is true
}
}
C Selection Control
if else
– Basic if else
if (test expression)
{
// statements to be executed if the test
expression is true
}
else
{
// statements to be executed if the test
expression is false
}
– if else ladder
if (test expression)
{ // statements to be executed if the
test expression is true }
else if (test expression)
{ // statements to be executed if the
test expression is true } … … … …
else
{ // statements to be executed if the
test expression is false }
C Selection Control
if else
– Nested if else
if (test expression)
{ if (test expression) { // statements to be executed if the test expression is true } else { //
statements to be executed if the test expression is false } }
else if (test expression)
{ if (test expression) { // statements to be executed if the test expression is true } else { //
statements to be executed if the test expression is false } }
...
else
{ if (test expression) { // statements to be executed if the test expression is true } else { //
statements to be executed if the test expression is false } }
C Selection Control
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
... … … …
default:
// default statements
}
goto
label;
goto label;
C Program
A08
#include<stdio.h>
void main()
{
int x;
printf("Enter an Integer A: ");
scanf("%d", &x);
if(x<0)
{ printf("Number %d is a Negative integer", x); }
if(x>0)
{ printf("Number %d is a Positive integer", x); }
}
C Program
A09
#include<stdio.h>
void main()
{
int x, y;
printf("Enter two Integers A and B: ");
scanf("%d %d", &x, &y);
if(x<y)
{ printf("A = %d is less than B = %d", x, y); }
else
{ printf("A = %d is Greater than B = %d", x, y); }
}
C Program
A10
#include<stdio.h>
void main()
{
int x, y, z;
printf("Enter two Integers A and B: ");
scanf("%d %d", &x, &y);
printf("Enter 1 for Bitwise And, 2 for Bitwise Exclusive OR, 3 for Bitwise OR");
scanf("%d", &z);
switch(z)
{
case 1:
C Program
A10
printf("Bitwise And or A and B is %d", x&y);
break;
case 2:
printf("Bitwise Exclusive OR or A and B is %d", x^y);
break;
case 3:
printf("Bitwise OR or A and B is %d", x|y);
break;
}
}
C Iteration Control
– Iteration control is used to repeat a block of code until a specified condition is
met.
– Iteration control is also known as loop in programming languages.
– There are three (3) types of iteration control:
– for
– while
– do while
– Basic loops print 1D data where nested loops are used to print
multidimensional data.
C Iteration Control
– For
– Basic
for (initialization Statement; test Expression; update Statement)
{ // statements inside the body of the loop }
– Nested
for (initialization Statement; test Expression; update Statement)
{ for (initialization Statement; test Expression; update Statement)
{ // statements inside the body of the loop }
}
C Iteration Control
– while
while (test Expression)
{ // statements inside the body of the loop }
– do while
do
{
// statements inside the body of the loop
}while (test Expression);
C Iteration Control
– Break
– The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
– The break statement is almost always used with the if...else statement inside the
loop.
– Continue
– The continue statement skips the current iteration of the loop and continues with the
next iteration. Its syntax is: continue;
– The continue statement is almost always used with the if...else statement.
C Program
A11
#include<stdio.h>
void main()
{
int i;
printf("Even Numbers between 1 to 100n");
for(i=1; i<=100; i++)
{
if(i%2==0)
{ printf("%d ", i); }
}
}
C Program
A12
#include<stdio.h>
void main()
{
int i=1;
printf("Odd Numbers between 1 to 100n");
while(i<=100)
{
if(i%2!=0)
{ printf("%d ", i); }
i++;
}
}
C Program
A13
#include<stdio.h>
void main()
{
int i=1;
printf("Natural Numbers between 1 to 100n");
do
{
printf("%d ", i);
i++;
}while(i<=100);
}
C Function
– In C, we can divide a large program into the basic building blocks known as a
function.
– The function contains the set of programming statements enclosed by {}.
– A function can be called multiple times to provide reusability and modularity to
the C program.
– In other words, we can say that the collection of functions creates a program.
– The function is also known as procedure or subroutine in other programming
languages.
C Function
– There are two types of Functions in C:
– Standard Library Function
– printf(), scanf(), puts(), sqrt(), max(), gets(), pow(), etc.
– User Define Function
– It has three parts:
– Function Declaration
– Function Call
– Function Definition
C Function
– Types of User Define Function
– No arguments passed, no return value
– No arguments passed, return value
– Arguments passed, no return value
– Arguments passed, return value
C Function
– Function Declaration
– Outside main function
Return_Type function_Name (type1 argument1, type2 argument2, ...);
– Function Call
– Inside main function
function_Name (type1 argument1, type2 argument2, ...);
– Function Definition
– Outside main function
Return_Type function_Name (type1 argument1, type2 argument2, ...)
{ //body of the function }
C Function
– Return Statement
– The return statement terminates the execution of a function and returns a value to
the calling function.
– The program control is transferred to the calling function after the return statement.
– Syntax of the return statement: return (expression);
– The type of value returned from the function and the return type specified in the
function prototype and function definition must match.
C Function
– Recursion
– A process in which function call itself is known as recursion.
– There are two types of recursion
– Direct
– Function call itself within same function
– Indirect
– Function call itself through different funtion
C Program
A14
#include<stdio.h>
#include<math.h>
void main()
{
long int base, power, i;
printf("Enter the base and power: ");
scanf("%d %d", &base, &power);
i=pow(base,power);
printf("Answer is %d", i);
}
C Program
A15
#include<stdio.h>
float calArea(float);
void main()
{
float area, radius;
printf("Enter radius of a circle: ");
scanf("%f", &radius);
area=calArea(radius);
printf("Area of a circle is %f", area);
}
C Program
A15
float calArea(float r)
{
float i;
i=3.14*r*r;
return i;
}
C Array
– An array is a variable that can store multiple values of same data type.
– In memory block Arrays are the consecutive memory locations.
– Array can be one dimensional or multidimensional depending on the data.
– Syntax:
– One Dimensional Array: datatype arrayName [array_Size];
– Two Dimensional Array: datatype arrayName [array_Size1] [array_Size2];
C Array
– Array Initialization
– There are four ways to initialize Array
– Initialize array at the time of declaration (int a[4] = {10, 20, 30, 40};)
– Initialize all elements of an array with 0 (zero) (int a[10] = {0};)
– Initialize to define the size of an array (int a[] = {10, 20, 30, 40, 50};)
– Initialize array elements individually (int a[3]; a[0] = 10; a[1] = 20; a[2] = 30;)
– Access Array Elements
– You can access elements of an array by indices.
– Indices start from 0 to n-1
C Program
A16
#include<stdio.h>
void main()
{
int a[5], i, j;
printf("Enter five integer numbers: ");
for(i=0; i<5; i++)
{ scanf("%d", &a[i]); }
j=a[0];
i=1;
while(i<5)
C Program
A16
{
if(j<a[i])
{ j=a[i]; }
i++;
}
printf("%d is the biggest number you have entered", j);
}
C Strings
– A string is a sequence of characters terminated with a null character.
– char c [] = "c string";
– Commonly used string functions:
strcpy (s1, s2); Copies string s2 into string s1.
strcat (s1, s2); Concatenates string s2 onto the end of string s1.
strlen(s1); Returns the length of string s1.
strcmp (s1, s2); Returns 0 if s1 and s2 are the same; less than 1 if s1<s2; greater than 1 if s1>s2.
strchr (s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
strstr (s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
C Program
A17
#include<stdio.h>
void main()
{
char str[50];
int i=0;
printf("Enter the String: ");
gets(str);
while(str[i]!='0')
{
i++;
C Program
A17
}
i--;
printf("String in reverse: ");
while(i>=0)
{
printf("%c", str[i]);
i--;
}
}
C Structure
– The structure is another user-defined data type available in C that allows
combining data items of different kinds.
– Syntax:
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
C Program
A18
#include<stdio.h>
struct student
{
int roll;
float marks;
char name[50];
};
void main()
{
struct student s;
C Program
A18
printf("Enter Student Roll Number: ");
scanf("%d", &s.roll);
printf("Enter Student Name: ");
scanf("%s", &s.name);
printf("Enter Student Marks: ");
scanf("%f", &s.marks);
printf("nn");
printf("Roll Number: %d", s.roll);
printf("nStudent Name: %s", s.name);
printf("nStudent Marks: %f", s.marks);
}
C Union
– A union is a special data type available in C that allows storing different data types in the same
memory location.
– You can define a union with many members, but only one member can contain a value at any
given time.
– Unions provide an efficient way of using the same memory location for multiple-purpose.
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
C Program
A19
#include<stdio.h>
#include<string.h>
union book
{
int code;
float price;
char name[50];
};
void main()
{
C Program
A19
union book b;
printf("Enter Book code: ");
scanf("%d", &b.code);
strcpy(b.name,"C programming");
b.price=245.99;
printf("nn");
printf("Book Code: %d", b.code);
printf("nBook Name: %s", b.name);
printf("nBook Price: %f", b.price);
}
C Pointer
– A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location.
– Like any variable or constant, you must declare a pointer before using it to store any
variable address.
– The general form of a pointer variable declaration is data_type *var_name;
– There are 2 ways to use pointers:
– Call by reference
– Pass memory location of variable
– Call by value
– Pass value of variable
C Program
A20
#include<stdio.h>
void main()
{
int x, y, *p1, *p2;
printf("Enter Two Numbers: ");
scanf("%d %d", &x, &y);
p1=&x;
p2=&y;
printf("%d X %d = %d", *p1, *p2, (*p1)*(*p2));
}
C Data Files
– A file is a container in computer storage devices used for storing data.
– There are two type of Data Files:
– Text files
– Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
– Binary files
– Binary files are mostly the .bin files in your computer. Instead of storing data in plain text,
they store it in the binary form (0's and 1's).
– Functions: fopen(), fclose(), fread(), fwrite(), fseek()
C Program
A20
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c[60];
int no, n;
fp=fopen("initial.txt","a+");
printf("Enter the Student Name and Roll Number: ");
scanf("%s %d", c, &no);
C Program
A20
rewind(fp);
printf("Enter Student Roll Number: ");
scanf("%d", &n);
while(!feof(fp))
{
fscanf(fp,"%s %d", c, &no);
if(no==n)
{ printf("n%s n%d", c, no); }
}
fclose(fp); }
C Syntax
– #INCLUDE
#include <header name>
– ACCESSING AN ELEMENT OF A MULTIDIMENSIONAL ARRAY
array_name[index1][index2]; //index number starts from 0 to size-1
– ACCESSING AN ELEMENT OF AN ARRAY
array_name[index]; //index number starts from 0 to size-1
– ASSIGNMENT
identifier = value or identifier;
C Syntax
– BASIC C STRUCTURE
#include<...> //Header File
#include<...> //Header File
void main(void) //Main Function
{ //Start of Function
statement 1; //Function Body
statement 2; //Function Body
...
} //End of Function
C Syntax
– BREAK STATEMENT
break;
– CONTINUE STATEMENT
continue;
– CREATING CONSTANT
Const datatype IDENTIFIER = value; //For int, float, & double
Const datatype IDENTIFIER = ‘value’; //For char only
#define IDENTIFIER value //For int, float, & double
#define IDENTIFIER ‘value’ //For char only
C Syntax
– DECLARING A MULTIDIMENSIONAL ARRAY
datatype array_name[row][column];
– DECLARING AN ARRAY
datatype array_name[size];
– DO-WHILE LOOP
do
{
Statements;
} while(condition);
C Syntax
– FOR LOOP
for(variable initialization; condition; variable increment)
{
Statements;
}
– FUNCTION CALLING
function Name ([argname1, ...]);
– FUNCTION DECLARATION
return_datatype function Name( type [argname1], type [argname2], ...);
C Syntax
– FUNCTION DEFINITION
return_datatype function Name( type [argname1], type [argname2], ...)
{
Statements;
return(variable or argname); //If return datatype is not void
}
– GETTING THE ADDRESS STORED IN A POINTER
datatype identifier1 = &identifier;
C Syntax
– IF STATEMENT
if(conditional)
{
Statements;
}
– IF-ELSE-IF LADDER
if(condition)
{
Statements;
} else if(condition)
{
Statements;
} … else
{
Statements;
}
C Syntax
– INITIALIZING A MULTIDIMENSIONAL ARRAY
array_name[row][column]={{values}, {values}, {values}, ...};
– INITIALIZING AN ARRAY
array_name[size]={value1, value2, value3, ...};
– INPUT
scanf(“control String”, &variable list);
C Syntax
– MAIN FUNCTION
datatype main(argument)
{
statement 1; //Function Body
statement 2; //Function Body
...
}
C Syntax
– NESTED DO-WHILE LOOP
do
{
do
{
Statements;
} while(condition);
Statements;
} while(condition);
– NESTED FOR LOOP
for(variable initialization; condition; variable increment)
{
for(variable initialization; condition; variable increment)
{
Statements;
}
Statements;
}
C Syntax
– NESTED IF STATEMENT
if(condition)
{
if(condition)
{
Statements;
}
}
– NESTED WHILE LOOP
while(condition)
{
while(condition)
{
Statements;
}
Statements;
}
C Syntax
– POINTER DECLARATION
datatype *identifier;
– POINTER INITIALIZATION
datatype *identifier= value; //For int, float, double
datatype *identifier= ‘value’; //For char only
– PRINT
printf(“Control Statement”, Variable list);
C Syntax
– SWITCH-CASE STATEMENTS
switch(variable)
{
case constant 1: //constant can be number of ‘character’
Statements;
break;
case constant 2: //constant can be number of ‘character’
Statements;
break; … … … …
default:
statements;
}
C Syntax
– VARIABLE DECLARATION
Datatype identifier;
– VARIABLE INITIALIZATION
Identifier = value; //For int, float, & double
Identifier = ‘value’; //For char only
– WHILE LOOP
while(condition)
{
Statements;
}

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Overview of c language
Overview of c languageOverview of c language
Overview of c language
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Header files in c
Header files in cHeader files in c
Header files in c
 
Introduction of c programming
Introduction of c programmingIntroduction of c programming
Introduction of c programming
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
Why C is Called Structured Programming Language
Why C is Called Structured Programming LanguageWhy C is Called Structured Programming Language
Why C is Called Structured Programming Language
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
C Language
C LanguageC Language
C Language
 
class and objects
class and objectsclass and objects
class and objects
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Python PPT
Python PPTPython PPT
Python PPT
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
 
C#.NET
C#.NETC#.NET
C#.NET
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 

Similar a C Language

Similar a C Language (20)

PROGRAMMING IN C - SARASWATHI RAMALINGAM
PROGRAMMING IN C - SARASWATHI RAMALINGAMPROGRAMMING IN C - SARASWATHI RAMALINGAM
PROGRAMMING IN C - SARASWATHI RAMALINGAM
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDYC LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
C LANGUAGE UNIT-1 PREPARED BY M V BRAHMANANDA REDDY
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
Introduction to programming c
Introduction to programming cIntroduction to programming c
Introduction to programming c
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Part 1
Part 1Part 1
Part 1
 
Computer Programming In C.pptx
Computer Programming In C.pptxComputer Programming In C.pptx
Computer Programming In C.pptx
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Lesson 1
Lesson 1Lesson 1
Lesson 1
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharp
 
Introduction to c_sharp
Introduction to c_sharpIntroduction to c_sharp
Introduction to c_sharp
 
C_Intro.ppt
C_Intro.pptC_Intro.ppt
C_Intro.ppt
 
Basics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptxBasics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptx
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
 
What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it works
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 

Más de Syed Zaid Irshad

DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionSyed Zaid Irshad
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptxSyed Zaid Irshad
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxSyed Zaid Irshad
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in ComputingSyed Zaid Irshad
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xiSyed Zaid Irshad
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xiiSyed Zaid Irshad
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionSyed Zaid Irshad
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the LawSyed Zaid Irshad
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information TechnologySyed Zaid Irshad
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year BookSyed Zaid Irshad
 
Using subqueries to solve queries
Using subqueries to solve queriesUsing subqueries to solve queries
Using subqueries to solve queriesSyed Zaid Irshad
 

Más de Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 
Using subqueries to solve queries
Using subqueries to solve queriesUsing subqueries to solve queries
Using subqueries to solve queries
 

Último

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja 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
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
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
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
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
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
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
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
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
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
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
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 

Último (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .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
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
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
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
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)
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
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
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
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)
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 

C Language

  • 2. Outline – Program, Language, & Programming Language – Object Oriented Programming vs Procedure Oriented Programming – About C – Why still Learn C? – Basic Terms – C Stuff – C Syntax – C Program
  • 3. Program, Language, & Programming Language – Program – A series of coded software instructions to control the operation of a computer or other machine. – Language – A system of symbols and rules for writing programs or algorithms. – Programming Language – A programming language is a vocabulary and set of grammatical rules for instructing a computer or computing device to perform specific tasks. The term programming language usually refers to high-level languages, such as BASIC, C, C++, COBOL, Java, FORTRAN, Ada, and Pascal.
  • 4. Object Oriented Programming vs Procedure Oriented Programming – Object oriented Programming – Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior. – Procedure Oriented Programming – A procedural language is a computer programming language that follows, in order, a set of commands.
  • 5. Object Oriented Programming vs Procedure Oriented Programming Parameter POP OOP Focus Procedures Data Approach Top-down Bottom-up Program Decomposition Into Functions Into Objects Access Modes No modes Private, Public, & Protected Data Hiding No Hiding Support Hiding Data Movement Function to function Only with member function Example C, COBOL, FORTRAN C++, Java, SmallTalk
  • 6. About C – Introduction – Applications/Products that use C – Features of C – Drawbacks of C
  • 7. Introduction – C is a general-purpose, Mid-level, procedure-oriented programming language development by Dennis Ritchie in 1972 at Bell Telephone Laboratories (AT&T Bell Laboratories). – Previous languages BCPL and B from C is evolved are type less languages. C introduced the concept of data types and other features. – C language uses complier (it converts code into binary language). – In 2011 C11 was released and in 2018 the refined version called C18 was introduced.
  • 8. Applications/Products that use C – Operating Systems – Unix OS, and Linux Kernel – Mobile Operating System – Some parts of Android OS – Databases – Some Portion of Oracle, and MySQL – Programming Languages – C++, Java, C#, Python, Ruby initially implemented in C.
  • 9. Features of C – General-Purpose Programming Language – Can develop various applications of different domain – Portable Language – Program can be run on other computers having same environment – Block-Structured Language – It allows a large program to be divide into small sections called functions – Mid-level Language – It contains both high and low level language features
  • 10. Features of C – Extensible – We can add more functionality to C – Reliable – It is more reliable (good in quality and performance) that its evolved versions – Typed Language – It uses the data types and strong data definition – Powerful Operator Support – It supports vast number of operators
  • 11. Features of C – Vast Built-in Library – C contains huge built-in library to support functionality – Hardware Interaction – C can directly interact with hardware for faster execution – Graphical Application – It also support graphical programming – Relation with Assembly – C can be used to directly write assembly code
  • 12. Drawbacks of C – C does not support OOP – C does not support runtime checking (RTC) – Detect runtime errors, such as memory access errors and memory leak, in a native code application during the development phase. – C is not a strictly typed language – C does not provide any data security – C does not have the concept of namespace – Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
  • 13. Why still Learn C? – All modern programming languages are influenced by C. – C++, Java, Python all have same basic structure like C. – If you can fully absorb C you can easily learn any programming language. – Also C has a variety of offerings like: – You can program a microcontroller that can perform a simple task like switching on/off a light or a medical device that can give you heart rate. – Can develop an OS kernel or whole software for a supercomputer.
  • 14. Basic Terms – Source Code – Source code is a code which is written by programmer in a human-readable form with proper programming syntaxes. – Executable code – Executable code is the machine-readable code which can be executed directly by the machine. – Compiler – A compiler is a software module that converts source code of the program into executable code. – Compile Time – The time required for the compilation of the source code of a program.
  • 15. Basic Terms – Run Time – The time takin by the program during execution. – Object code – When dealing large program, it gets divided into subprograms. These subprograms create object code after compilation. – Linker – Linker links all the object codes to produce executable code. – Loader – Part of a compiler which is responsible for loading the executable code in main memory for execution.
  • 16. Basic Terms – Built-in Library – It is a collection of predefined functions available to help the programmers to write a good and efficient program – Header files – A file that contains declaration of library functions, global variables and Marco definition
  • 17. C Stuff – Basic Structure – Processor Directive – Tokens – Semicolon – Comments – Character Set – Keywords – Whitespace
  • 18. C Stuff – Literal – Escape Sequence – Variable – Constant – Data Type – Type Qualifier – Input/Output – Operator Precedence & Associativity
  • 19. C Stuff – Types of Errors – Selection Control – Iteration Control – Function – Array – Strings – Structure – Union
  • 21. C Basic Structure /* Comments */ Preprocessor Directives Global Declaration Function Main() { ------------------------------ ------------------------------ } User-define Function
  • 22. C Basic Structure #include<...> //Header File #include<...> //Header File void main(void) //Main Function { //Start of Function statement 1; //Function Body statement 2; //Function Body ... } //End of Function
  • 23. C Pre-processor Directive – Pre-processor directive is a keyword or statement which tells the compiler to adjust or make addition to the written code for proper execution. – Directive start with # (Hash) and does not end with : (semicolon). – Some directives are: – #include – #include <filename.h> or #include “filename.extention” – #define – #define variableName value – #if etc.
  • 24. C Pre-processor Directive – #include<filename.h> – #include<stdio.h> – Functions like prinft(), scanf(), getc(), putc(), fopen(), fclose(), remove(), fflush() – #include<conio.h> – Functions like clrscr(), getch(), getche(), textcolor(), textbackground() – #include<math.h> – Functions like sin(), cos(), tan(), pow(), sqrt(), cbrt(), exp(), log(), etc.
  • 25. C Pre-processor Directive – #define <VARIABLENAME> <value> – #define PI 3.14 – Making a constant name PI having the value of 3.14 – #define FIRSTLETTER ‘a’ – Constant FIRSTLETTER that contains a – #define CATCHPHRASE “I will be back.” – A constant string stored in CATCHPHRASE
  • 26. C Tokens – A token is either a keyword, an identifier, a constant, a string literal, an operator or a symbol. – i.e. void main(void) – Contains five (4) Tokens – Token 1: void – Token 2: main – Token 3: ( – Token 4: )
  • 27. C Semicolons – Like in English language the period (.) symbol shows the end of the sentence in C language semicolon (;) does the same. – Semicolon is also called statement terminator. – i.e. statement1; – Here ; indicates that statement has ended
  • 28. C Comments – Comments are like helping text in your C program and they are ignored by the compiler. – There are two types of comments support by C – Multiline Comments – /* … … – text – … … */ – Single line Comments – //text
  • 29. C Character Set – Set of alphabets, letters and some special characters that are valid in C language. – Alphabets – A, B, C, …, Z – a, b, c, …, z – Digits – 0, 1, 2, …, 9 – Symbols – !, “, %, +, _, -, ., ?, /, #, ‘, @, ;, :, …
  • 30. C Keywords – Keywords are the reserved words whose meaning are already known to the complier. – Other name of Keywords is Reserved words. – They cannot be used as Identifiers in program. – There are 32 in total keywords in C.
  • 31. C Keywords Keyword Description auto Define a local variable break Pass the control out of iteration statement and switch case Use in switch statement char Data type for characters const Unmodifiable variable continue Used to skip certain statement in loop default Used in switch case do Do-while loop (iteration statement) double Data type floating numbers double precision else Decision making statement
  • 32. C Keywords Keyword Description enum Define enumerated type data extern Tell complier that variable declared somewhere else float Data type for fraction numbers for For loop (iteration statement) goto Unconditional jump if Decision making statement int Data type for integer numbers long Type modifier register Store data in CPU register return Return the flow of control back to calling function
  • 33. C Keywords Keyword Description short Type modifier signed Type modifier sizeof Size of variable static Variable that stay live till end of program struct Collection of different data types switch Decision making statement typedef Define a new type union Collection of different data types, that share common storage space unsigned Type Modifier void Means nothing
  • 34. C Keywords Keyword Description volatile Used to indicate a volatile enity while While loop (iteration statement)
  • 35. C Whitespace – Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. – Whitespace separates one part of a statement from another and enables the compiler to identify where one element ends in a statement. – Whitespace also increases the readability of the text. – i.e. – Without whitespace intfloatchar – With whitespace int float char
  • 36. C Literal – Literals are data used for representing fixed values. – Integer – 4, 99, 300002 – Floating – 8.54, 67.32, 0.000019 – Character – ‘a’, ‘R’, ‘h’, ‘P’ – String – “C Program”, “Bell Telephone”, “Pakistan”
  • 37. C Escape Sequence – Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C programming. Escape Sequence Character Escape Sequence Character ’ Single Quotation Mark ” Double Quotation Mark ? Question Mark Backslash 0 Null Character b Backspace f Form Feed n Newline r Return t Horizontal Tab v Vertical Tab
  • 38. C Variable – A variable is the name of the memory location, that is used to store data. – Value in a variable can be changed, and can be reused many times. – Rules of defining variable: – A variable can have alphabets, digits, and underscore (_) – A variable name either start with the alphabet, or underscore only. – No whitespace is allowed within the variable name. – If variable name has two different names the second name may start with capital. – A variable name must not be any reserved word or keyword, i.e. int, goto, etc. _salary, fatherName, table3.
  • 39. C Variable – Types of Variables – Local/Automatic variable – Variable declared with in function (keyword: auto) – Global variable – Variable declared outside the function – Static variable – Variable has the ability to retain the value in multiple function (keyword: static) – External variable – Variable that are declared in other files (keyword: extern)
  • 40. C Variable – Storage Classes – It specify scope and lifetime of a variable within a program or function. – Scope: as the region of a program in which a variable is available for use. – Lifetime: duration of time in which a variable exists in the memory during execution. Automatic Register Static External Keyword auto register static extern Scope Used within the function to which it belong Globally Lifetime Same as the function’s lifetime Same as the program’s lifetime Default value Initialized with garbage value Initialized with 0
  • 41. C Constant – Variable that cannot change its value throughout the program is called constant. – There are two ways to make a variable constant. – #define VARIABLENAME value – const VARIABLENAME = value; – #define is always a global constant where as const can be local or global. – i.e. – #define PI 3.14 – const PI = 3.14;
  • 42. C Data Types – Basic Data Types – Int, float, double, char – Extended Data Types – Basic data types with short, long, signed, unsigned – Other Data Types – Bool, Enumerated, Complex, Derived – Conversion of Data Types – Type Casting
  • 43. C Data Type – Data types are declarations for variables. This determines the type and size of data associated with variables. – int Range: -32768 to 32767 – float Range: 3.4 e -38 to 3.4 e 38, double Range: 1.7 e -308 to 1.7 e 308 – char Range: -128 to 127 Data Type Size Description Example int 2 byte Integer values int _table = 4; float 4 byte Floating point value float temp = 36.9; double 8 byte Double precision floating point values double test = 56.42349823; char 1 byte Single character char letter4 = ‘d’;
  • 44. C Data Type – Format Specifier tells the compiler which type of data is about to display on screen or should be taken from the user. Data Type Format Specifier Example Format Specifier Example int %d 3 %2d _3 float %f 45.000000 %.2f 45.00 double %lf 7.000000 %.3lf 7.000 char %c a %2c _a
  • 45. C Type Qualifier – Type qualifiers are used to declare the variables along with the data types. – There are four (4) type qualifiers in C. – long – Increase the length of value – short – Default or decrease the length of value – signed – Both positive and negative values – unsigned – Only positive values – Complex – Only imaginary part. – Header file: complex.h – data_type complex variable_name = -1
  • 46. C Data Type – Extended Data Types Data Type Range Size FS long double at least 10, usually 12 or 16 %Lf long int -2,147,483,648 to 2,147,483,647 at least 4, usually 8 %li long long int at least 8 %lli short int -32,768 to 32,767 2 usually %hd signed char -128 to 127 1 %c unsigned char 0 to 255 1 %c unsigned int 0 to 65535 at least 2, usually 4 %u unsigned long int 0 to 4,294,967,295 at least 4 %lu unsigned long long int at least 8 %llu unsigned short int 0 to 65,535 2
  • 47. C Data Types – Other Data Types – Bool – Only two possible values true or false. – Header file: stdbool.h – bool variable_name = true; or bool variable_name = false; – Enumerated – It is a user-define data type which restrict the user to have a set of defined values for a variable. – enum variable_name{const1, const2, ....... };
  • 48. C Data Types – Other Data Types – Derived – These data types are defined by user itself. – These include Arrays, Structures,, Union, Pointers etc.
  • 49. C Data Type – Conversion of Data Types First Operand Second Operand Result First Operand Second Operand Result char char char char int int char long int long int char float float char double double int int int int long int long int int float float int double double long int float float long int double double float float float float double double double double double
  • 50. C Data Type – Type Casting – Implicit – Implicit conversions do not require any operator for converted. They are automatically performed when a value is copied to a compatible type in the program. – i.e. int a; float b; b = a; – Explicit – Many conversions, especially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion. – i.e. int a; short b; b = (short) a;
  • 51. C Input/Output – Input – scanf() is one of the commonly used functions to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. – scanf(“format Specifier”, &variable); – Example: – scanf(“%d”, &tableNo); – scanf(“%f”, &temperature); – scanf(“%c”, &eighthLetter);
  • 52. C Input/Output – Output – printf() is one of the main output functions. The function sends formatted output to the screen. – printf(“Format_Specifier/String”, variable(s)); – Example: – printf(“This is C Language Class”); – printf(“Table no %d”, tableNo); – printf(“%f current room Temperature”, temperature); – printf(“D E F G %c I J K L”, eighthLetter);
  • 53. C Program A01, A02 #include<stdio.h> void main( ) { printf("Hello world"); } #include<stdio.h> void main( ) { printf("Hellonworld"); }
  • 54. C Program A03 #include<stdio.h> void main( ) { int x=82; float y=11.1; char z='Z'; printf("x=%dny=%fnz=%c", x, y, z); }
  • 55. C Program A04 #include<stdio.h> void main( ) { int x; float y; char z; printf("Enter Integer, Floating-point and a character "); scanf("%d %f %c", &x, &y, &z); printf("x=%dny=%fnz=%c", x, y, z); }
  • 56. C Program A05 #include<stdio.h> void main( ) { int x, y, z; printf("Enter two Integer A and B: "); scanf("%d %d", &x, &y); z=x; x=y; y=z; printf("A=%d B=%d", x, y); }
  • 57. C Operator Precedence & Associativity – Operator Precedence – It describes the way in which the operations are evaluated. When we have several operations in an expression, each part is evaluated are resolved in a predetermined order decided by the operator precedence. – Higher precedence operators always solved first. – Associativity – It defines the way in which the operator having some precedence are evaluated.
  • 58. C Operator Precedence & Associativity Rank Operator Meaning Associativity 1 () Function Call Left to Right [] Array Element Left to Right -> Indirect Member Selection Left to Right . Direct Member Selection Left to Right 2 ! Logical Negation Right to Left ~ Bitwise Complement Right to Left + Unary Plus Right to Left - Unary Minus Right to Left ++ Increment Right to Left -- Decrement Right to Left
  • 59. C Operator Precedence & Associativity Rank Operator Meaning Associativity 2 & Address of Operator Right to Left * Pointer Reference Right to Left sizeof Size of Object Right to Left (type) Type Casting Right to Left 3 * Multiply Left to Right / Divide Left to Right % Modulus Left to Right 4 + Addition Left to Right - Subtraction Left to Right 5 << Left Shift Left to Right
  • 60. C Operator Precedence & Associativity Rank Operator Meaning Associativity 5 >> Right Shift Left to Right 6 < Less than Left to Right <= Less than Equal Left to Right > Greater than Left to Right >= Greater than Equal Left to Right 7 == Equal Left to Right != Not Equal Left to Right 8 & Bitwise AND Left to Right 9 ^ Bitwise Exclusive OR Left to Right 10 | Bitwise OR Left to Right
  • 61. C Operator Precedence & Associativity Rank Operator Meaning Associativity 11 && Logical AND Left to Right 12 || Logical OR Left to Right 13 ?: Conditional Operator Left to Right 14 = Assignment Operator Right to Left *= Multiply Assignment Right to Left /= Divide Assignment Right to Left %= Modulus Assignment Right to Left += Addition Assignment Right to Left -= Subtraction Assignment Right to Left &= Bitwise AND Assignment Right to Left
  • 62. C Operator Precedence & Associativity Rank Operator Meaning Associativity 14 ^= Bitwise Exclusive OR Assignment Right to Left |= Bitwise OR Assignment Right to Left <<= Left Shift Assignment Right to Left >>= Right Shift Assignment Right to Left 15 , Comma (Separator) Right to Left
  • 63. C Operator Precedence & Associativity Operator Expression Output Operator Expression Output ! a = 0; a == 0; !a == 0; True False -- a = 1; --a; a--; 0 1 ~ a=1; ~a; -2 * 1 * 2; 2 + a = 1; +a; +1 / 4 / 2; 2 - a = 1; -a; -1 % 4 % 3; 1 ++ a = 1; ++a; a++; 2 1 + 4 + 5; 9
  • 64. C Operator Precedence & Associativity Operator Expression Output Operator Expression Output - 6 – 4; 2 <= 4 <= 5 4 <= 4 5 <= 4 True True False << 3 << 2 0 0 1 1 1 1 _ _ 12 > 5 > 4 4 > 5 True False >> 3 >> 2 0 0 1 1 _ _ 0 0 0 >= 5 >= 4 5 >=5 4 >=5 True True False < 4 < 5 5 < 4 True False == 4 == 4 4 == 5 True False
  • 65. C Operator Precedence & Associativity Operator Expression Output Operator Expression Output != 4 != 5 4 != 4 True False | 12 | 5 1 1 0 0 0 1 0 1 1 1 0 1 13 & 12 & 5 1 1 0 0 0 1 0 1 0 1 0 0 4 && 4 == 4 && 5 == 5 4 == 4 && 5 != 5 True False ^ 12 ^ 5 1 1 0 0 0 1 0 1 1 0 0 1 9 || 4 == 4 || 5 == 5 4 == 4 || 5 != 5 4 != 4 || 5 != 5 True True False
  • 66. C Operator Precedence & Associativity Operator Expression Output Operator Expression Output ?: 4 == 4 ? 1 : 2 4 != 4 ? 1 : 2 1 2 -= a -= 4; -2 = a = 2; 2 &= a &= 1; 0 *= a *= 4; 8 ^= a ^= 1; 3 /= a /= 2; 1 |= a |= 1; 3 %= a %= 4; 2 <<= a <<= 1; 4 += a += 4; 6 >>= a >>= 1; 1
  • 67. C Program A06 #include<stdio.h> void main( ) { int x, y, sum, sub, mul, div, mod; printf("Enter two Integer A and B: "); scanf("%d %d", &x, &y); sum=x+y; sub=x-y; mul=x*y; div=x/y;
  • 68. C Program A06 mod=x%y; printf("Sum of Two Integer is %d", sum); printf("nDifference of Two Integer is %d", sub); printf("nProduct of Two Integer is %d", mul); printf("nDivision of Two Integer is %d", div); printf("nRemainder of Two Integer is %d", mod); }
  • 69. C Program A07 #include<stdio.h> void main( ) { int x; int y; printf("Enter an Integer A: "); scanf("%d", &x); y=++x; printf("Pre-Increment %d", y);
  • 70. C Program A07 y=x++; printf("nPost-Increment %d", y); printf("nEnter an Integer B: "); scanf("%d", &x); y=--x; printf("nPre-Decrement %d", y); y=x--; printf("nPost-Decrement %d", y); }
  • 71. C Types of Errors – Error is an illegal operation performed by the user which results in the abnormal working of the program. – Programming errors often remain undetected until the program is compiled or executed. – The most common errors can be broadly classified as follows: – Syntax – Run Time – Linker – Logical – Semantic
  • 72. C Types of Errors – Syntax – Errors that occur when programmer violate the rules of writing C syntax are known as syntax errors. – These errors indicates something that must be fixed before the code can be compiled. – All these errors are detected by the compiler and thus also known as compile-time errors. – Run Time – Errors which occur during program execution(run-time) after successful compilation are called run-time errors. – One of the most common run-time errors is division by zero also known as Division error. – These types of error are hard to find as the compiler doesn’t point to the line at which the error occurs.
  • 73. C Types of Errors – Linker – These errors occur when after compilation we link the different object files with main’s object using Ctrl+F9 key (RUN). – These are errors generated when the executable of the program cannot be generated. – This may be due to wrong function prototyping, incorrect header files. – One of the most common linker errors is writing Main() instead of main().
  • 74. C Types of Errors – Logical – On compilation and execution of a program, the desired output is not obtained when certain input values are given. These types of errors which provide incorrect output but appears to be error-free are called logical errors. – These are one of the most common errors done by beginners. – These errors solely depend on the logical thinking of the programmer. – Semantic – This error occurs when the statements written in the program are not meaningful to the compiler.
  • 75. C Selection Control – Selection control is way in programming language to control which statement should execute or stop it/them from executing. – There the three (3) main selection control in C: – if – Basic if – Nested if – if else – Basic if else – if else ladder – Nested if else – switch
  • 76. C Selection Control if – Basic if if (test expression) { // statements to be executed if the test expression is true } – Nested if if (test expression) { // statements to be executed if the test expression is true if (test expression) { // statements to be executed if the test expression is true } }
  • 77. C Selection Control if else – Basic if else if (test expression) { // statements to be executed if the test expression is true } else { // statements to be executed if the test expression is false } – if else ladder if (test expression) { // statements to be executed if the test expression is true } else if (test expression) { // statements to be executed if the test expression is true } … … … … else { // statements to be executed if the test expression is false }
  • 78. C Selection Control if else – Nested if else if (test expression) { if (test expression) { // statements to be executed if the test expression is true } else { // statements to be executed if the test expression is false } } else if (test expression) { if (test expression) { // statements to be executed if the test expression is true } else { // statements to be executed if the test expression is false } } ... else { if (test expression) { // statements to be executed if the test expression is true } else { // statements to be executed if the test expression is false } }
  • 79. C Selection Control switch (expression) { case constant1: // statements break; case constant2: // statements break; ... … … … default: // default statements } goto label; goto label;
  • 80. C Program A08 #include<stdio.h> void main() { int x; printf("Enter an Integer A: "); scanf("%d", &x); if(x<0) { printf("Number %d is a Negative integer", x); } if(x>0) { printf("Number %d is a Positive integer", x); } }
  • 81. C Program A09 #include<stdio.h> void main() { int x, y; printf("Enter two Integers A and B: "); scanf("%d %d", &x, &y); if(x<y) { printf("A = %d is less than B = %d", x, y); } else { printf("A = %d is Greater than B = %d", x, y); } }
  • 82. C Program A10 #include<stdio.h> void main() { int x, y, z; printf("Enter two Integers A and B: "); scanf("%d %d", &x, &y); printf("Enter 1 for Bitwise And, 2 for Bitwise Exclusive OR, 3 for Bitwise OR"); scanf("%d", &z); switch(z) { case 1:
  • 83. C Program A10 printf("Bitwise And or A and B is %d", x&y); break; case 2: printf("Bitwise Exclusive OR or A and B is %d", x^y); break; case 3: printf("Bitwise OR or A and B is %d", x|y); break; } }
  • 84. C Iteration Control – Iteration control is used to repeat a block of code until a specified condition is met. – Iteration control is also known as loop in programming languages. – There are three (3) types of iteration control: – for – while – do while – Basic loops print 1D data where nested loops are used to print multidimensional data.
  • 85. C Iteration Control – For – Basic for (initialization Statement; test Expression; update Statement) { // statements inside the body of the loop } – Nested for (initialization Statement; test Expression; update Statement) { for (initialization Statement; test Expression; update Statement) { // statements inside the body of the loop } }
  • 86. C Iteration Control – while while (test Expression) { // statements inside the body of the loop } – do while do { // statements inside the body of the loop }while (test Expression);
  • 87. C Iteration Control – Break – The break statement ends the loop immediately when it is encountered. Its syntax is: break; – The break statement is almost always used with the if...else statement inside the loop. – Continue – The continue statement skips the current iteration of the loop and continues with the next iteration. Its syntax is: continue; – The continue statement is almost always used with the if...else statement.
  • 88. C Program A11 #include<stdio.h> void main() { int i; printf("Even Numbers between 1 to 100n"); for(i=1; i<=100; i++) { if(i%2==0) { printf("%d ", i); } } }
  • 89. C Program A12 #include<stdio.h> void main() { int i=1; printf("Odd Numbers between 1 to 100n"); while(i<=100) { if(i%2!=0) { printf("%d ", i); } i++; } }
  • 90. C Program A13 #include<stdio.h> void main() { int i=1; printf("Natural Numbers between 1 to 100n"); do { printf("%d ", i); i++; }while(i<=100); }
  • 91. C Function – In C, we can divide a large program into the basic building blocks known as a function. – The function contains the set of programming statements enclosed by {}. – A function can be called multiple times to provide reusability and modularity to the C program. – In other words, we can say that the collection of functions creates a program. – The function is also known as procedure or subroutine in other programming languages.
  • 92. C Function – There are two types of Functions in C: – Standard Library Function – printf(), scanf(), puts(), sqrt(), max(), gets(), pow(), etc. – User Define Function – It has three parts: – Function Declaration – Function Call – Function Definition
  • 93. C Function – Types of User Define Function – No arguments passed, no return value – No arguments passed, return value – Arguments passed, no return value – Arguments passed, return value
  • 94. C Function – Function Declaration – Outside main function Return_Type function_Name (type1 argument1, type2 argument2, ...); – Function Call – Inside main function function_Name (type1 argument1, type2 argument2, ...); – Function Definition – Outside main function Return_Type function_Name (type1 argument1, type2 argument2, ...) { //body of the function }
  • 95. C Function – Return Statement – The return statement terminates the execution of a function and returns a value to the calling function. – The program control is transferred to the calling function after the return statement. – Syntax of the return statement: return (expression); – The type of value returned from the function and the return type specified in the function prototype and function definition must match.
  • 96. C Function – Recursion – A process in which function call itself is known as recursion. – There are two types of recursion – Direct – Function call itself within same function – Indirect – Function call itself through different funtion
  • 97. C Program A14 #include<stdio.h> #include<math.h> void main() { long int base, power, i; printf("Enter the base and power: "); scanf("%d %d", &base, &power); i=pow(base,power); printf("Answer is %d", i); }
  • 98. C Program A15 #include<stdio.h> float calArea(float); void main() { float area, radius; printf("Enter radius of a circle: "); scanf("%f", &radius); area=calArea(radius); printf("Area of a circle is %f", area); }
  • 99. C Program A15 float calArea(float r) { float i; i=3.14*r*r; return i; }
  • 100. C Array – An array is a variable that can store multiple values of same data type. – In memory block Arrays are the consecutive memory locations. – Array can be one dimensional or multidimensional depending on the data. – Syntax: – One Dimensional Array: datatype arrayName [array_Size]; – Two Dimensional Array: datatype arrayName [array_Size1] [array_Size2];
  • 101. C Array – Array Initialization – There are four ways to initialize Array – Initialize array at the time of declaration (int a[4] = {10, 20, 30, 40};) – Initialize all elements of an array with 0 (zero) (int a[10] = {0};) – Initialize to define the size of an array (int a[] = {10, 20, 30, 40, 50};) – Initialize array elements individually (int a[3]; a[0] = 10; a[1] = 20; a[2] = 30;) – Access Array Elements – You can access elements of an array by indices. – Indices start from 0 to n-1
  • 102. C Program A16 #include<stdio.h> void main() { int a[5], i, j; printf("Enter five integer numbers: "); for(i=0; i<5; i++) { scanf("%d", &a[i]); } j=a[0]; i=1; while(i<5)
  • 103. C Program A16 { if(j<a[i]) { j=a[i]; } i++; } printf("%d is the biggest number you have entered", j); }
  • 104. C Strings – A string is a sequence of characters terminated with a null character. – char c [] = "c string"; – Commonly used string functions: strcpy (s1, s2); Copies string s2 into string s1. strcat (s1, s2); Concatenates string s2 onto the end of string s1. strlen(s1); Returns the length of string s1. strcmp (s1, s2); Returns 0 if s1 and s2 are the same; less than 1 if s1<s2; greater than 1 if s1>s2. strchr (s1, ch); Returns a pointer to the first occurrence of character ch in string s1. strstr (s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
  • 105. C Program A17 #include<stdio.h> void main() { char str[50]; int i=0; printf("Enter the String: "); gets(str); while(str[i]!='0') { i++;
  • 106. C Program A17 } i--; printf("String in reverse: "); while(i>=0) { printf("%c", str[i]); i--; } }
  • 107. C Structure – The structure is another user-defined data type available in C that allows combining data items of different kinds. – Syntax: struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables];
  • 108. C Program A18 #include<stdio.h> struct student { int roll; float marks; char name[50]; }; void main() { struct student s;
  • 109. C Program A18 printf("Enter Student Roll Number: "); scanf("%d", &s.roll); printf("Enter Student Name: "); scanf("%s", &s.name); printf("Enter Student Marks: "); scanf("%f", &s.marks); printf("nn"); printf("Roll Number: %d", s.roll); printf("nStudent Name: %s", s.name); printf("nStudent Marks: %f", s.marks); }
  • 110. C Union – A union is a special data type available in C that allows storing different data types in the same memory location. – You can define a union with many members, but only one member can contain a value at any given time. – Unions provide an efficient way of using the same memory location for multiple-purpose. union [union tag] { member definition; member definition; ... member definition; } [one or more union variables];
  • 111. C Program A19 #include<stdio.h> #include<string.h> union book { int code; float price; char name[50]; }; void main() {
  • 112. C Program A19 union book b; printf("Enter Book code: "); scanf("%d", &b.code); strcpy(b.name,"C programming"); b.price=245.99; printf("nn"); printf("Book Code: %d", b.code); printf("nBook Name: %s", b.name); printf("nBook Price: %f", b.price); }
  • 113. C Pointer – A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. – Like any variable or constant, you must declare a pointer before using it to store any variable address. – The general form of a pointer variable declaration is data_type *var_name; – There are 2 ways to use pointers: – Call by reference – Pass memory location of variable – Call by value – Pass value of variable
  • 114. C Program A20 #include<stdio.h> void main() { int x, y, *p1, *p2; printf("Enter Two Numbers: "); scanf("%d %d", &x, &y); p1=&x; p2=&y; printf("%d X %d = %d", *p1, *p2, (*p1)*(*p2)); }
  • 115. C Data Files – A file is a container in computer storage devices used for storing data. – There are two type of Data Files: – Text files – Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad. – Binary files – Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store it in the binary form (0's and 1's). – Functions: fopen(), fclose(), fread(), fwrite(), fseek()
  • 116. C Program A20 #include<stdio.h> #include<conio.h> void main() { FILE *fp; char c[60]; int no, n; fp=fopen("initial.txt","a+"); printf("Enter the Student Name and Roll Number: "); scanf("%s %d", c, &no);
  • 117. C Program A20 rewind(fp); printf("Enter Student Roll Number: "); scanf("%d", &n); while(!feof(fp)) { fscanf(fp,"%s %d", c, &no); if(no==n) { printf("n%s n%d", c, no); } } fclose(fp); }
  • 118. C Syntax – #INCLUDE #include <header name> – ACCESSING AN ELEMENT OF A MULTIDIMENSIONAL ARRAY array_name[index1][index2]; //index number starts from 0 to size-1 – ACCESSING AN ELEMENT OF AN ARRAY array_name[index]; //index number starts from 0 to size-1 – ASSIGNMENT identifier = value or identifier;
  • 119. C Syntax – BASIC C STRUCTURE #include<...> //Header File #include<...> //Header File void main(void) //Main Function { //Start of Function statement 1; //Function Body statement 2; //Function Body ... } //End of Function
  • 120. C Syntax – BREAK STATEMENT break; – CONTINUE STATEMENT continue; – CREATING CONSTANT Const datatype IDENTIFIER = value; //For int, float, & double Const datatype IDENTIFIER = ‘value’; //For char only #define IDENTIFIER value //For int, float, & double #define IDENTIFIER ‘value’ //For char only
  • 121. C Syntax – DECLARING A MULTIDIMENSIONAL ARRAY datatype array_name[row][column]; – DECLARING AN ARRAY datatype array_name[size]; – DO-WHILE LOOP do { Statements; } while(condition);
  • 122. C Syntax – FOR LOOP for(variable initialization; condition; variable increment) { Statements; } – FUNCTION CALLING function Name ([argname1, ...]); – FUNCTION DECLARATION return_datatype function Name( type [argname1], type [argname2], ...);
  • 123. C Syntax – FUNCTION DEFINITION return_datatype function Name( type [argname1], type [argname2], ...) { Statements; return(variable or argname); //If return datatype is not void } – GETTING THE ADDRESS STORED IN A POINTER datatype identifier1 = &identifier;
  • 124. C Syntax – IF STATEMENT if(conditional) { Statements; } – IF-ELSE-IF LADDER if(condition) { Statements; } else if(condition) { Statements; } … else { Statements; }
  • 125. C Syntax – INITIALIZING A MULTIDIMENSIONAL ARRAY array_name[row][column]={{values}, {values}, {values}, ...}; – INITIALIZING AN ARRAY array_name[size]={value1, value2, value3, ...}; – INPUT scanf(“control String”, &variable list);
  • 126. C Syntax – MAIN FUNCTION datatype main(argument) { statement 1; //Function Body statement 2; //Function Body ... }
  • 127. C Syntax – NESTED DO-WHILE LOOP do { do { Statements; } while(condition); Statements; } while(condition); – NESTED FOR LOOP for(variable initialization; condition; variable increment) { for(variable initialization; condition; variable increment) { Statements; } Statements; }
  • 128. C Syntax – NESTED IF STATEMENT if(condition) { if(condition) { Statements; } } – NESTED WHILE LOOP while(condition) { while(condition) { Statements; } Statements; }
  • 129. C Syntax – POINTER DECLARATION datatype *identifier; – POINTER INITIALIZATION datatype *identifier= value; //For int, float, double datatype *identifier= ‘value’; //For char only – PRINT printf(“Control Statement”, Variable list);
  • 130. C Syntax – SWITCH-CASE STATEMENTS switch(variable) { case constant 1: //constant can be number of ‘character’ Statements; break; case constant 2: //constant can be number of ‘character’ Statements; break; … … … … default: statements; }
  • 131. C Syntax – VARIABLE DECLARATION Datatype identifier; – VARIABLE INITIALIZATION Identifier = value; //For int, float, & double Identifier = ‘value’; //For char only – WHILE LOOP while(condition) { Statements; }