C Programming
C Programming
C Programming
C History
• C is a programming language. The C language was
first developed in 1972 by Dennis Ritchie at AT&T
Bell Labs.
• Many ideas came from type less languages BCPL and B
Introduction To C
• C is a high-level programming language.
– In the computer world, the further a programming language is from the
computer architecture, the higher the language's level. The high-level
programming languages, on the other hand, are closer to our human
languages.
• High-level programming languages, including C, have the following
advantages:
– Readability: Programs are easy to read.
– Maintainability: Programs are easy to maintain.
– Portability: Programs are easy to port across different computer platforms.
• C allows you to get control of computer hardware and peripherals.
That's why the C language is sometimes called the lowest high-level
programming language.
• Case – sensitive.
Introduction To C cont…
• C's syntax is terse and the language does not restrict what
is "allowed" -- the programmer can pretty much do
whatever they want.
• C's type system and error checks exist only at compile-
time. The compiled code runs in a stripped down run-time
model with no safety checks for bad type casts, bad array
indices, or bad pointers. There is no garbage collector to
manage memory. Instead the programmer manages heap
memory manually. All this makes C fast but fragile.
Why ‘C’ Language is required?
• Of higher level languages, C is the closest
to assembly languages
– bit manipulation instructions
– pointers (indirect addressing)
• Most microcontrollers have available C
compilers
• Writing in C simplifies code development
for large projects
C is a powerful and flexible language
• File name
• Comments - /* */, //, nested?
• #include
• main()
• printf(), “\n”
• return()
First C Program
1: #include <stdio.h>
2: main()
3: {
4: printf("Hello, World!\n");
5: return 0;
6: }
On TurboC IDE
• Press Alt+F9 to Preprocess, Compile and
Assemble
1. char :
a) Occupy 1 byte
b) Much be enclosed with in single
quotes(‘’)
c) Format specifier is %c
2. int :
a) Depending on the operating system and the C
compiler you're using, the length of an integer varies
b) Format Specifier is %d
c)No special char with in the integer constant
C Data Types (contd.)
3. float :
a) Occupies 4 bytes
b) Format specifier is %f
c) No special character
within the float constant
Expressions
Definition
• In C, an expression is anything that
evaluates to a numeric value. C expressions
come in all levels of complexity
Simple Expressions
• The simplest C expression consists of a single
item: a simple variable, literal constant, or
symbolic constant. Here are four expressions
Expression Description
PI A symbolic constant
(defined in the program)
20 A literal constant
rate A variable
-1.25 Another literal
constant
Evaluation of expressions
• A literal constant evaluates to its own
value. A symbolic constant evaluates to the
value it was given when you created it
using the #define directive. A variable
evaluates to the current value assigned to it
by the program.
Complex Expressions
Example:
i) x = a + 10;
ii) y = x = a + 10;
iii) x = 6 + (y = 4 + 5);
Operators
Data Manipulation with Operators
(contd.)
• Conditional Operator:
^ bitwise exclusive OR
| bitwise OR
&& logical AND
|| logical OR
?: conditional
= += /= %= += assignment, compound
-= <<= >>= &= assignment
^= |=
, comma
Anatomy of a C Function
• Function type:
– type of value a function is going to return after its execution
• Function name:
– Choose a name that reflects what the function can do.
• Arguments to the function:
– information passed to functions are known as arguments.
– An argument list contains two or more arguments that are
separated by commas.
• Opening & closing brace:
– braces are used to mark the beginning and end of a function /
statement block.
• Function body:
– contains variable declarations and C statements
C Keywords (ANSI’89)*
*
All keywords
default goto sizeof volatile in lower-case
do if static while
Variables
• A variable is a named data storage location in your
computer's memory. By using a variable's name in
your program, you are, in effect, referring to the
data stored there.
Rules To Create Variable Names
Heap
Global variables
Program code
Variables
A variable is a named location in memory that is used
to hold a value that can be modified by the program.
break;
• Break an infinite loop.
• to exit the switch construct after the statements within a
selected case are executed.
continue;
• Instead of breaking a loop, there are times when you
want to stay in a loop but skip over some statements
within the loop. To do this, you can use the continue
statement provided by C. The continue statement
causes execution to jump to the top of the loop
immediately.
goto
• The general form is:
statement1;
label: statement2;
...
goto label;
• label is a label name that tells the goto statement
where to jump. You have to place label in 2 places:
– One is at the place where the goto statement is going to jump
(note that a colon must follow the label name),
– and the other is the place following the goto keyword.
while (expression)
{
statement1;
...
}
eg.: int i;
i = rand();
or
int getchar(void);
int c;
c = getchar();
Functions in C(contd.)
• Functions with a Fixed Number of Arguments:
int function_1(int x, int y);
• To declare a function with a fixed number of arguments,
you need to specify the data type of each argument.
• It's recommended to indicate the argument names so that
the compiler can have a check to make sure that the
argument types and names declared in a function
declaration match the implementation in the function
definition.
Functions in C(contd.)
• Prototyping a Variable Number of Arguments:
• The ellipsis token ... (i.e., three dots) represents a variable
number of arguments
• Initializing Strings:
char arr_str[7] = {`H', `e', `l', `l',
`o', `!', '\0'};
• char str[7] = "Hello!";
• char str[] = "Hello!";
Manipulating Strings(contd.)
• String Constants Versus Character Constants:
– Differnce between: char ch = `x';
char str[] = "x";
• String as a char pointer:
char *ptr_str;
ptr_str = "A character string.";
• Multidimensional arrays
C supports multidimensional arrays.
type name[size1][size2]…[sizeN]
Manipulating Strings(contd.)
• String Constants Versus Character Constants:
– Difference between: char ch = `x';1B
char str[] = "x";
2B
An Introduction to
Pointers
• What Is a Pointer?
A pointer is a variable whose value is used to point to (point
to location of) another variable.
• Address operator ( &) The & is a unary operator that returns
memory address of its operand.
– %p, %u
• Dereference Operator ( * ) this unary operator returns the
value located at the address that follows.
• Declaring Unions
union union_tag
{
data_type1 variable1;
data_type2 variable2;
...
} union variable1, …, union variableN;
Unions(contd.)
• Defining Union Variables:
Union variables can be defined after declaring a union.
union | union uni_name
{ | {
int a; | int a;
char c[10]; | char c[10];
float f; | float f;
}name1, name2; | };
| union uni_name name1,name2;
• Referring a Union with . or ->
The dot operator (.) can be used in referencing union members.
The arrow operator (->)is used to reference the union member
year with the pointer ptr.
Unions(contd.)*
• Initializing a Union:
• The memory location of a union is shared by different members
of the union at different times. The size of a union is equal to
the size of the largest data item in the list of the union members,
which is large enough to hold any members of the union, one at
a time.
• Therefore, it does not make sense to initialize all members of a
union together because the value of the latest initialized member
overwrites the value of the preceding member.
• Initialize a member of a union only when you are ready to use it.
The value contained by a union is the value that is latest
assigned to a member of the union.
Unions(contd.)*
#include <stdio.h>
union u
{
char ch[2];
int num;
};
int UnionInitialize(union u val);
main(void)
{
union u val; int x;
x = UnionInitialize(val);
printf("The 2 character constants held by the
union:\n");
printf("%c\n", x & 0x00FF); printf("%c\n", x >> 8);
return 0;
}
int UnionInitialize(union u val)/*function definition*/
{val.ch[0] = `H'; val.ch[1] = `i'; return val.num;}
Unions(contd.)
There are 2 kinds of union applications:
struct tag_name
{
data_type name1: length1;
data_type name2: lenght2;
. . .
data_type nameN: lengthN;
} variable_list;
Q&A
• Q. What will happen if you initialize all
members of a union together?
• Q. Can you access the same memory
location with different union members?
Reading from and Writing to
Standard I/O
• There are 3 file streams that are pre-opened
• Stdin – The std i/p for reading – keyboard.
• Stdout – The std o/p for writing – monitor.
• Stderr – The std error for writing error messages.
• Getting the Input from the User
• getc()
• getchar()
• Printing the Output on the Screen
• putc()
• putchar()
Disk File Input and Output*
• The C language provides a set of rich library functions to perform input
and output (I/O) operation. Those functions can read or write any type of
data to files.
• What Is a File?
A file represents a concrete device(a disk file, a terminal, a
printer, or a tape drive) with which you want to exchange
information. Before you perform any communication to a file,
you have to open the file. Then you need to close the opened
file after you finish exchanging information with it.
• What Is a Stream?
The data flow you transfer from your program to a file, or
vice versa, is called a stream, which is a series of bytes. To
perform I/O operations, you can read from or write to any
type of files by simply associating a stream to the file.
The Basics of Disk File I/O*
• Pointers of FILE
A pointer of type FILE is called a file pointer, which references
a disk file. A file pointer is used by a stream to conduct the
operation of the I/O functions.
Eg., the following defines a file pointer called fptr:
FILE *fptr;
• Opening a File:
fopen() gives you the ability to open a file and associate a
stream to the opened file. You need to specify the way to open a
file and the filename with the fopen() function. The syntax
for the fopen() function is:
#include <stdio.h>
FILE *fopen(const char *filename, const char *mode);
• Opening a File(contd.):*
The fopen() function returns a pointer of type FILE. If an
error occurs during the procedure to open a file, the fopen()
function returns a null pointer.
• The following list shows the possible ways to open a file by various strings
of modes:
"r" opens an existing text file for reading.
"w" creates a text file for writing.
"a" opens an existing text file for appending.
"r+" opens an existing text file for reading or writing.
"w+" creates a text file for reading or writing.
"a+" opens or creates a text file for appending.
"rb" an existing binary file for reading.
"wb" creates a binary file for writing.
"ab" opens an existing binary file for appending.
"r+b" opens an existing binary file for reading or writing.
"w+b" creates a binary file for reading or writing.
"a+b" opens or creates a binary file for appending.
• Closing a File:
After a disk file is read, written, or appended with
some new data, you have to disassociate the file
from a specified stream by calling the fclose()
function.
The syntax for the fclose() function is
#include <stdio.h>
int fclose(FILE *stream);
If fclose() closes a file successfully, it returns
0. Otherwise, the function returns EOF.
#include <stdio.h>
main(void)
{
FILE *fptr;
char filename[]= “hydra.txt";
if ((fptr = fopen(filename, “a")) == NULL)
{
printf("Cannot open %s.\n", filename);
}
else
{
printf("The value of fptr: 0x%p\n", fptr);
printf("Ready to close the file.");
fclose(fptr);
}
return reval;
}
Reading and Writing Disk Files*
• Read or write one character at a time:
fgetc() and fputc(), can be used to read from or write to a disk
file one character at a time.
The syntax for the fgetc() function is:
#include <stdio.h>
int fgetc(FILE *stream);
The fgetc() function fetches the next character from the
stream specified by stream.
The syntax for the fputc() function is:
#include <stdio.h>
int fputc(int c, FILE *stream);
Here c is an int value that represents a character. The fputc()
function returns the character written if the function is successful;
otherwise, it returns EOF. After a character is written, the
fputc()function advances the associated file pointer.
Reading and Writing Disk Files*(contd.)
#include <stdio.h>
char *fgets(char *s, int n, FILE *stream);
#include <stdio.h>
int fputs(const char *s, FILE *stream);
• Here ptr references the array that contains the data to be written
to an opened file pointed to by the file pointer stream. size
indicates the size of each element in the array. The fwrite()
function returns the number of elements actually written.
• If there is no error occurring, the number returned by fwrite()
should be the same as the third argument in the function. The
return value may be less than the specified value if an error
occurs.
Reading and Writing Disk Files*(contd.)
#include <stdio.h>
long ftell(FILE *stream);
• The general form to use the #ifdef and #endif directives is:
#ifdef macro_name
statement1
Statement
. . .
statementN
#endif