C LANGUAGE NOTES

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

Excel shortcuts

C LANGUAGE NOTES #cs50pg1


 == means equals to
 %s means take the value from string and put it in that place it’s a place holder
 || means or Boolean expression
 Conio.h is used to take input from keyboard
 In c the convention is to indent 4 spaces

1 2 3 4 printf(“xyz”);

 Variables stores value


 = assignment
 You use words int, string only when creating the variable after if you want to do changes in
The variable you don’t have to mention int
 While(true) starts a forever loop any non-zero value is interpreted as true so anything other
than 0 in the parenthesis will be true and will start a forever loop…..to include values like
true we have to use another header file as <stdbool.h>
 Ctrl c will help you cancel a forever loop or to get out of the terminal window
 mv will not only move the file but it can also be used to rename the file
 you can make a variable constant by const
 // is used for comments single line
 Double line comments /*…comment….*/
 Abstraction- creating functions

Int get_size(void) // this has integer output and no input

Void print_grid(int size) // this has no output but takes input of variable size

 Int uses 32 bit of storage of our computer’s RAM 2^31 to the positive and 2^-31 to the
negative
 To avoid integer overflow we use long which has more bit’s……….long uses 64 bit
 %f represents floating point value
 Type casting converting one data value to another …. Used to avoid truncation
 Floating point imprecision the computer can be precise only upto certain value……. Double is
used to solve this problem it has twice as many bits as that of float
 Unsigned data type eliminates negative and and the range for positive goes upto 4 billion
 Char data type takes 8 bit (1 byte) of memeory
 Float store 32 bits (4 byte)……double 64 bits
 Void is a type but not a data type…..functions can have void return type(they don’t return
value)
 String stores a series of char
 Don’t redeclare var again and again just once is enough…..intialisation is another thing it’s
different from declaring
 Modulus operator (%) used for getting the remainder
 X = x*5 or x *= 5 same thing

 Boolean expressions are of two types logical and relational operators #cs50pg2
 (&&) called impercent is used for two variables it is only true when both variables are true
 (||) this is logical or true when either one is true called vertical block
 (!) logical not
 Relational operators: <,>,== (equality),=! (inequality),
 Conditionals: if, if-else, else-if, nested loop if-if-if-else,
 Switch statement (imp break;)
 Int X = (expression) ? 5 : 6; ( if else statement short form ) called ( ? :) ternary operator ( it
works like if expression is true the value will be 5 else the value will be 6)
 while ( Boolean expr) loop starts when the Boolean expr is true
 do while this loop will execute all lines of code inside the curly bracket that comes under do
and then checks the condition again repeats the loop
 for loop it can declare and initialize variable then gives Boolean expr in middle then
increment or decrement [ for (start; bool expr; increment)]
 while -use to repeat a loop unknown no. of times, and possibly not at all
 do- while – use to repeat a loop an unknown number of times, but at least once
 for – loop repeats discreate number of times’
 linux command line: 1)ls (list) (gives list of all the files in the directory..green is the
executable file)
2) cd (change directory) – allows to navigate between the directory … pwd- present working
directory (helps you identify where you are)
3) mkdir – make directory
4) cp – copy ( cp sorce to destination)
5) rm – to remove file
6) mv – move sorce to destination

ARRAYS

ciphertext encrypted text transformed from plaintext using an


encryption algorithm

Compiler – clang, gcc

#cs50pg3
Pre processor – are used processed before the program- #include

Compiling – converts the program in assembly language

Assembling – converts to machine code

Linking – links all the code

For finding errors in the code you can use – printf , debug50 ,
rubber duck

Data types-

1) bool – 1 byte
2) int - 4 byte
3) long – 8 bytes
4) float – 4 bytes
5) double - 8 bytes
6) char - 1 byte
7) string – depends

0\ representation of 0 in memory or as a character or you can also


represent as null

If – strings words[2];

Words[0] = “hi!”;

Words[1] = “BYE”;

Printf(“%s\n”, words[0]);

#cs50pg4
Printf(“%s\n”, words[1]); ….this will print the letters on that index

You can find the length of the string length by using library string.h
as shown below-

Int main(void)

String name = get_string(“name: “);

Int length = strlen(name);

Printf(“%i\n”,length):
}

We have a library called ctype.h which has toupper function which


converts lower case letters into upper case

*search about command line arguments

When a program exits without error, a status code of 0 is provided


the computer. Often, when an error occurs that results in the
program ending, a status of 1 is provided by the computer.

Cryptography is the art of ciphering and deciphering a message.

plaintext and a key are provided to a cipher, resulting in ciphered


text.
The key is a special argument passed to the cipher along with the
plaintext. The cipher uses the key to make decisions about how to
implement its cipher algorithm.

There are two types of error that occur in a program – syntactical


and logical

#cs50pg5
C++ NOTES

Data types

Primitive – int, float, char , Boolean

Derived - function, array, pointer, refrence

User defined – class, structure, union, enum

SIZE : Int and float 4 byte char and bool 1 byte


PREPROCESSOR DIRECTIVE - # include

Iostream.h-header file for taking input and output

Return 0 – exit status it tells the complier that the program is over it
will not execute anything after that

Difference between while and dowhile – in do while the loop will


work atleat one time

Continue-is used to skip to the next iteration of the loop

Break- is used to terminate the loop

= - Assigns value
C notes
 variables is the name of a memory location which stores some data – case sensitive, 1st
character is alphabet or underscore, variable can’t be a comma, blank space, only
underscore can be used in variable
 keywords are special words which are known to the compiler eg: int, switch, break, float etc.
 %d is used to store int value, % f is used to store float value , %c is used to store character
value
 For taking input use scanf : scanf (“%d”,&age)
 Compiler translates C cod into machine code : gcc hello.c
 For running the program for windows: ./a.exe
 Instruction – statements
 Type declaration instruction - in which you give value to a variable but remember to declare
variable before using it
 A+B …. A= operand1 , B=operand 2, + = operand …. If y= A+B (the value of A+B is stored in y)
 Precedence – priority order of operators : (1) *,/,% (2) +,-(3) =(assignment) …….. and always
calculate from left to right for operators like / , * they have the same preference so go from
left to right….if there’s bracket solve inside the bracket
 Relational operators : ==, >,<,<=,!= (don’t give space between exclamation and equal to sign)
 True =1
 False=0
 A= A+B OR A+=B
 ‘I’ is iterator variable or counter
 ++1 pre increment, 1++ post increment, --1 pre decrement, 1-- post decrement
 Break helps us to get out of the loop…..remember break,gets you out of nested loop
 Continue skip to next iteration
 Function is a block of code that performs a particular task
 Passing arguments –parameter (it takes value), return value (it gives value)
 Above is the precedence order when logical and arithmetic operators are in one expression

ARGUMENT VS PARAMETER

1) Values that 1) values in function

Are passed declaration &

In function definition

Call

2) Used to send 2) used to receive

Value Value

3)Actual parameter 3) formal parameters

 Function can return only one value at a time


 Use %f to print double values
 Anything done by iteration i.e. for loop can be done by recursion and vice-versa
 Base case stops the recursion
 Iteration has infinite loop and recursion has stack overflow means the memory overflows
 Pointer is a variable that stores the memory address of another variable
 Syntax : int*ptr = &age; (*value at address , & address of operator
Int_age= *ptr;
 %p is for pointer address it prints a hexadecimal number
 %u is for unsigned int
 Pointer to pointer is a variable that stores the memory address of another pointer
 Syntax : int **pptr;
 Pointers in function call : call by value – we pass of variable as argument, call by refrence –
we pass address of variable as argument
 When we call a function the value changes but when we go back in main function the value
does not change there but if we pass a pointer variable it makes changes in the actual value
therefore the value in the main function also changes
 Remember in call by value you are not making changes in actual value you are making a
copy of that value so the address in call by value will never be same
 If you pass the address to the calling function then it is call by refrence
 Ptr++ will change the data type by so if the type is int then 4bytes will be added to the
memory location vice versa with the decrement operator
 Char will increase by one byte
 For float +4 byte
 Array is a pointer
 Arrays as function argument void printnos(int arr[],int n) or void printnos(int * arr, int n
 Multidimensional array –
2d array - int arr [][] ={{1,2},{3,4}}; //declare
//acess
Arr[0][0]
Arr[0][1]
Arr[0][1]
Arr[1][1]
You can imagine this in the form of matrix
But it is stored in thee memory in the form of 1,2,3,4 . at arr[0][0] = 1,arr[0][1]=2

Initializing an array – char name[] = {‘S’,’A’,’B’,’H’,’Y’,’A’,’\0’};

Char name[] = “SABHYA”; …………..remember the quotes while writing words


and strings

String format specifier - %s remember for pointer there is no need of &


Whenever you enter %s , then there is no need to input ‘\0’ char

Scanf() cannot input multi-word strings with spaces

Gets() and puts() come into picture and also fgets()-

Gets(str)-input , puts(str)-output, fgets(str, n, file) – use stdin for file., and it stops when n-1 char
input or new line is entered……..puts print the statement and it automatically puts you in next line

String is a pointer

Initializing string using pointer – char *str = “hello world”;

Difference between initializing the string with pointer and array – with pointer you can reinitialize
the strings, arrays can not be modified

Standard lbrary function – <string.h>

1) Strlen(arr)……..used for – count number of characters excluding ‘\0’


2) Strcpy(newstr, oldstr)- copies the value of oldstr in new str
3) Strcat(firststr,secstr) – concatenates first string with second string
4) Strcmp (firststr,secstr)- 0 means equal string , +ve value means first > sec (ascii), -ve value
means sec>first (ascii) ………….[it will do secstr-first str and will-ve value or +ve value]

Structures – is a collection of values of different data types

Syntax- struct student {


char name [100];

Int roll;

Float cgpa;

Use – struct student s1;

S1.name

S1.rollno
Benefits of array – you don’t have to rememeber 100 variables, it also helps in concepts like salting

Benefits of structure – we don’t have to declare a lot of variable , good data management and
organization

ARRAY OF STRUCTURES –

Struct student ECE[100]; ……………….saving information of 100 students

ECE[0].roll=700;

INTIALIZING STRUCTURE –

Struct student s1 ={“sabhya”,1664,7.9};

Struct student s2 ={0};……this means all values are null values

INTIALISING STRUCTURE USING POINTER –

Struct student *ptr;

Ptr = &s1;

INTIALIZING STRUCTURE BY FUNCTION –

Void info(struct student s1);

structure pass value by call by value therefore if you make any change in the function and pass it to main the value will not change but
if you change the value in main before calling the function then the value will change and new value will be passed to the function

type def keyword (nick name)-

typedef struct computerengineeringstudent

{ int roll;

Int name;} coe;

Coe student1; …..variable

RAM – volatile memory ……contents are lost when program terminates

HARD DISK – non volatile memory

File – container in a storage device to store data……used to persist data

Operations on file : create, open , close , read , write

Types – text(.txt , .c) , binary(.exe, .mp3 , .jpg)


FILE POINTER – 1) hidden structure that needs to be created for opening a file

2) a file ptr that points to this structure & is used to acess the file

3) syntax – FILE *fptr; ……file is data type as it is structure

4) fptr = fopen("filename",mode);

MODES –

1) “r” open to read


2) “rb” open to read in binary…..in r and rb mode if the file does not exist null will be stored in
ptr
3) “w” open to write
4) “wb”open to write in binary….if a file does not exist then these two function will create a file

And if a file exist then that file will open and all the data in the file will get deleted and new data
will be stored

5) “a” open to append………..if you want to keep the data and store new data
Make sure if you check if a file exists before using it

Reading from a file - fscanf(fptr, “%c”,&ch);

fgetc(fptr)…..char read

fputc(‘a’,fptr)….char read…..remember only applicable to charchter for other data types use fscanf

EOF(END OF FILE) -fgetc returns EOF to show that the file has ended

DYNAMIC MEMORY ALLOCATION (DMA)

It is a way to allocate memory to a data structure during the runtime…..we need functions to
allocate memory dynamically

Runtime - time between start and end of program

Functions for DMA

a. Malloc() memory allocation


b. Calloc() continuous allocation
c. Free()
d. Realloc() re alloc..
MALLOC – it gives us the required memory in between the code ….memory should be in
bytes and returns a pointer of type void
Ptr = (*int)malloc(5*sizeof(int)); size of returns us the size of any data type
CALLOC – all the values are initialized to zero by this function
Ptr = (*int)calloc(5,sizeof(int));………..remember while writing program write like this int*
FREE – we use it to free memory that is allocated using malloc & alloc
Free (ptr );
REALLOC – reallocate(increase or decrease) memory using the same pointer &size.
Ptr = realloc(ptr,newsize);
PYTHON

 You can write text in double as well as in single quotes


 Python is a case sensitive language
 Float,integer,Boolean
 Concatenation process of joining a variable and a text statement
 Arithmetic operators +,-,/,*
 % remainder operator
 **power eg:5**2 that means 5 to the power 2
 i+=2 same as c
 # for comments
 elif means else if
 range is a function : range(5) , output: range(0,5)
 i=1
while i<=n:

Print(i) ………starts infinite loop

 [] list
 () tuple not compulsory
 {} set
 There is no index in set (unodered)
 Dictionary if information is stored in pair then that info is stored in dictionary
 Function : if a part performs a specific operation that is called function
 Types of functions : in-built,module,user-defined
 In built – int, str, bool
 Module – import math
 Print(dir(math)) …….(all the function in the math directory will be printed)

From math import sqrt

Print(sqrt(4))

From math import *……..(means you can use all the function no need to mention sqrt or any

other function just mention them while printing)


 User defined function : syntax-
def function_name(parameters): //do something

You might also like