Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
22 views19 pages

Chapter 1 Notes (11 Files Merged) (1) - Invert

The document provides an overview of programming concepts in C, including variables, data types, control structures, functions, pointers, arrays, and file I/O. It outlines the rules for variable naming, the types of constants, keywords, and the structure of C programs. Additionally, it covers advanced topics such as recursion, structures, and the use of standard library functions.

Uploaded by

vk5311009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views19 pages

Chapter 1 Notes (11 Files Merged) (1) - Invert

The document provides an overview of programming concepts in C, including variables, data types, control structures, functions, pointers, arrays, and file I/O. It outlines the rules for variable naming, the types of constants, keywords, and the structure of C programs. Additionally, it covers advanced topics such as recursion, structures, and the use of standard library functions.

Uploaded by

vk5311009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Variables Variables

Variable is the name of a memory Rules


location which stores some data.
a. Variables are case sensitive
b. 1st character is alphabet or '_'

Memory c. no comma/blank space


d. No other symbol other than '_'
a b
25 S

Variables Constants
Data Types
Values that don't change(fixed)

Types

Integer Character
Constants Real Constants
1, 2, 3, 0
Constants a b A',
' ', ' ', '

, -1, -2 '#', '&'


1.0, 2.0,
3.14, -24

Keywords Keywords
Reserved words that have special auto double int stru t c
meaning to the compiler break else long sw t i ch
case enum egister
r ty pedef
32 Keywords in C char extern e n
r tur u nion
continue for s igned v oid
do if st ta ic w hile
default goto i eof
sz v olatile
const float short n igned
u s
Program Structure Comments
Lines that are not part of program
#include<stdio.h>

int main() { Single Line Multiple


printf("Hello World"); Line
return 0; //
/*
*/
}

Output Output
printf(" Hello World "); CASES
1. integers
printf(" age is %d ", age);
new line
printf(" kuch bhi \n"); 2. r eal numbers
printf(" value of pi is %f ", pi);
3. characters
printf(" star looks like this %c ", star);

Input Compilation
A computer program that translates C code
scanf(" %d ", &age); into machine code

a.exe (windows)
Hello.c C Compiler
a.out (linux & mac)
Instructions Instructions
These are statements in a Program Type Declaration Instructions Declare var before using it
VALID INVALID
Types
int a = 22; int a = 22;
int b = a; int b = a;
int c = b + 1; int c = b + 2;
Type Declaration Control int d = 1, e; int d = 2, e;
Instructions Arithmetic Instructions
Instructions int a,b,c;
a = b = c = 1; int a,b,c = 1;

Arithmetic Instructions Arithmetic Instructions


a+b VALID
a=b+c
INVALID
b+c=a
Operand 1 Operand 2 a=b*c a = bc
a=b/c a = b^c
Operator

NOTE - single variable on the LHS NOTE - pow(x,y) for x to the power y

Arithmetic Instructions Arithmetic Instructions


Modular Operator % Type Conversion
Returns remainder for int int op int int
3%2=1

-3 % 2 = -1 int op float float

float op float float


Arithmetic Instructions Arithmetic Instructions
Operator Precedence Associativity (for same precedence)
*, /, % x = 4 + 9 * 10
Left to Right

x=4*3/6*2
+, -

= x = 4*3 / 6*2

Instructions Operators
Control Instructions a. Arithmetic Operators
Used to determine flow of program
b. Relational Operators
a. Sequence Control
c. Logical Operators
b. Decision Control
d. Bitwise Operators
c. Loop Control
e. Assignment Operators
d. Case Control
f. Ternary Operator

Operators Operators
Relational Operators Logical Operators
== && AND
>, >= || OR
<, <= ! NOT
!=
Operator Precendence Operators
Priority Operator Assignment Operators
1 !
=
2 *, /, %
+=
3 +, -

-=
4 <, <=, >, >=

5 ==, != *=

6 &&
/=
7 ||

8 = %=

Conditional Statements if-else


Types
if(Condition) {
//do something if TRUE
if-else Switch }
else {
//do something if FALSE
}

Ele is optional block


can also work without {}

else if Conditional Operators


Ternary
if(Condition 1) {
//do something if TRUE Condition ? doSomething if TRUE : doSomething if FALSE;
}
else if (Condition 2) {
//do something if 1st is FALSE & 2nd is TRUE
}

give 1 & 0 cases


Conditional Operators Conditional Operators
i ch
sw t sw t i ch Properties
i ch(number) {
sw t
a. Cases can be in any order
case C1: //do something
break;
case C2 : //do something
break; b. Nested switch (switch inside switch) are allowed
default : //do something
}

Loop Control Instructions for Loop


To repeat some parts of the program
for(initialisation; condition; updation) {
do something
Types //

}
for while do while

Special Things while Loop

- Increment Operator while(condition) {

- Decrement Operator //do something

}
- Loop counter can be float
or even character
- Infinite Loop
do while Loop break Statement
do {
// do something exit the loop
} while(condition);

continue Statement Nested Loops

for( .. ) {
skip to next iteration for( .. ) {

Functions Syntax 1
Function Prototype
block of code that performs particular task
void printHello( );

Take Do Return
Argument Work Result

it can be used multiple times


increase code reusability
> Tell the compiler
Syntax 2 Syntax 3
Function Definition Function Call
v oid printHello() { int main() {
printf("Hello"); printHello( );
} return 0;
}

> Do the Work > Use the Work

Properties Function Types


- Execution always starts from main
Library User-
function defined
- A function gets called directly or indirectly from main
Special functions declared & defined by
inbuilt in C programmer
canf( ), printf( )
s
- There can be multiple functions in a program

Passing Arguments Passing Arguments


functions can take value give some value
&
v oid printHello( );
parameter e
r turn value
v oid printTable(int n);

int sum(int a, int b);


Passing Arguments Argument v/s Parameter
functions can take value give some value
&
alues that are
v v alues in function
passed in declaration &
function call definition
parameter e n value
r tur

us ed to send us ed to receive
value value

actual formal
parameter parameters

NOTE Recursion
a. Function can only return one value at a time When a function calls itself, it's called recursion
b. Changes to parameters in function don't change the values in
calling function.
Because a copy of argument is passed to the function

Properties of Recursion Pointers


a. Anything that can be done with Iteration, can be done with A variable that stores the memory
recursion and vice-versa. address of another variable
b. Recursion can sometimes give the most simple solution. Memory
c. Base Case is the condition which stops recursion. age ptr

d. Iteration has infinite loop & Recursion has stack overflow 22 2010

2010 2013
Syntax Declaring Pointers
int age 22 = ;
int *ptr;
int *ptr age =& ;
char *ptr;
int age *ptr
_ = ;
float *ptr;
Memory
age ptr
22 2010

2010 2013

Format Specifier Pointer to Pointer


A variable that stores the memory
printf("%p", &age); address of another pointer

printf("%p", ptr); Memory


age pptr ptr
printf("%p", &ptr); 22 2013 2010

2010 2012 2013

Pointer to Pointer Pointers in Function Call


Syntax
Call by call by
int **pptr; Value Reference
char **pptr; We pass value of We pass address of
variable as variable as
argument argument
float **pptr;
Arrays Syntax
int marks[3];
Collection of similar data types stored at char name[10];
contiguous memory locations
float price[2];

Input & Output Inititalization of Array


scanf("%d", &marks[0]); int marks[ ] = {97, 98, 89};

int marks[ 3 ] = {97, 98, 89};


printf("%d", marks[0]);

Memory Reserved :

Pointer Arithmetic Pointer Arithmetic


Pointer can be incremented CASE 2
& decremented
CASE 1

CASE 3
Pointer Arithmetic Array is a Pointer

- We can also subtract one pointer from another int *ptr = &arr[0];

int *ptr = arr;


- We can also compare 2 pointers

Traverse an Array Arrays as Function Argument


int aadhar[10]; //Function Declaration
void printNumbers (int arr[ ], int n)
int *ptr = &aadhar[0]; OR
void printNumbers (int *arr, int n)

//Function Call
printNumbers(arr, n);

Multidimensional Arrays Strings


2 D Arrays
int arr[ ][ ] = { {1, 2}, {3, 4} }; Declare
//
A character array terminated by a '\0' (null character)
null character denotes string termination
// Access
EXAMPLE
arr[0][0]
arr[0][1] char name[ ] = {'S', 'H', 'R', 'A', 'D', 'H', 'A','\0'};
arr[1][0] char class[ ] = {'A', 'P', 'N', 'A', ' ', 'C', 'O', 'L', 'L', 'E', 'G', 'E', '\0'};
arr[1][1]
Initialising Strings What Happens in Memory?
char name[ ] = {'S', 'H', 'R', 'A', 'D', 'H', 'A','\0'};
char name[ ] = {'S', 'H', 'R', 'A', 'D', 'H', 'A','\0'};
char name[ ] = "SHRADHA";
char name[ ] = "SHRADHA";

name
char class[ ] = {'A', 'P', 'N', 'A', ' ', 'C', 'O', 'L', 'L', 'E', 'G', 'E', '\0'}; S H R A D H A \0

char class[ ] = "APNA COLLEGE"; 2000 2001 2002 2003 2004 2005 2006 2007

String Format Specifier IMPORTANT


scanf( ) cannot input multi-word strings with spaces
"%s"

Here,
char name[ ] = "Shradha"; gets( ) & puts( ) come into picture
printf("%s", name);

String Functions String using Pointers


gets(str) Dangerous &
Outdated puts(str) char *str = "Hello World";
Store string in memory & the assigned
input a string output a string address is stored in the char pointer 'str'
even multiword)
(

char *str = "Hello World"; //can be reinitialized

fgets( str, n, file)


stops when n-1
chars input or new
line is entered char str[ ] = "Hello World";
//cannot be reinitialized
Standard Library Functions Standard Library Functions
<str ing.h> ing.h>
<str

1 strlen(str) 2 strcpy(newStr, oldStr)


count number of characters excluding '\0' copies value of old string to new string

Standard Library Functions Standard Library Functions


<str ing.h> ing.h>
<str

3 strcat(firstStr, secStr) 4 str cpm(firstStr, secStr)


concatenates first string with second string Compares 2 strings & returns a value
0 -> ing equal
str

positive -> first > second (ASCII)


negative -> first < second (ASCII)
firstStr should be large
enough

Structures Syntax
struct student { struct student s1;
a collection of values of different data types
char name[100]; s1.cgpa = 7.5;

int roll;
EXAMPLE
For a student store the following : float cgpa;
name (String) };

r oll no (Integer)
cgpa (Float)
Syntax Structures in Memory name roll cgpa
struct student { c dent
stru t stu {

char name[100]; char name 100


[ ]; 2010 2110 2114

int roll; int roll


;

float cgpa;
float cgpa ;

}
}

c e a e o ed in contiguous memory locations


stru tur s r st r

Benefits of using Structures Array of Structures


- Saves us from creating too many variables
c
stru t student ECE[100];
struct student COE[100];
- Good data management/organization
c
stru t stu dent IT[100];

ACCESS
IT[0].roll = 200;
IT[0].cgpa = 7.6;

Initializing Structures Pointers to Structures


struct student s1;
struct student s1 = { "shradha", 1664, 7.9};
struct student *ptr;
struct student s2 = { "rajat", 1552, 8.3};

struct student s3 ={ 0 };
ptr =&s1;
Arrow Operator Passing structure to function

(*ptr).code ptr->code //Function Prototype


void printInfo(struct student s1);

ty pedef Keyword File IO


RAM Hard Disk
us ed to create alias for data types

coe student1;

File IO Operation on Files


FILE - container in a storage device to store data Create a File
Open a File
- RAM is volatile Close a File
- Contents are lost when program terminates Read from a File

- Files are used to persist the data Write in a File


Types of Files File Pointer
Text Files Binary Files FILE is a (hidden)structure that needs to be created for opening a file
A FILE ptr that points to this structure & is used to
textual data binary data access the file.
.txt, . c .exe, .mp3, .jpg

FILE *fptr;

Opening a File File Opening Modes


FILE *fptr; "r" open to read
fptr = fopen("filename", mode); "rb" open to read in binary
"w" open to write
"wb" open to write in binary
Closing a File "a" open to append
fclose(fptr);

BEST Practice Reading from a file


Check if a file exists before reading from it.
char ch;
fscanf(fptr, "%c", &ch);
Writing to a file Read & Write a char
fgetc(fptr)
char ch = 'A';
fputc( 'A', fptr)
fprintf(fptr, "%c", ch);

EOF (End Of File) Dynamic Memory Allocation


fgetc returns EOF to show that the file has ended It is a way to allocate memory to a data structure during
the runtime.

We need some functions to allocate


& free memory dynamically.

Functions for DMA malloc( )


memory allocation
a. malloc( )
takes number of bytes to be allocated
b. calloc( )
& returnsa pointer of type void
c. free( )
d. realloc( ) ptr = (*int) malloc(5 * sizeof(int));
calloc () free ()

We use it to free memory that is allocated


continuous allocation

initializes with 0 ing malloc calloc


us &

ptr = (*int) calloc(5, sizeof(int)); free ptr


( );

realloc( )

reallocate (increase or decrease) memory


using the same pointer & size.

ptr = realloc(ptr, newSize);

You might also like