C-Programming Part1 Upto Fucntions
C-Programming Part1 Upto Fucntions
DSSD - August’15
Outline
Day1
Day2
3. Control Statements
4. Functions
Day3
8. Introduction to pointers
9. Arrays & Pointers
10.Pointers with Functions
Day5
11.Strings
12.Structures, Unions & Bit-fields
Day6
13.File I/O
14.Preprocessor
Outline
Day 7
Day8
What is Unix?
What is Linux?
Linux Distributions
00:00:00 Hours, Jan 1, 1970 is time zero for UNIX. It is also called as
epoch.
Reference: http://en.wikipedia.org/wiki/History_of_Unix
UNIX
Reference: http://en.wikipedia.org/wiki/History_of_Unix
What is Linux?
A clone of UNIX, Developed in 1991 by Linus Torvalds, a
Finnish graduate student (It was his personal project)
Consist of
Linux Kernel
IBM PowerPC
Routers, GPS
Robo
Linux is everywhere
Check www.top500.org to know the power of Linux (June-2015 List)
Why Linux is everywhere?
Open, Free or Cheap
2. Ubuntu
3. Fedora
4. RHEL
5. CentOS
UNIX/Linux Structure
Linux File System
Details of File System
/ root directory
/boot files for booting system
/etc configuration files
/bin important system binaries
/sbin contains system admin programs(super user)
/usr user applications
/lib dynamic libraries
/home user home directories
/root super user home dir
/var contains variable data constantly generated when
system is running
/dev device files
Files, Directories and Inodes
File: A file represents a sequence of bytes.
Each file will have a name
A root user will also be present and he has all the administrave
privileges.
1. Read (r) - Indicates that a given category of user can read a file.
2. Write (w) - Indicates that a given category of user can write to a file.
3. Execute (x)- Indicates that a given category of user can execute the file.
Directory permissions:
3. Execute (x)- Operations can be perfomred on the files of the directories. This
bit is also called as search bit, it indicates whether you are permitted to
search files under that directory
The kernel sits on top of the hardware and is the core of the OS; it
receives tasks from the shell and performs them
The shell is the command line interface through which the user interacts
with the OS. Most commonly used shell is “bash”
Linux has a kernel and one or more shells – bash, csh, ksh etc.
When you login to the system the default shell will be given to the user.
Bash is the default shell for Linux (We can change the default shell)
GUI of Linux is in fact an application program works on the shell.
Shell commands
Shell Command - A command is a program which interacts with the
kernel to provide the environment and perform the functions called by the
user.
Command Structure:
chmod +x users.sh
Example:
#!/bin/bash
date
who
ps -ax
How to explore?
Man pages
Manpage
$ man ls
$ man 2 mkdir
$ man man
$ man -k mkdir
$manpath
/etc/man.config
How to explore…?
Man page sections
1. File management
2. System information
4. Network
5. Searching
8. Miscellaneous
Shell commands…
1. File management
ls - directory listing
cd - change to home
$ man man
Who am I?
$ whoami
Where am I?
$ cd
$ pwd
Shell commands…
1. File management …
What is here?
$ ls
$ ls -a
A file or a directory?
$ ls -F
$ ls -l
Shell commands…
1. File management …
$ cd path_of_dest_dir
$ cd ..
$ cd
$ cd /
Shell commands…
1. File management …
$ mkdir dir_name
$ mkdir –p dssd/c/day1/linux
$ cp file1 file2
$ cp –r dir1 dir2
Shell commands…
1. File management …
● 4 – read (r)
● 2 – write (w)
● 1 – execute (x)
Examples:
C standards
1989 - ANSI C (C89)
Reference: http://en.wikipedia.org/wiki/C_(programming_language)
Applications of “C”
Operating Systems
Applications developed using C
Language Compilers • Google Chrome, Firefox browsers
Assemblers • Unix/Linux
Text Editors • MySQL
Requirements:
OS: Linux
Syntax of C
Components of a C Program
i=2;
Expressions j=i+5;
return 0;
Whitespaces }
Compilation Phases
Compilation Phases
Compiling and running C programs
How to compile and run if my project has hundreds of
source files?
Make – Utility program
make: “make” is a utility that automatically builds executable programs
and libraries from source code
Reference: http://www.gnu.org/software/make/manual/make.html
Simple makefile
make finds the target prog1 and sees that it
Functions: int factorial (int n); /∗function takes int , returns int ∗/
Variables
A variable is a name for a location in memory
A variable must be declared by specifying the variable's name and the type of
information that it will hold
int total;
int count, temp, result;
int sum = 0;
int base = 32, max = 149;
total = 55;
y = f(x);
Q = sin(30);
int variable;
scanf(“%d”, &variable);
<keyboardinput> 30
A single bit can represent two possible states, like a light bulb
that is either on (1) or off (0)
1 bit ? 21 = 2 items
How many 2 bits ? 22 = 4 items
items can be 3 bits ? 23 = 8 items
represented by
4 bits ? 4
2 = 16 items
5 bits ? 25 = 32 items
Relationship Between a Byte and a Bit
What is the value of this binary
number?
00101100
0 0 1 0 1 1 0 0
11111111
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
+
1
-------------------------------
1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Analogy with car odometers
Analogy with car odometers
[http://www.hyperocity.com/volvo240/images/Volvo/odometerrepair/speedo999999.jpg]
Variables…
Total keywords - 32
Additional C99 key words (Total -5):
inline – For writing inline functions (Discuss in functions)
_imaginary – To declare imaginary values (iy)
_complex – To declare complex variables (a+ib)
_Bool – To declare a Boolean type variable (stdbool.h)
restrict – To declare restricted pointers
Quiz 2
Data Types:
Basic data types int, char, float, double
Enumerated data types enum
Void data type void
Derived data types Arrays, Pointers,
Structures and Unions
Sizes of Basic data types
Type Size Value Range
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 or 4 -32,768 to 32,767 (or)
-2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 0 to 65,535 (or)
0 to 4,294,967,295
Short 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295
Computer Memory
9278
Main memory is divided
9279 into many memory
9280 locations (or cells)
9281
9282
9283 Each memory cell has a
9284 numeric address, which
9285 uniquely identifies it
9286
Storing Information
9278
char (8 bits = 1 byte)
9279
9280
9281
9282
9283
9284
9285
9286
Storing a short
9278
9279 short (16 bits = 2 bytes)
9280
9281
9282
9283
9284
9285
9286
Storing an int
9278
9279
9280 int (32 bits = 4 bytes)
9281
9282
9283
9284
9285
9286
Storing a long
9278
9279
9280
9281
9282 long (64 bits = 8 bytes)
9283
9284
9285
9286
Storing a float
9278
9279
9280 float (32 bits = 4 bytes)
9281
9282
9283
9284
9285
9286
Storing a double
9278
9279
9280
9281
9282 double (64 bits = 8 bytes)
9283
9284
9285
9286
The sizeof() operator
#include <stdio.h>
#include <stdlib.h>
system("PAUSE");
return 0;
}
Void Data Type
o The type specifier void indicates that no value is available.
o It is an empty data type
o It can be used in the following situations
o Function returns as void
A function with no return value has the return type as void.
Example: void exit (int status);
o Function arguments as void
A function with no parameter can accept as a void.
Example: int rand(void);
o Pointers to void
A pointer of type “void *” represents the address of an object, but not its type. For
example a memory allocation function
Example: void *malloc( size_t size );
It returns a pointer to void which can be casted to any data type.
Symbolic constants for sizes of basic data types
Type Conversions
Type conversion: It is a way to convert a variable/constant from one
data type to another data type. There are two types:
a) Implicit type conversion
b) Explicit Type conversion
a) Implicit type conversion: Implicit type conversion, also known
as coercion, is an automatic type conversion by the compiler.
#include <stdio.h>
main()
{
int i = 10; Output: 107.0
char c = „a'; /* ascii value is 97 */
float sum;
sum = i + c;
#include <stdio.h>
main()
{
int sum = 14, count = 4; Output: 3.5
double mean;
Examples:
const int x=14;
volatile int a=10;
Constants
Values can‟t be modified once defined, Also called literals
Can be of any of other data type
Integer constants eg: 1234
Long constant eg: 123456L
Unsigned constant: eg: 241Ul, 241UL
Floating point eg: 123.4 or 1e-2
Character eg: „0‟ (equal to integer val 48)
Enumerated eg: enum boolean { NO, YES };
backslash causes an
"escape" from the normal
way characters are
interpreted by the
compiler
Quiz 3
1. What is the difference between the declaration and the definition of a
variable?
2. What are maximum and minimum values that can be stored in the char data
type? -128 to 127
3. Is there any Boolean data type in C? What data types can be used instead of
the Boolean type in C? char and int
4. What does keyword „void' denote? When is the keyword „void' generally used
in C code?
5. The format identifier „%i‟ is also used for _____ data type?
Quiz 3…
1. What is the output of the below program?
#include <stdio.h>
#define a 10
int main()
{
const int a = 5;
printf("a = %d\n", a);
}
Compilation error
Session 1
What is Memory?
Collection of Bits
For example,
Obtaining status
Note: The combination of bit level operators and the pointers can
replace the assembly code. For example, only 10% of UNIX is
written using assembly code and the rest is in C.
Bitwise Operations in Integers
There are six operators
Restrictions: We can use these operators only on int and char data
typed variables - Signed and unsigned char, short, int, long, long long
Bitwise Operations in Integers…
Examples - &, |, ^ and ~
unsigned short int a,b;
unsigned short int c;
a = 0xb786 1 0 1 1 0 1 1 1 1 0 0 0 0 1 1 0
b = 0xb420 1 0 1 1 0 1 0 0 0 0 1 0 0 0 0 0
c = a&b = 0xb400 1 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0
c = a|b = 0xb765 1 0 1 1 0 1 1 1 1 0 1 0 0 1 1 0
c = a^b = 0x0365 0 0 0 0 0 0 1 1 1 0 1 0 0 1 1 0
c = ~a = 0x4879 0 1 0 0 1 0 0 0 0 1 1 1 1 0 0 1
Example - Left Shift (<<)
Before shift 1 0 1 1 0 1 1 1 1 0 0 0 0 1 1 0
a= 0xb786
After shift 1 0 1 1 1 1 0 0 0 0 1 1 0 0 0 0
a= 0x9a30
Before shift 1 0 1 1 0 1 1 1 1 0 0 0 0 1 1 0
a= 0xb786
After shift 0 0 0 1 0 1 1 0 1 1 1 1 0 0 0 0
a= 0x16f0
#include <stdio.h>
int main()
{
int x = 1, y = 0, z = 5;
int a = x && y || z++;
printf("%d", a); return 0;
}
Answers: C (z++=5, 0 || 5 = 1)
Quiz 4…
2. What is the output of this code?
#include <stdio.h>
int main()
{
int x = 1, y = 0, z = 3;
x > y ? printf("%d", z) : return z;
}
Syntax Error
Correct Statement:
return(x > y ? printf("%d", z) : z)
Quiz 4…
3. What is the output of this code?
#include <stdio.h>
void main()
{
int x = 0, y = 2, z = 3;
int a = x & y | z;
printf("%d", a);
}
#include <stdio.h>
void main()
{ (a) Syntax Error
(b) -1 1
int i = -3;
(c) 1 -1
int k = 3 (d) 1 0
int j = i % 2; Answers: b
int m = k % -2;
printf("%d %d", j, m);
}
Quiz 4
5. What is the output of this code?
#include <stdio.h>
void main()
{ (a) 3
(b) 24
int x = 5 * 9 / 3 + 9;
(c) 60
} (d) None
Answers: b
Class Room Work
1. Write a program that asks the user to enter two numbers, obtain the two
numbers from the user and prints the sum, product, difference, quotient and
remainder of the two numbers.
2. Write a program to convert a positive integer (2 digits) to binary.
Day 2
3. Control Statements
4. Functions
Control Statements
• Definition: The control-flow of a language specify the order in which
computations are performed.
• Types:
• Decision Making (Branching)
o if else statement, if..else..if.. Statement (Multi-way decision making)
o Nested if statement
o Switch statement
• Loops
o For Loop
o While Loop
o Do while Loop
if..else
• Definition: The if-else statement is used to express decisions.
• The else part is optional.
Syntax:
If (expression)
set of statements;
else
set of statements;
Example :
If(a>b)
print( “ a is greater\n);
else
print(“ b is greater\n”);
if..else
Example : Write a C program to print the number entered by user
only if the number entered is negative.
#include <stdio.h>
int main()
{
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);
if(num<0)
{ /* checking whether number is less than 0 or not. */
printf("Number = %d\n",num);
}
else
printf("The if statement in C programming is easy.");
return 0;
}
If..else..if..
• Multi Way decision making: If any expression is true, the corresponding
statement is executes and chain terminates
• Last “else” part handles “none of the above”
Syntax: Example :
If (expression) If(a>b)
statement 1; print( “ a is greater\n);
else if (expression) else if (b>a)
statement 2; print(“ b is greater\n”);
else if (expression) else
statement 3; printf(“ a & b are equal”);
else
statement 4;
Nested if
• Nested if: You can use one if or else if statement inside
another if or else if statement(s).
Syntax: Example :
1. Write a program to find out the smallest and the largest of three integers
using
(a) Only if
(b) Only if else
(c) Nested if
Switch
• Definition: The switch statement is a multi-way decision that tests
whether an expression matches one of a number of constant integer
values, and branches accordingly.
Syntax:
Switch(expression)
{
case const-expr :
statements;
break;
case const-expr :
statements;
break;
……………
……………
default :
statements;
}
Switch - Rules
Rules:
# include <stdio.h>
int main()
{
char op;
float num1, num2;
switch(op)
{
case '+':
printf("%f + %f = %f",num1, num2, num1+num2);
break;
Switch – Example1…
Example1: /* Simple Calculator – Add, Sub, Mul, Div */
case '-':
printf("%f - %f = %f",num1, num2, num1-num2);
break;
case '*':
printf("%f * %f = %f",num1, num2, num1*num2);
break;
case '/':
printf("%f / %f = %f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message */
printf("Error! operator is not correct");
break;
}
return 0;
}
Switch…Example2
Example2: /* count digits, white case ' ':
space, others */ case '\n':
case '\t':
#include <stdio.h> nwhite++;
main() break;
{ default:
int c, i, nwhite, nother,ndigit[10]; nother++;
nwhite = nother = 0; break;
for (i = 0; i < 10; i++) }
ndigit[i] = 0; }
while ((c = getchar()) != EOF) printf("digits =");
{ for (i = 0; i < 10; i++)
switch (c) { printf(" %d", ndigit[i]);
case '0': case '1': case '2': case '3': printf(", white space = %d,
case '4': other = %d\n", nwhite,
case '5': case '6': case '7': case '8': nother);
case '9': return 0;
ndigit[c-'0']++; }
break;
If else .vs. Switch
• The functioning of if-else and switch is more or less same
If..else switch
If else .vs. Switch
• In another form:
If..else…if… switch
If else .vs. Switch
else if Ladder Switch
In else if ladder, the control goes In case of switch case, as per the
through the every else if statement value of the switch, the control jumps
until it finds true value of the statement to the corresponding case.
or it comes to the end of the else if
ladder.
Less compact, Not readable More compact than lot of nested else
if. More readable.
Less efficient (slow), if the size of the More efficient (Fast) – Jump Table or
ladder is big Branch Table
Syntax:
Syntax:
while (expression)
{
statement(s);
}
while loop - Example
Example: /* Print Floid Triangle */
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
printf("Enter the number of rows of Floyd's triangle to print\n");
scanf("%d", &n);
while (expr)
{
}
return 0;
}
do..While loop
• A do-while loop executes a block of statements at least once.
• The remaining behavior is same as while loop.
Syntax:
do
{
statement(s);
} while(expression)
do..while loop - Example
Example: /* Reverse a number */
#include <stdio.h>
main()
{
int val, r_digit;
printf("Enter the number to be reversed.\n");
scanf("%d", &val);
do {
r_digit = val % 10;
printf("%d", r_digit);
val = val / 10;
} while( val != 0 );
printf("\n");
}
break
• A break statement is used for early exit from a loop.
• It can be used to terminate a case in the switch statement
• If you are using nested loops then the break statement will stop the execution
of the innermost loop and start executing the next line of code after the block.
Syntax: break;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
continue
• A continue statement executes the next iteration of the loop, skipping the
remaining code in a block.
Syntax: continue;
int a = 1;
do
{
if( a == 3)
{
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 6 ); Output : 1 2 4 5
goto
• A goto statement causes an unconditional jump from the goto to a labeled
statement in the same function.
• Used to break the loops that are deeply nested, break works for only for a
single level of loop
• Deprecated – Not recommended to use
Syntax:
goto label;
…..
Label : statement;
goto - Example
Example:
#include <stdio.h>
int main ()
{
int a = 10;
LOOP: do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
Quiz 5
1. How can you make the loops to run infinite number of time ?
1. Write a program to print the multiplication table of a given number (upto 10)
using for loop.
2. Write a program to find the number of digits in a given integer number. Use
While loop or Do While loop.
Class Room Work
Solution: /* Multiplication Table */
#include <stdio.h>
int main()
{
int n, i;
printf("Enter an integer to find multiplication table: ");
scanf("%d",&n);
for(i=1;i<=10;++i)
{
printf("%d * %d = %d\n", n, i, n*i);
}
return 0;
}
Class Room Work
Solution: /* Number of digits */
#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
n/=10; /* n=n/10 */
++count;
}
printf("Number of digits: %d",count);
}
Day 2
3. Control Statements
4. Functions
Functions
• Definition: A function is a self-
contained program segment that Input
carries out some specific, well-
defined task.
• Every C program consists of one or
more functions. Function -
Computations
• Function should be declared or
prototyped before it is being used
anywhere
• One of these functions must be
Output
called “main” * (conditions apply)
• Function will carry out its intended
action whenever it is called.
Defining a Function
Syntax:
Syntax:
return_type function_name( parameter list );
• Function Call: To use a function, you will have to call that function to perform
the defined task.
• When a program calls a function, program control is transferred to the called
function.
• A called function performs defined task and when its return statement is
executed
Function prototypes…
Example:
double max( double param1, double param2)
{
if (param1 > param2)
{
Examples: return param1; }
else
{
float sqrt( float );
return param2;
}
int maximium( int , int ); }
Return type of a C Function
• Every C function must specify the type of data being generated by the
function.
• If the function does not generate any data, its return type can be “void”.
• The type of expression returned must match the type of the function, or
be capable of being converted, otherwise we can see undefined
behaviour.
Example:
void print_happy_birthday( int age )
{
printf("Congratulations on your %d th Birthday\n", age);
return;
}
Functions - Example
Example:
#include <stdio.h>
long int facrorial( int ); Function prototype
int main()
{ Actual Argument
int n; long int fact;
fact = factorial( n ); Function Call
printf(“Factorial of %d is %ld”, n, fact);
return 0;
} Formal Argument
long int factorial( int n ) /* calculate the factorial of n */
{
int i;
long int prod = 1;
if (n > 1)
for (i = 2; i <= n; ++i)
prod *= i;
return(prod);
}
Function Parameters
Parameters are the symbolic name for "data" that are passed to a function
Formal Arguments - Called function
Actual Arguments - Calling function
Two ways that arguments can be passed to a function:
Call by value
o Copy of data is sent to the function being called
o Doesn‟t affect the original data
Call by Reference
o Reference to the data is sent
o Reference parameter "refers" to the original data in the calling function.
o Changes affect the original data
Size of a function
Functions – Parameter Parsing
• In a function parameters are passed/parsed in Right to Left direction.
Functions - Advantages
Advantages:
• Modularity
• Readability
• Reusability
• Easy to develop, debug and test
• Allows test-driven development
• Allows unit testing
• Allows top-down modular approach
Recursion
• Definition: Recursion is a process by which a function calls itself
repeatedly, until some specified condition has been satisfied.
• To solve a problem recursively
o The problem must be written in a recursive form.
o The problem statement must include a stopping condition.
• A recursive function must have the following type of statements :
o A statement to test and determine whether the function is calling
itself again.
o A statement that calls the function itself and must be argument.
o A conditional statement (if-else).
o A return statement.
Recursion
Syntax:
A()
Void A()
void main() {
{ if (stopping condition)
return;
A(); else
return; A();
} return;
}
Recursion – Example1 - Factorial
factorial(5) = 5 * factorial(4)
4 * factorial(3)
n
3 * factorial(2)
2 * factorial(1)
n - 1
Recursion – Example1 - Factorial
Example: Recursive function to find factorial
int fibonacci(int i)
{
if(i == 0) return 0;
if(i == 1) return 1;
return (fibonacci(i-1) + fibonacci(i-2));
}
Recursion
Advantages:
• Simple to code (Not Always)
• Size of the code will be less
• Readable
• Disadvantages:
• Difficult to understand in some algorithms
• Stack Overflow in case of deep recursion
• Less portable
• Writing parallel recursive functions is error prone
Class room Exercise - 6
1. Write a program to implement multiplication using
addition. Use recursion.
2. Write a program to swap two numbers.
3. Write a recursive function to find the sum of n
integers.
Class room Exercise - 6
Trace of Function multiply(6,3)
Auto Register
Default storage class for local used to define local variables that should be
variables stored in a register instead of RAM.
Max size = size of register (=1 word)
can‟t have unary operator applied to it
int count;
Should be used for variables that need quick
auto int count; access e.g counters
Ex: register int count;
extern
static Provides reference of global variable that is
Exists during the lifetime of the visible to ALL the program files
program When you use 'extern', the variable cannot
Enables variables to maintain their be initialized as all it does is point the
values between the function calls variable name at a storage location that has
Can also be applied to global been previously defined
variable but the scope is restricted extern modifier is most commonly used
to file in which is declared when there are two or more files sharing the
static int count=2; same global variables or functions
Storage Classes
Defines the scope (visibility) and life-time of variables and/or functions
Example auto
#include <stdio.h>
void increment(int);
int main() void increment(int count)
{ {
auto count = 1; count++;
increment(); printf("count is %d\n", count);
increment(); }
increment();
}
#include <stdio.h>
void increment(int);
int main() void increment(int count)
{ {
register count = 1; count++;
increment(); printf("count is %d\n", count);
increment(); }
increment();
}
Example static
#include <stdio.h>
void increment(); void increment( )
int main() {
{ static int count=0;
increment(); count++;
increment(); printf("count is %d\n", count);
increment(); }
}
Example extern
#include<stdio.h>
int x = 10 ;
int main( )
{
extern int y ; //Declaration
printf ( "The value of x is %d\n", x ) ;
printf ( "The value of y is %d\n",y ) ;
return 0;
}
int y = 50 ; //Definition
Day 3
Escape sequences
Number representation in C
Escape Sequences
Definition: Character combinations consisting of a backslash (\)
followed by a letter or by a combination of digits.
Uses:
Escape
Description Representation
sequence
Number
Base Calculation Example
Representation
1x24+0x23+1x22+1x21 0010111
Binary 0,1 0010111
+1x20
Decimal 0,1,2,3,4,5,6,7,8,9 2x101+3x100 23 -
000 010
Octal 0,1,2,3,4,5,6,7 2x81+7x80 27
111
0,1,2,3,4,5,6,7,8,9,a,b,c,d, 0001 0111
Hexadeci e,f (or)
1x161+7x160 17
mal 0,1,2,3,4,5,6,7,8,9,A,B,C,
D,E,F
Number representation in C…
Integer constants are constant data elements that have no fractional
parts or exponents.
Always begin with a digit.
Can specify integer constants in decimal, octal, or hexadecimal form.
Can specify signed or unsigned types and long or short types.
To specify a decimal constant, begin the specification with a nonzero
digit.
Example:
int num = 120; //decimal constant
Number representation in C…
Byte
Description
character
fgetc()
reads a byte from a file stream
getc()
fgets() reads a byte line from a file stream
fputc()
writes a byte to a file stream
putc()
fputs() writes a byte string to a file stream
getchar() reads a byte from stdin
reads a byte string from stdin (deprecated in
gets()
C99, obsolete in C11)
putchar() writes a byte to stdout
puts() writes a byte string to stdout
ungetc() puts a byte back into a file stream
I/O functions…
File accessing & Direct I/O:
A: Format Specifier
About “printf” – Format Specification
Syntax:
% [flags] [width] [.precision] [{h | l | ll | I |
I32 | I64}]type
If width is prefixed with 0, zeros are added until the minimum width is
0
reached. If 0 and – appear, the 0 is ignored.
A blank. Prefix the output value with a blank if the output value is signed
' '
and positive; the blank is ignored if both the blank and + flags appear.
When used with the o, x, or X format, the # flag prefixes any nonzero
output value with 0, 0x, or 0X, respectively.
# When used with the e, E, f, a or A format, the # flag forces the output
value to contain a decimal point in all cases.
When used with the g or G format, the # flag forces the output value to
contain a decimal point in all cases and prevents the truncation of trailing
zeros. Ignored when used with c, d, i, u, or s.
Format Specification - Width
Width Specification:
Examples:
Output:
%4f: 12.432100
%8.5f: 1.23400
%.1f: 12.4
%.3f: 12.432
%.3f: 100.200
%.3g: 100
%.3f: 3.142
%.3g: 3.14
%.5s: abcde
Format Specification – Size
Size Specification:
Examples:
short int i = 3;
long int j = 3;
wchar_t* wide_str = L"This is a wide string";
long double d = 3.1415926535;
Output:
%hd: 3
%ld: 3
%ls: This is a wide string
%Lg: 3.14159
Format Specification – Type Character
Type character
More Examples:
%#x: 0x78
%x: c
%#X: 0X78
%X: C
%#o: 0170
%o: 14
%#2f: 120.567000
%g: 3.14159
%g: 9.3e+007
%G: 9.3E+007
%07d: 0000102
+102
%-7d,%-5d,: 11 ,22 ,
%#010x: 0x00000079
%#010X: 0X00000079
2 /* Using the integer conversion specifiers */
3 #include <stdio.h>
4
5 int main() 1. Print
6 {
7 printf( "%d\n", 455 );
8 printf( "%i\n", 455 ); /* i same as d in printf */
9 printf( "%d\n", +455 );
10 printf( "%d\n", -455 );
11 printf( "%hd\n", 32000 );
12 printf( "%ld\n", 2000000000 );
13 printf( "%o\n", 455 );
14 printf( "%u\n", 455 );
15 printf( "%u\n", -455 );
16 printf( "%x\n", 455 );
17 printf( "%X\n", 455 );
18
19 return 0;
20 }
A
This is a string
This is a string Program Output
This is also a string
Examples:
scanf("%f", &a);
scanf("%4f", &b);
scanf("%ls", &y);
scanf("%*d %[0123456789]", myname);
“scanf” – format specifier
The format argument specifies the interpretation of the input and can
contain one or more of the following:
1. White-space characters: blank, tab ('\t') or newline ('\n').
A white-space character causes scanf() to read, but not to store, all
consecutive white-space characters in the input up to the next non-white-
space character.
One white-space character in the format matches any number (including
0) and combination of white-space characters in the input.
2. Non-white-space characters:
Except percent sign (%).
A non-white-space character causes scanf() to read, but not to store,
a matching non-white-space character.
If the next character in the input stream does not match, scanf()
terminates.
“scanf” – format specifier…
3. Format specifications:
Introduced by the percent sign (%).
A format specification causes scanf() to read and convert characters in
the input into values of a specified type.
The value is assigned to an argument in the argument list.
“scanf” – format specifier…
The format is read from left to right.
Characters outside format specifications are expected to match the
sequence of characters in the input stream; the matching characters in
the input stream are scanned but not stored.
If a character in the input stream conflicts with the format specification,
scanf() terminates, and the character is left in the input stream as if it
had not been read.
When the first format specification is encountered, the value of the first
input field is converted according to this specification and stored in the
location that is specified by the first argument.
The second format specification causes the second input field to be
converted and stored in the second argument, and so on through the
end of the format string.
“scanf” – format specifier…
Examples:
scanf( "%ls", &x ); // read a wide-character string
wscanf( "%hC", &x ); // read a single-byte character
“scanf” – Example1
char *p;
int q;
errno = 0;
q = scanf("%a[a-z]", &p);
if (q == 1)
{
printf("read: %s\n", p);
free(p);
}
else if (errno != 0)
{
perror("scanf");
}
else
{
printf("No matching characters\n"):
}
Note: “a” is interpreted as a specifier for floating-point numbers
“scanf” – When it stops reading a field?
The scanf() function scans each input field, character by character. It
may stop reading a particular input field before it reaches a space
character for a variety of reasons:
1) The specified width has been reached.
2) The next character cannot be converted as specified.
3) The next character conflicts with a character in the control string
that it is supposed to match.
4) The next character fails to appear in a given character set.
For whatever reason, when the scanf() function stops reading an input
field, the next input field is considered to begin at the first unread
character.
“scanf” – Type field Characters
The following information applies to any of the scanf() family of functions.
The type character is the only required format field.
Appears after any optional format fields.
The type character determines whether the associated argument is
interpreted as a character, string, or number.
“scanf” – Type field Characters…
Character Type of input expected Type of argument
Character.
White-space characters that are
c ordinarily skipped are read when c is Pointer to char
specified. To read next non-white-space
single-byte character, use %1s;
Character.
White-space characters that are
C ordinarily skipped are read when C is Pointer to wchar_t
specified. To read next non-white-space
single-byte character, use %1s;
Run the following program and precede the %c‟s with spaces.
#include <stdio.h>
int main(void)
{ White space will terminate a string
char a, b;
int i, j;
printf("Enter two char-int pairs: ");
scanf(" %c %d", &a, &i);
scanf(" %c %d", &b, &j);
printf("%c:%d:\n", a, i);
printf("%c:%d:\n", b, j);
return 0;
}
1 /* Fig 9.20: fig09_20.c */
2 /* Reading characters and strings */
3 #include <stdio.h>
4
5 int main()
6 {
7 char x, y[ 9 ];
1. Initialize variables
8
9 printf( "Enter a string: " );
10 scanf( "%c%s", &x, y ); 2. Input
11
12 printf( "The input was:\n" );
13 printf( "the character \"%c\" ", x ); 3. Print
14 printf( "and the string \"%s\"\n", y );
15
16 return 0;
17 }
#include <stdio.h>
#include <ctype.h>
main( )
{
char letter[80];
int count, tag;
/* enter the text */
for (count = 0; (letter[count] = getchar()) I= '\no; ++count) ;
tag = count;
/* display the line in uppercase */
for (count = 0; count < tag; ++count) putchar(toupper(letter[count]));
}
String Input - gets()
Purpose: Reads characters from the standard input (stdin) and stores them
as a C string into str until a newline character or the end-of-file is reached.
Syntax: char * gets ( char * str );
Return value:
o On success, the function returns str.
o If the end-of-file is encountered while attempting to read a character,
the eof indicator is set (feof).
o If this happens before any char could be read, the pointer returned is
a null pointer (and the contents of str remain unchanged).
o If a read error occurs, the error indicator (ferror) is set and a null
pointer is also returned
Arguments: Pointer to a block of memory (array of char) where the
string read is copied as a C string.
String Input - gets()
A terminating null character is automatically appended after the
characters copied to str.
The newline character, if found, is not copied into str
It does not include the ending newline character in the resulting string
It does not allow to specify a maximum size for str (which can lead to
buffer overflows).
String Input - puts()
Purpose: Writes the C string pointed by str to the standard output (stdout)
and appends a newline character ('\n').
#include <stdio.h>
/* read and write a line of text */
int main( )
{
char line[80];
gets(1ine);
puts(1ine);
return 0;
]
Thank You