0% found this document useful (0 votes)
19 views

C Program

Uploaded by

ajaymithran1992
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

C Program

Uploaded by

ajaymithran1992
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 182

.

Introduction and First Program


&
Variables and Data types
Introduction
C is a general purpose high level language and it is developed by
“Dennis Ritche” in 1972.

C is a structured programming language

C supports functions that enables easy maintainability of code, by


breaking large file into smaller modules

Comments in C provides easy readability

C is a powerful language.
Why Name 'C' was given to this language

 Many of the ideas of C language were derived and taken from 'B‘
language.
 BCPL and CPL are previous versions of 'B' language.
 As many features came from B it was named as 'C'.
Why Name 'C' was given to this language

C programming
Language-Structured
and Disciplined C programs built from
approach to Variable and type
programming language declarations
Functions
Statements
Expressions
Structure Of “C” Programs

Before going and reading the structure of C programs we


need to have a basic knowledge of the following:
 C's Character Set
 C's Keywords
 The General Structure of a 'C' Program
 How To End A Statement
 Free Format Language
 Header Files & Library Functions
C's Character Set

C does not use every character set and key found on


modern computers . The only characters that C -Language
uses for its programs are as follows:
 A-Z all alphabets
 a-z all alphabets
 0-9
 # % & ! _ {} [] () $$$$ &&&& |
 space . , : ; ' $ "
+ - / * =
Example of “C” Program

/* HELLO.C -- Hello, world


*/
#include <stdio.h>
int main()
{
printf("Hello, world\n");
return 0;
}
Basic Structure Of “C” Programs
#include<stdio.h> Header Files

#include<conio.h>
void main()
{ Entry Point of program

-- other statements
}
Indicates starting of
program
Header files

 The files that are specified in the include section is called


as Header File.
 These are precompiled files that has some functions
defined in them.
 We can call those functions in our program by supplying
parameters.
 Header file is given an extension .h .
 C Source file is given an extension .c
Running a ‘C’ Program
1.Type a program.
2.Save it.
3.Compile the program – This will generate an .exe file
(executable)
4.Run the program (Actually the exe created out of
compilation will run and not the .c file)
5.In different compiler we have different option for
compiling and running.
Main function

This is the “Entry Point” of a program.


When a file is executed, the start point is the main function.
From main function the flow goes as per the programmers choice.
There may or may not be other functions written by user in a
program.
Main function is compulsory for any C program.
“C” language TOKENS

The smallest individual units in a C program are known as tokens. In


a C source program, the basic element recognized by the compiler
is the "token." A token is source-program text that the compiler does
not break down into component elements.
C has 6 different types of tokens viz.
Keywords [e.g. float, int, while]
Identifiers [e.g. main, amount]
Constants [e.g. -25.6, 100]
“C” language TOKENS

Strings [e.g. “SMIT”, “year”]


Special Symbols [e.g. {, }, [, ] ]
Operators [e.g. +, -, *]
C - programs are written using these tokens and the general syntax.
keywords

 "Keywords" are words that have special meaning to the


C compiler.
 Their meaning cannot be changed at any instance.
 Serve as basic building blocks for program statements.
 All keywords are written in only lowercase.
keywords
auto double register
else return switch
break
enum short type def
case
extern signed union
char unsigned
float sizeof
const void
for static
continue goto struct volatile

default if int while

do long
The Identifiers

Identifier is a name given to program elements such as variables,


functions, procedure, arrays and soon. First character must be an
Alphabet or Underscore. Identifier consists of sequence of letters,
digits or combination of both.
The Identifiers
 First character must be an Alphabet or Underscore( _ ).
 Special characters and embedded commas are not
allowed.
 First 31 characters are given high priority or preference.
 Keyword cannot be used as Identifier.
 There should not be any white space.
 Both uppercase and lowercase letters are permitted.
 The underscore character is also permitted in identifiers.
The Identifiers
C is a case sensitive language.
It matters whether an identifier, such as a variable name,
is uppercase or lowercase.
Example:
 area
 Area
 AREA
 ArEa
are all seen as different variables by the compiler.
Constants
Constants in C are the fixed values that do not change
during the execution of a program
Integer Constants
Refers to sequence of digits such as decimal integer, octal
integer and hexadecimal integer.
Some of the examples are 112, 0551, 56579u, 0X2 etc.

Real Constants
The floating point constants such as 0.0083, -0.78, +67.89
etc.
Constants
Constants and variables must be declared before they can be used.
 A constant declaration specifies the type, the name and the value
of the constant any attempt to alter the value of a variable defined
 as constant results in an error message by the compiler
 A variable declaration specifies the type, the name and possibly the
initial value of the variable.
 When you declare a constant or a variable, the compiler: Reserves
a memory location in which to store the value of the constant or
variable.
 Associates the name of the constant or variable with the memory
location.
Constants
Single Character Constants

 A single char const contains a single character enclosed


within pair of single quotes [ ‘ ’ ]. For example, ‘8’, ‘a’ ,
‘i’ etc.

String Constants
 A string constant is a sequence of characters enclosed in
double quotes [ “ ” ];
• For example, “0211”, “Stack Overflow” etc.
Variables
A Variable is a data name that is used to store any data
value.
Variables are used to store values that can be changed
during the program execution.
Variables in C have the same meaning as
variables in algebra. That is, they represent some unknown,
or variable, value.
x=a+b
z + 2 = 3(y - 5)
Remember that variables in algebra are represented by a
single alphabetic character
Variables
Variables in C may be given representations containing multiple
characters. But there are rules for these representations.
Variable names in C :
1. A variable name can have letters (both uppercase and lowercase
letters), digits and underscore only.
2. The first letter of a variable should be either a letter or an
underscore. However, it is discouraged to start variable name with
an underscore. It is because variable name that starts with an
underscore can conflict with system name and may cause error.
3. There is no rule on how long a variable can be. However, only the
first 31 characters of a variable are checked by the compiler. So,
the first 31 letters of two variables in a program should be different.
Declaring Variables
Before using a variable, you must give the compiler some information
about the variable; i.e., you must declare it.
The declaration statement includes the data type of the variable.
Examples of variable declarations:
int length ;
float area ;
Variables are not automatically initialized. For example, after
declaration
int sum;
the value of the variable sum can be anything (garbage).
Thus, it is good practice to initialize variables when they are declared.
Once a value has been placed in a variable it stays there until the
program alters it.
Datatypes
Data Type is used to define the type of value to be used in a Program.
Based on the type of value specified in the program specified amount
of required Bytes will be allocated to the variables used in the
program
Datatypes
There are three classes of data types here::
Primitive data types
– int, float, double, char
Aggregate OR derived data types
– Arrays come under this category
– Arrays can contain collection of int or float or char or double data
User defined data types
– Structures and enum fall under this category.
Datatypes
Type Size Representation Minimum range Maximum range
char, signed char 8 bits ASCII -128 127
unsigned char bool 8 bits ASCII 0 255
short, signed short 16 bits 2's complement -32768 32767

unsigned short 16 bits Binary 0 65535


int, signed int 16 bits 2's complement -32768 32767
unsigned int 16 bits Binary 0 65535
long, signed long 32 bits 2's complement -2,147,483,648 2,147,483,647
unsigned long 32 bits Binary 0 4,294,967,295
float 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38
double 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38
long double 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38
Declaring Variables with DataTypes
Data_type variable_list;
int age; Multiple Assignments:
float diameter; int a=10;
int b=20;
Char c;
int c=20;
Double salary;
int age=24; int a,b,c;
float diameter=2.56 A=b=c=20;
char c=’A’;
double salary=56.7990;
Declaring Variables
#include<stdio.h>
int main()
{
int id=101;
float years=24.5f;
double salary=30000.564;
char name[20]=”Gtec Education”;
printf(“id=%d”,id);
printf(“name=%s”,name);
printf(“salary=%0.2lf”,salary);
printf("\n%0.2f",years);
return 0; }
Input & Output
Input
– scanf(“%d”,&a);
– Gets an integer value from the user and stores it under the name
“a”
Output
– printf(“%d”,a)
– Prints the value present in variable a on the screen
TypeConversion
Type conversion in C is the process of converting one data type to
another. The type conversion is only performed to those data types
where conversion is possible.

Type conversion is performed by a compiler. In type conversion,


the destination data type can’t be smaller than the source data
type.

Type conversion is done at compile time and it is also called


widening conversion because the destination data type can’t be
smaller than the source data type.
TypeConversion

There are two types of Conversion:


Implicit Conversion (automatically)
Explicit Conversion (manually)
TypeConversion
#include<stdio.h>
int main(){
int a=10;
double b=a;
double d=25.53;
int c=(int)d;

printf(“id=%d”,a);
printf(“id=%lf”,b);
printf(“id=%d”,c);
printf("\n%lf",d);
return 0: }
OPERATORS
Operators
Operator is a Symbol that tells or instructs the Compiler to perform
certain Mathematical or Logical manipulations (Calculations).
Operators are used in a program to work on data and variables.
Operators in general form a part of Mathematical or Logical
expression.
Operators are generally classified into different types. They are
described one below another as follows.
C Logical Operators. An expression containing logical operator
returns either 0 or 1 depending upon whether expression results
true or false.
Logical operators are commonly used in decision making in C
programming.
Operators
1.Arithmetic Operators • Arithmetic (+,-,*,/,%)
• Relational (<,>,<=,>=,==,!=)
2.Relational Operators
• Logical (&&,||,!)
3.Logical Operators • Bitwise (&,|)
• Assignment (=)
4.Assignment Operators • Compound assignment(+=,*=,-=,/=,
%=,&=,|=)
5.Conditional Operators • Shift (right shift >>, left shift <<)
6.Unary operators
Arithmetic operators
Arithmetic operators are used
Operator Meaning Details
to perform Arithmetic
operations. They form a part + Addition Performs addition on integer numbers, floating point

of program. Programs can be numbers. The variable name which is used is the

written with or without operand and the symbol is operator.

operators. But calculations are


- Subtraction Subtracts one number from another.
performed only using
operators. * Multiplication Used to perform multiplication

/ Division It produces the Quotient value as output.

% Modulo It returns the remainder value as output.


Arithmetic operators
#include <stdio.h>
c = a/b;
int main() printf("a/b = %d \n",c);
{ c = a%b;
int a = 9,b = 4, c; printf("Remainder when a divided by b = %d \
n",c);
c = a+b;
printf("a+b = %d \n",c); return 0;
}
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
Assignment Operators
The Assignment Operator evaluates an expression on the right of the
expression and substitutes it to the value or variable on the left of the
expression. The general form is identifier = expression
Eg: x = a + b;
Subtract AND assignment operator. It subtracts the right operand from
the left operand and assigns the result to the left operand.
Multiply AND assignment operator. It multiplies the right operand with the
left operand and assigns the result to the left operand.
Eg: C *= A is equivalent to C = C * A
Here the value of a + b is evaluated and substituted to the variable x. ‘=’
equal to is used in Assignment operators. It is of two types. They are
Assignment Operators
(i)Simple assignment operator
In Simple assignment operator only one ‘=’ equal to operator
is used. It is used to assign a value to variable or expression.
The general form is
identifier = expression
Eg: y=35; x=ax+b-c;
(ii) Shorthand assignment operator
Shorthand assignment operator must be an arithmetic
operator or bitwise operator. The general form is
identifier <operator> = expression
The operator must be an arithmetic operator or bitwise
operator.
Assignment Operators

Example Example
Example Example
Operator Meaning Simp. Assign Shorthand

Operator Meaning Simp. AssignShorthand

+= Assign sum x=x+1 x+ =1

-= Assign difference y=y-1 y-=1


>>= Assign right shift

*= Assign product z=z*(x+y) z*=(x+y)

&= Assign bitwise AND y = y&x y&=x


/= Assign quotient y=y/(x+y) y/=(x+y)

%= Assign remainder x=x%z x%=z


|= Assign bitwise OR

~= Assignone’s complement

^= Assign bitwise X - OR z = z^y z^=y


<<= Assign left shift x = x << z x << = z
Assignment Operators
#include <stdio.h>
int main() printf("c = %d\n", c);
{ c /= a; // c is 5
printf("c = %d\n", c);
int a = 5, c; c %= a; // c = 0
c = a; // c is 5 printf("c = %d\n", c);

printf("c = %d\n", c); return 0;


c += a; // c is 10 }

printf("c = %d\n", c);


c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
Relational Operators
Relational Operators are used to compare two same
quantities.

There are six relational operators. They are mentioned one


below another as follows.

A relational operator is a programming language construct or


operator that tests or defines some kind of relation between
two entities. These include
Relational Operators
#include <stdio.h> printf("%d != %d is %d \n", a, b, a != b);
int main() printf("%d != %d is %d \n", a, c, a != c);
{ printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
int a = 5, b = 5, c = 10;
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d == %d is %d \n", a, b, a == b); printf("%d <= %d is %d \n", a, c, a <= c);
printf("%d == %d is %d \n", a, c, a == c); return 0;
printf("%d > %d is %d \n", a, b, a > b); }
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
Logical Operators
Logical Operators are used when we need to check more
than one condition. It is used to combine two or more
relational expressions.

Logical Operators are used in decision making. Logical


expression yields value 0 or 1 i.e.,( Zero or One) . 0 indicates
that the result of

logical expression is TRUE and 1 indicates that the result of


logical expression is FALSE.
Logical Operators
Logical AND (&& )

The result of the Logical AND operator will be TRUE If both value is
TRUE. If any one of the value is false then the result will be always
False. The result is similar to basic Binary multiplication.

Eg: a > b && x = = 10

The expression is true only if both expressions are true i.e., if a is


greater than b and x is equal to 10.
Declaring Variables
Logical OR ( || )

If any of the expression is true the result is true else false otherwise.
The result is similar to basic Binary addition.

The logical OR is used to combine 2 expressions or the condition


evaluates to true if any one of the 2 expressions is true.

Eg: a < m || a < n

It evaluates to true if a is less than either m or n and when a is less


than both m and n.
Declaring Variables
Logical NOT ( ! )

It acts upon single value. If the value is true result will be false and if
the condition is false the result will be true. The logical not operator
takes single

11

expression and evaluates to true if the expression is false and


evaluates to false if the expression is true.

Eg(!a)
Logical Operators
#include <stdio.h> result = (a != b) || (c < b);
int main() printf("(a != b) || (c < b) is %d \n",
result);
{
int a = 5, b = 5, c = 10, result; result = !(a != b);
printf("!(a != b) is %d \n", result);
result = (a == b) && (c > b);
result = !(a == b);
printf("(a == b) && (c > b) is %d \n", printf("!(a == b) is %d \n", result);
result);
result = (a == b) && (c < b); return 0;
}
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
Unary Operator-
#include <stdio.h>
Unary Operator-it performs single int main()
{
operator int a = 10, b = 100;
Ex:++,-- float c = 10.5, d = 100.5;

It has 4 types printf("++a = %d \n", ++a);


1)Postfix increment: a++ printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
2)Postfix decrement: a-- printf("--d = %f \n", --d);
3)Prefix increment: ++a
return 0;
4)Prefix decrement:--a }
Declaring Variables
onditional Operators

Conditional Operator Ternary operator is also known as “Ternary


operator”. The general form of Conditional Operator

is (exp1)?(exp2):(exp3);

where exp1 is the condition which is to be checked and exp2 is the


true value and exp3 is the false value. If the condition in exp1 is false
then statement in exp3 will be automatically executed.
Declaring Variables
Eg:
#include<stdio.h> void main()
{
int x,y,z;
printf(“Enter the value of a and b :”); scanf(“%d %d”,&x,&y);

z=((x>y)?x:y);

printf(“The biggest value is %d”,z);

}
DECISION MAKING
&
LOOPING
Declaring Variables
It is used to perform operation based on the condition given. There are 5
conditional control structures. They are:

1.If

2.If.else if

3.Nested if

4.switch.
Declaring Variables
If structure:

In this structure if the condition satisfies the statement under it will be


executed. Else the statements below it will be executed.

Syntax:
if(condition)
{
statement;
}
Declaring Variables
#include <stdio.h>
int main()
{
int age;
printf("Enter age : ");
scanf("%d", &age);
if (age >=60)
printf("You can have the pension");
return 0;
}
Declaring Variables
if..else structure:
In this structure if the condition satisfies the statement under it will be
executed. Else the statements under the else part will be executed.
Syntax:
if(condition)
{
statement;
}
else
{
statement;
}
Declaring Variables
#include <stdio.h>
int main()
{
int age;
printf("Enter age : ");
scanf("%d", &age);
if (age >= 18)
printf("You can Vote!");
else
printf("You cant Vote!");
return 0;
}
if..elseif structure:
if(condition)
In this structure if the condition {
satisfies the statement under if will be statement 1;
executed. Else the condition }
else if(condition)
becomes true in elseif part the {
statements under it will be executed. statement 2;
Else if both the condition becomes }
…..
false the default else part will be …..
executed. else if(condition)
{
statement n;
}
else
{
Stmt;
}
Declaring Variables
#include<stdio.h> if(score>=90 && score<=100)
int main() grade = 'A';
else if(score>=80)
{ grade = 'B';
int score; else if(score>=70)
grade = 'C';
char grade; else if(score>=60)
printf("Enter score(0-100): "); grade = 'D';
else if(score>=50)
scanf("%d",&score); grade = 'E';
if(score<0 || score>100) { else
grade = 'F';
printf("Invalid Score"); printf("Grade: %c\n", grade);
return 0;
return 0; }
}
Switch:
Alternative extension of if else switch (expression)
statement which allows a variable to {
case 1: statement 1;
be tested for equality against list of break;
values. Each value is called a “case” case 2: statement 2;
and the variable is being switched is break;
….
checked for switch case. ….
case n: statement n;
break;
default: statement;
break;
}
Declaring Variables
#include <stdio.h> switch (choice){
void main() case 1:
{ printf("%d + %d = %d\n", a, b, a + b);
int choice; break;
case 2:
printf("Select an option from the list
printf("%d - %d = %d\n", a, b, a - b);
below:\n");
break;
printf("1. Addition\n"); case 3:
printf("2. Subtraction\n"); printf("%d * %d = %d\n", a, b, a * b);
printf("3. Multiplication\n"); break;
printf("4. Division\n"); case 4:
printf("5. Modulus\n"); printf("%d / %d = %d\n", a, b, a / b);
break;
printf("6. Exit\n");
case 5:
printf("Enter your choice: "); printf("%d %% %d = %d\n", a, b, a % b);
scanf("%d", &choice); break;
int a, b; case 6:
// read two numbers printf("Exiting...\n");
printf("Enter two numbers: "); break;
default:
scanf("%d %d", &a, &b); printf("Invalid choice\n");
}}
Nested if:
If an if structure comes inside another if structure, then it is called as nested
if.
Syntax:
if(condition)
{

if(condition)
{
statement;
}
statement;
}
Nested if:
#include<stdio.h>
void main()
{
int x=45;
if(x<90){
if(x>30){
printf(“The student is brilliant\n”);
}
printf(“The student is not brilliant\n”);
}
Printf(“The value of x=%d\n”,x);
}
Nested if:
Loops are used to perform a specific task many times till the condition gets
satisfied. Using loop structure we can make a statement ‘n’ no of times, till
our condition gets satisfied.

Types of Looping Structures:

There are 3 looping structures. They are:

1.While

2.Do while

3.For
Nested if:
while:
While is the entry control statement. If the test condition is true the body of
the loop will be executed.
Syntax:
while(test condition)
{
body of the loop;
}
Nested if:
#include<stdio.h>
int main(){
int i=1,n;
printf("\nEnter The Limit : ");
scanf("%d",&n);
while(i<=n)
{
printf("\n%d",i);
i++;
}
return 0;
}
Nested if:
do-while:
do-while is the exit control statement. Body of the loop will be executed at
least once.
Syntax:
do
{
body of the loop;
}
while(test condition);
Nested if:
#include<stdio.h>
int main(){
int i=0,n;
printf("\nEnter The Limit : ");
scanf("%d",&n);
do
{
printf("\n%d",i);
i+=2; //i=i+2
}while(i<=n);
return 0;
}
Nested if:
For loop:
Execute a statement or group of statement repeatedly for a noun number of
times.
Syntax:
for (i=initial condition;testcondition;inc/dec)
{
body of the loop;
}
Nested if:
Eg prog:

#include<stdio.h>
int main(){
int i,n;
printf("\nEnter The Limit : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\n%d",i);
}
return 0;}
Nested if:
Nested for loop:
In this loop structure more than one form can be nested. In this one loop
stands for row and another stands for column.
Syntax:
for(initialization; condition; inc/dec){
for(initialization; condition; inc/dec){
statement 1;
statement 2;
statement n;
}
}
Nested if:
void main()
{
int i,j; int n;
printf("Enter the value of N:\n");
scanf("%d",&n);
printf("\n");
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
printf("%d\t",j);
}
printf("\n");
}}
Nested if:
#include <stdio.h>
int main() {
int i = 0;
int i;
while (i < 10) {
for (i = 0; i < 10; i++) { if (i == 4) {
if (i == 4) { break;
}
break; printf("%d\n", i);
} i++;
}
printf("%d\n", i);
}

return 0;
}
Nested if:
#include <stdio.h>
int main() {
int i = 0;
int i;
while (i < 10) {
for (i = 0; i < 10; i++) { if (i == 4) {
if (i == 4) { continue;
}
continue; printf("%d\n", i);
} i++;
}
printf("%d\n", i);
}

return 0;
}
STRING
Declaring Variables
Strings are actually one-dimensional array of characters terminated by a null
character '\0'. Thus a null-terminated string contains the characters that
comprise the string followed by a null.
The following declaration and initialization create a string consisting of the
word "Hello". To hold the null character at the end of the array, the size of
the character array containing the string is one more than the number of
characters in the word "Hello.“
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above
statement as follows −
char greeting[] = "Hello";
.
Declaring Variables
strlen(str) – To find length of string str
strrev(str) – Reverses the string str as rts
strcat(str1,str2) – Appends str2 to str1 and returns str1
strcpy(st1,st2) – copies the content of st2 to st1
strcmp(s1,s2) – Compares the two string s1 and s2
strcmpi(s1,s2) – Case insensitive comparison of strings
.
Declaring Variables
// C program to illustrate strings

#include<stdio.h>
#include<string.h>
int main()
{
// declare and initialize string
char str[] = “gtec";
// print string
printf("%s",str);
return 0;
}
.
Declaring Variables
/#include<stdio.h>
#include<string.h>
int main(){
char c[20],a[20];
char x[10]={'G','T','E','C','\0'};
char y[10]={'E','D','U','A','T','\0'};
printf("x : %s",x);
printf("\nEnter The String : ");
gets(c);
printf("c : %s",c);
return 0;
}
Declaring Variables
/#include<stdio.h>
#include<string.h>
int main(){
printf("\nCompare : %d ",strcmp(x,c));//String Compare
printf("\nLength : %d ",strlen(c));//String Length
printf("\nReverse : %s ",strrev(c));//String Reverse
printf("\nUppercase : %s ",strupr(c));//String Upper
printf("\nLowercase : %s ",strlwr(c));//String Lower
printf("\nCopy : %s ",strcpy(a,c));//String Copy
strcat(x,y);
printf("\nConcatenation : %s ",x);//String Concatenation
return 0;}
Declaring Variables
• pow(n,x) – evaluates n^x
• ceil(1.3) – Returns 2
• floor(1.3) – Returns 1
• abs(num) – Returns absolute value
• log(x) - Logarithmic value
• sin(x)
• cos(x)
• tan(x)
.
Declaring Variables
Functions:
A Function is a group of statement that together perform a task.
Every C program has atleast one function which is called main() function.

General form of the function:


returntype functionname(parameter list)
{
Body of the function;
}
Declaring Variables
A large C program is divided into basic building blocks called C function. C
function contains set of instructions enclosed by “{ }” which performs specific
operation in a C program. Actually, Collection of these functions creates a C
program.

There are two types of functions in C programming:


• Library Functions: are the functions which are declared in the C header files
such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
• User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces complexity of a
big program and optimizes the code.
Declaring Variables
There are 3 aspects in each C C functions aspect
syntax
s
function. They are,
Return_type
• Function declaration or prototype – function_name
function definition
This informs compiler about the (arguments list)
{ Body of function; }
function name, function parameters
function_name
and return value’s data type. function call
(arguments list);
• Function call – This calls the actual return_type
function function declaration function_name
(argument list);
• Function definition – This contains
all the statements to be executed.
Declaring Variables
• Syntax of function
Declaration section
<<Returntype>> funname(parameter list);
Definition section
<<Returntype>> funname(parameter list)
{
body of the function
}
Function Call
Funname(parameter);
Declaring Variables
Return type:
A function may return a value. Return type is the data type of the value that
function returns.
Some functions can perform to decide operations without return a value.
Return type is void.
Declaring Variables
• Procedure is a function whose return type is void

• Functions will have return types int, char, double, float or even structs and
arrays

• Return type is the data type of the value that is returned to the calling point
after the called function execution completes
Declaring Variables
#include<stdio.h>
void fun(int a); //declaration
int main()
{
fun(10); //Call
}
void fun(int x) //definition
{
printf(“%d”,x);
}
Declaring Variables
Actual parameters are those that are used during a function call

Formal parameters are those that are used in function definition and function
declaration
Declaring Variables
Types of function calling

function without arguments and without return value


function without arguments and with return value
function with arguments and without return value
function with arguments and with return value
/No Return Without Argument Function in C/*
#include<stdio.h>
void add();
int main(){
add(); //Function Calling
return 0;}
//Function Definition
void add(){
int a,b,c;
printf("\nEnter The Value of A & B :");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nTotal : %d",c);}
//No Return With Argument Function in C*
#include<stdio.h>
void add(int,int);
int main(){
int a,b;
printf("\nEnter The Value of A & B : ")
scanf("%d%d",&a,&b);
add(a,b); // Actual Parameters
return 0;}
void add(int x,int y) //Formal Parameters{
int c;
c=x+y;
printf("\nTotal : %d",c);}
//Return Without Argument Function in C
#include<stdio.h>
int add();x
int main(){
int a;
a=add();
printf("\nTotal : %d",a);
return 0;}
int add(){
int a,b;
printf("\nEnter The Value of A & B : ");
scanf("%d%d",&a,&b);
return a+b;}
//Return With Argument Function in C
#include<stdio.h>
int add(int,int);
int main(){
int a,b;
printf("\nEnter The Value of A & B : ");
scanf("%d%d",&a,&b);
a=add(a,b);
printf("\nTotal : %d",a);
return 0;}
int add(int x,int y){
return x+y;
}
Declaring Variables
#include<stdio.h>/*
int factorial(int i) //5{
if(i<=1){
return 1;
}
return i*factorial(i-1); //5*4*3*2*1}
int main(){
printf("Factorial : %d",factorial(5));
return 0;}
Declaring Variables
Array:
An array is a collection of similar data type value in a single variable.
Advantages of Array:
Code Optimization: Less code is required, one variable can store numbers of
value.
Easy to traverse data: By using array easily retrieve the data of array.
Easy to sort data: Easily sort the data using swapping technique
Random Access: With the help of array index you can randomly access any
elements from array.
Declaring Variables
An array is a collection of data that holds fixed number of values of same type.
For example: if you want to store marks of 100 students, you can create an
array for it.

float marks[100];

The size and type of arrays cannot be changed after its declaration.
Arrays are of two types:
– One-dimensional arrays
– Multidimensional arrays (will be discussed in next chapter)
Declaring Variables
Syntax:

datatype variable_name[size of the array]; i) Declaration of C Array

We can declare an array in the c language in the following way. data_type


array_name[array_size];

Now, let us see the example to declare the array. int marks[5];
Declaring Variables
Few key notes:
• Arrays have 0 as the first index not 1. In this example, mark[0]
• If the size of an array is n, to access the last element, (n-1) index is used. In
this example, mark[4]
• Suppose the starting address of mark[0] is 2120d. Then, the next address,
a[1], will be 2124d, address of a[2] will be 2128d and so on. It's because the
size of a float is 4 bytes.
Declaring Variables
Initialization of C Arraay
The simplest way to initialize an array
is by using the index of eaach
element. We can initialize each
eleement of the array by using the
index. Consider the following
example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Declaring Variables
Single Dimensional Array:

In this, it consists of a single row or single column. The elements are


stored in consecutive memory locatioon in all type of arrays.
Rules for Declaring One Dimensional Array
1.An array variable must be declared before being used in a prograam.
2.The declaration musst have a data type(int, float, char, double, etc.),
variable name, and subscript.
3.The subscript represents the size of the array. If the size is decclared as
10, programmers can sttore 10 elements.
4.An array index always starts from 0. For example, if an array variable is
declared as s[10], thhen it ranges from 0 to 9.
5.Each array element is stored in a separate memory location.
Declaring Variables
How to declare an array in C?
data_type array_name[array_size];
For example,
#include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
Declaring Variables
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Declaring Variables
Multi-dimension arrays consists of multiple
no of rows and columns. Using nested for
loop we can assign or store values in
consecutive memory location. However, if
you want to store data as a tabular form, like
a table with rows and columns, you need too
get familiar with multidimensional arrays. A
multidimensional array is basically an array
of arrays.
For example, float x[3]][4];
Here, x is a two-dimensional (2d) array. The
array can hold 12 elements. You can think
the array as a table with 3 rows and each
row has 4 columns.
Declaring Variables
Initializing a multidimensional array
Here is how you can initialiize two-dimensional and three-dimensional
arrays:
Initialization of a 2d arrray
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
Declaring Variables
Initialization of a 3d arrray
You can initialize a three-dimensional array in a similar wayy to a two-
dimensional array. Here's an example,
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}}, {{13, 4, 56, 3}, {5, 9, 3, 5}, {3,
1, 4, 9}}};
Syntax:
datatype variable_namme[no of row][no of column] int rollno[4][4];
whhere,
rollno - variable
4 - size of row array
4 - size of column arraay
Declaring Variables
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{ 2,3,4},{1,2,3},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Declaring Variables
#include<stdio.h>
void main(){
int i,j,m,n;
int a[5][5];
printf("Enter the no of rows:\n"); scanf("%d",&m);
printf("Enter the no of columns:\n"); scanf("%d",&n);
printf("Enter the Matrix A:");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%d",&a[i][j]);
}
}
Declaring Variables
printf("A Matrix:\n"); for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
Declaring Variables
• Arrays allow to define type of variables that can hold several data items of
the same kind.
• Similarly structure is another user defined data type available in C that
allows to combine data items of different kinds and stored in different memory
location.
• Structures are used to represent a record.
• Title
• Author
• Subject
• Book ID
Declaring Variables
• Structures are user defined data types
• It is a collection of heterogeneous data
• It can have integer, float, double or character data in it
• We can also have array of structures
struct <<structname>>
{
members;
} element;
We can access element.members;
Declaring Variables
Defining a Structure
To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member.
The format of the struct statement is as follows −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
Declaring Variables
struct Person
{ Ex:
int id; struct student
{
char name[5]; int id;
}P1; char name[20];
float percentage;
P1.id = 1; };
P1.name = “vasu”;
Declaring Variables
#include<stdio.h>
struct student{ printf("\nName : %s",o.name);
char *name; printf("\nAge : %d",o.age);
printf("\nPercent : %f",o.per);
int age; return 0;
float per; }

};
int main(){
struct student o,o2;
o.name="GTEC COMPUTER EDUCATION";
o.age=24.;
o.per=85.5;
Declaring Variables
/Local and Global Scope Structure in C s.m1=50; s.m2=50; s.m3=50;
Programming printf("\nMark-1: %d",s.m1);
#include<stdio.h> printf("\nMark-2 : %d",s.m2);
struct student{ printf("\nMark-3 : %d",s.m3);}
int main(){
char *name;
struct student o;
int age; o.name="Naveen";
float per;}; o.age=30;
void total(){ o.per=85.5;
struct mark printf("\nName :
{ %s",o.name);
printf("\nAge : %d",o.age);
int m1,m2,m3;
printf("\nPercent : %f",o.per);
}s; total();
return 0;}
Declaring Variables
/Access members of structure using pointer.
#include<stdio.h>
struct student{
char *name;
int age;
float per;};
int main(){
struct student o={"RAM",25,75.5};
struct student *ptr=&o;
printf("\nName : %s",(*ptr).name);
printf("\nAge : %d",ptr->age);
printf("\nPercent : %f",ptr->per);
return 0;}
Declaring Variables
struct detail{ scanf("%d",&det.age);
int age; printf("Enter the address:\n");
char name[50]; scanf("%s",det.address);
printf("Enter the pincode:\n");
char address[250];
scanf("%ld",&det.pincode);
long int contno; printf("Enter the contact number:\n");
long double pincode; }; scanf("%ld",&det.contno);
void main() printf("\nthe name: %s",det.name);
{ printf("\nthe age: %d",det.age);
struct detail det; printf("\nthe address:%s",det.address);
printf("\nthe pincode: %ld",det.pincode);
printf("Enter the name:\n");
printf("\nthe contact number: %ld",det.contno);
scanf("%s",det.name); }
printf("Enter the age:\n");
Declaring Variables
/#include <stdio.h>
#include <string.h>
struct student
{
int id; strcpy(record.name, "Raju");
record.percentage = 86.5;
char name[20]; printf(" Id is: %d \n",
float percentage; record.id);
printf(" Name is: %s \n",
}; record.name);
printf(" Percentage is: %f \n",
int main() record.percentage);
{ getch( );
return 0;
struct student record ; }
record.id=1;
Declaring Variables
/Structure as function arguments in C Programming
#include<stdio.h>
struct student{
char *name;
int age;
float per;};void display(struct student o){
printf("\nName : %s",o.name);
printf("\nAge : %d",o.age);
printf("\nPercent : %f",o.per);}int main(){
struct student o={"RAM",25,75.5};
display(o);
return 0;}
//Array of Structure Objects
#include<stdio.h>
struct student{ printf("\n------------------------------");
printf("\nName : %s",o[0].name);
char *name; printf("\nAge : %d",o[0].age);
int age; printf("\nPercent : %f",o[0].per);
printf("\n------------------------------");
float per;};int main(){ printf("\nName : %s",o[1].name);
struct student o[2]; printf("\nAge : %d",o[1].age);
printf("\nPercent : %f",o[1].per);
o[0].name="Ram Kumar"; printf("\n------------------------------\n\n");
o[0].age=25;
return 0;}
o[0].per=65.25;
o[1].name="Sam Kumar";
o[1].age=12;
o[1].per=80;
Declaring Variables
A union is a special data type available in C that allows to store 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.
Declaring Variables
DEFINING A UNION
To define a union, you must use the union statement in the same way as you
did while defining a structure.
The union statement defines a new data type with more than one member for
your program. The format of the union statement is as follows −
Syntax:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Declaring Variables
#include<stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Declaring Variables
struct demo{
int a;//4
char b;};
union udemo{
int a;//4
char b;}o;
int main(){
o.a=65;
printf("\nUnion A : %d",o.a);
printf("\nUnion B : %c",o.b);
return 0;}
Declaring Variables
The typedef operator is used for creating alias of a data type
For example I have this statement
typedef int integer;
Now I can use integer in place of int
i.e instead of declaring int a;, I can use
integer a;
This is applied for structures too.
Declaring Variables
#include <stdio.h>
#include <string.h>
strcpy(record.name, "Raju");
typedef struct student record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
{ printf(" Name is: %s \n", record.name);
int id; printf(" Percentage is: %f \n",
record.percentage);
char name[20]; return 0;
float percentage; }

} status;
int main()
{
status record;
record.id=1;
Declaring Variables
Pointer is a special variable that stores address of another variable
Addresses are integers. Hence pointer stores integer data
Size of pointer = size of int
Pointer that stores address of integer variable is called as integer pointer and is
declared as int *ip;
Declaring Variables
• Pointers that store address of a double, char and float are called as double
pointer, character pointer and float pointer respectively.
• char *cp
• float *fp
• double *dp;
• Assigning value to a pointer
int *ip = &a; //a is an int already declared
Declaring Variables
int a;
a=10; //a stores 10
int *ip;
ip = &a; //ip stores address of a (say 1000)

ip : fetches 1000
*ip : fetches 10
* Is called as dereferencing operator
Declaring Variables
• Calling a function with parameters passed as values

int a=10; void fun(int a)


fun(a); {
defn;
}
Here fun(a) is a call by value.
Any modification done with in the function is local to it and will not be effected
outside the function
Declaring Variables
• Calling a function by passing pointers as parameters (address of variables is
passed instead of variables)

int a=1; void fun(int *x)


fun(&a); {
defn;
}
Any modification done to variable a will effect outside the function also
Declaring Variables
#include<stdio.h>
void main()
{int a=10;
printf(“%d”,a); a=10
fun(a);
printf(“%d”,a); a=10
}
void fun(int x)
{
printf(“%d”,x) x=10
x++;
printf(“%d”,x);} x=11
Declaring Variables
Declaring Variables
#include<stdio.h>
void main()
{ int a=10;
printf(“%d”,a); a=10
fun(a);
printf(“%d”,a); a=11
}
void fun(int x)
{
printf(“%d”,x) x=10
x++;
printf(“%d”,x); } x=11
Declaring Variables
• Call by value => copying value of variable in another variable. So any change
made in the copy will not affect the original location.
• Call by reference => Creating link for the parameter to the original location.
Since the address is same, changes to the parameter will refer to original
location and the value will be over written.
Declaring Variables

a and x are referring to same location. So value will be over written.


Declaring Variables
Declaring Variables
Declaring Variables
#include <stdio.h>
void salaryhike(int *var, int b){
*var = *var+b;}
int main()
{int salary=0, bonus=0;
printf("Enter the employee current salary:");
scanf("%d", &salary);
printf("Enter bonus:");
scanf("%d", &bonus);
salaryhike(&salary, bonus);
printf("Final salary: %d", salary);
return 0;}
Declaring Variables
#include<stdio.h>
int main(){
int a=10,*p;
int **q; // Pointer to Pointer or Double Pointer
int ***r; //Triple Pointer
p=&a; //Address of a
printf("\n Value of A : %d",a);
printf("\n Address of A : %d",&a);
printf("\n Value of P : %d",p);
printf("\n Address of P : %d",&p);
printf("\n P Dereferencing : %d",*p);
printf("\n------------------------------------");
Declaring Variables
q=&p; r=&q;
printf("\n Value of P : %d",p);
printf("\n Address of P : %d",&p);
printf("\n Value of q : %d",q);
printf("\n Address of q : %d",&q);
printf("\n **Q Dereferencing : %d",**q);
printf("\n------------------------------------");
printf("\n Value of q : %d",q);
printf("\n Address of q : %d",&q);
printf("\n Value of r : %d",r);
printf("\n Address of r : %d",&r);
printf("\n ***r Dereferencing : %d",***r);
Declaring Variables
#include<stdio.h>
int main(){
int a=10;
int *p,*r;
p=&a;
r=p+1;
printf("\nP Value : %d",p);
printf("\nR Value : %d",r);
return 0;
}
Declaring Variables
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text
substitution tool and it instructs the compiler to do required pre-processing
before the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin
in the first column. The following section lists down all the important
preprocessor directives −
Declaring Variables
Sr.No. Directive & Description
Sr.No. Directive & Description
1 #define 7 #else
Substitutes a preprocessor macro. The alternative for #if.
8 #elif
2 #include #else and #if in one statement.
Inserts a particular header from
another file. 9 #endif
Ends preprocessor conditional.
10 #error
3 #undef
Prints error message on stderr.
Undefines a preprocessor macro.
11 #pragma
Issues special commands to the compiler, using a
4 #ifdef standardized method.
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not
defined.

6 #if
Tests if a compile time condition is
true.
Declaring Variables
Program for #define Program for #define
Ex: Ex:
#include <stdio.h>
#include<stdio.h> #define MIN(a,b) ((a)<(b)?(a):(b))
#define PI 3.14 void main()
{
void main() clrscr( );
{ printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
printf("%f",PI);
}
Declaring Variables
Program for #undef variable. But before being undefined, it was used by square
Ex: variable.
Ex:
#include <stdio.h> #include <stdio.h>
#include<conio.h> #include<conio.h>
#define number 15
#define PI 3.14 int square=number*number;
#undef PI #undef number
void main()
void main() {
{ clrscr( );
printf("%d",square);
clrscr( ); getch( );
}
printf("%f",PI);
getch( );
}
Program for #ifdef using NOINPUT
#include <stdio.h> #include <stdio.h>
#define NOINPUT void main()
{
void main() int a=0;
{ clrscr( );
#ifdef NOINPUT
int a=0; a=2;
#ifdef NOINPUT #else
printf("Enter a:");
a=2; scanf("%d", &a);
#else #endif
printf("Value of a: %d\n", a);
printf("Enter a:"); }
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
}
Declaring Variables
• A file is a collection of related data that a computers treats as a single unit.
• Computers store files to secondary storage so that the contents of files
remain intact when a computer shuts down.
• When a computer reads a file, it copies the file from the storage device to
memory; when it writes to a file, it transfers data from memory to the storage
device.
• C uses a structure called FILE (defined in stdio.h) to store the attributes of
a file.
Declaring Variables
1. Create the stream via a pointer variable using the FILE structure:
FILE *p;
2. Open the file, associating the stream name with the file name.
3. Read or write the data.
4. Close the file.
Declaring Variables
• fopen - open a file- specify how its opened (read/write) and type (binary/text)
• fclose - close an opened file
• fread - read from a file
• fwrite - write to a file
• fseek/fsetpos - move a file pointer to somewhere in a file.
• ftell/fgetpos - tell you where the file pointer is located.
Declaring Variables
• r+ - open for reading and writing, start at beginning
• w+ - open for reading and writing (overwrite file)
• a+ - open for reading and writing (append if file exists)
Declaring Variables
Declaring Variables
Declaring Variables
• The file open function (fopen) serves two purposes:
– It makes the connection between the physical file and the stream.
– It creates “a program file structure to store the information” C needs to
process the file.
• Syntax:
filepointer=fopen(“filename”, “mode”);
Declaring Variables
• The file mode tells C how the
program will use the file.
• The filename indicates the system
name and location for the file.
• We assign the return value of
fopen to our pointer variable:
spData = fopen(“MYFILE.TXT”,
“w”);
spData = fopen(“A:\\MYFILE.TXT”,
“w”);
Declaring Variables
• When we finish with a mode, we need to close the file before ending the
program or beginning another mode with that same file.
• To close a file, we use fclose and the pointer variable:
fclose(spData);
Declaring Variables
Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
Declaring Variables
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
Declaring Variables
Syntax:
identifier = getc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
Declaring Variables
write a single character to the output file, pointed to by fp.
Example:
FILE *fp;
char ch;
putc (ch,fp);
Declaring Variables
• There are a number of ways to test for the end-of-file condition. Another way
is to use the value returned by the fscanf function:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}
Declaring Variables
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f \n ", a, b, c) ;
printf (“ %f %d %f \n ", e, f, g) ;
}
Declaring Variables
#include <stdio.h>
#include<conio.h>
void main()
{
char ch;
FILE *fp;
fp=fopen("out.txt","r");
while(!feof(fp))
{
ch=getc(fp);
printf("\n%c",ch);
}
getch();
}
Declaring Variables
Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

Remarks:
fread reads a specified number of equal-sized
data items from an input stream into a block.

ptr = Points to a block into which data is read


size = Length of each item read, in bytes
n = Number of items read
stream = file pointer
Declaring Variables
Example:
#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.txt", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
return 0;
}
Declaring Variables
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);

Remarks:
fwrite appends a specified number of equal-sized data items to an output file.

ptr = Pointer to any object; the data written begins at ptr


size = Length of each item of data
n =Number of data items to be appended
stream = file pointer
Declaring Variables
Example:
#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
Declaring Variables
This function sets the file position indicator for the stream pointed to by
stream or you can say it seeks a specified place within a file and modify it.

SEEK_SET Seeks from beginning of file


SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file
Declaring Variables
Example:
#include <stdio.h>
int main()
{
FILE * f;
f = fopen("myfile.txt", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);
fclose(f);
return 0;
}
Declaring Variables
offset = ftell( file pointer );

"ftell" returns the current position for input or output on the file
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}
Read a File in C Programming//r w a
#include<stdio.h>
int main(){
FILE *fp; }
char c; return 0;}
sample.txt
fp=fopen("sample.txt","r"); GTec Education
if(fp==NULL) Ambattur
Chennai-53.
{ 904123489
printf("\nFile Cant Open or File Not Found..");
}
while(1)
{
c=fgetc(fp);
if(c==EOF)
break;
printf("%c",c);
Read a File in C Programming//r w a
/Write a File#include<stdio.h>
int main(){
FILE *fp;
//fp=fopen("sample.txt","w");
fp=fopen("sample.txt","a");
fprintf(fp,"Gtec Computer Education\n");
fclose(fp);
return 0;}
Declaring Variables
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program.
Four types of storage class:
auto
register
static
extern
Declaring Variables
The auto Storage Class
The auto storage class is the default storage class for all local variables.
Syntax:
{
int mount;
auto int month;
}
The register Storage Class
The register storage class is used to define local variables that should be
stored in a register instead of RAM.
Syntax:
{
register int miles;
}
Declaring Variables
The static Storage Class
The static storage class instructs the compiler to keep a local variable in
existence during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope.
Declaring Variables
Example 1
1.#include<stdio.h>
2.static char c;
3.static int i;
4.static float f;
5.static char s[100];
6.void main ()
7.{
8.printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printe
d.
9.}
Declaring Variables
1.#include<stdio.h>
2.void sum()
3.{
4.static int a = 10;
5.static int b = 24;
6.printf("%d %d \n",a,b);
7.a++;
8.b++;
9.}
10.void main()
11.{
12.int i;
13.for(i = 0; i< 3; i++)
14.{
15.sum();}}
Declaring Variables
1.#include <stdio.h>
1.#include <stdio.h>
2.int main() 2.int a;
3.{ 3.int main()
4.extern int a; 4.{
5.printf("%d",a); 5.extern int a = 0;
6.printf("%d",a);
6.} 7.}
1.#include <stdio.h>
2.int a; 1.#include <stdio.h>
2.int main()
3.int main() 3.{
4.{ 4.extern int a;
5.extern int a; o a 5.printf("%d",a);
6.}
6.printf("%d",a);
int a = 20;
7.}

You might also like