C cheat sheet for varsity (extreme edition)

download C cheat sheet for varsity (extreme edition)

If you can't read please download the document

Transcript of C cheat sheet for varsity (extreme edition)

  1. 1. Author: Md. Saifur Rahman Education: 4th semester at CSE Department in Southeast University Banani, Dhaka, Bangladesh. Md. Saifur Rahman C Programming Language
  2. 2. C Cheat Sheet For Varsity c Case Sensitive(small/large) C has supportfor Octal & Hexadecimal Programs C Programing structure(has 3 parts) 1. Include files(header files) 2. Main function( main() ) 3. Other(Library/user defined functions) Function writting main() { } void main() { } int main() { return 0; } int main(void) { return 0; } void main(void) { return 0; } int main () { printf ("Welcome to C language"); return 0; } #include int main () { printf ("Welcome to C language"); return 0; } Header files In C, the contents of a module consist of structure type (struct) declarations, global variables, and functions. The functions themselves are normally defined in a source file (a .c file). Except for the main module, each source (.c) file has a header file (a .h file) associated with it that provides the declarations needed by other modules to make use of this module. The idea is that other modules can access the functionality in module X simply by #include "X.h" for the header file, and the linker will do the rest. The code in X.c needs to be compiled only the first time or if it is changed; the rest of the time, the linker will link Xs code into the final executable without needing to recompile it, which enables the Unix make utility and IDEs to work very efficiently. A header file is a file with extension .h which contains C function declarations and macro definitions and to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that come with your compiler. You request the use of a header file in your program by including it, with the C preprocessing directive #include like you have seen inclusion of stdio.h header file, which comes along with your compiler.
  3. 3. keywords Word 32 Identifier Name int a=5, b=10; here a, b identifier Identifier helps variables to remind its name Identifier Character String a a a Variable In memory there are million of locations. Varables means the name of specific location of memory which can store data & its values. Variables Value can be changed but address cannot be changed. Name of the randomaccess memory (RAM) loacation which can contains data so that nest time we can find the data easily.
  4. 4. string integer floating point saifur 67 67.0 A+ 4 4.0
  5. 5. Difference Character Set A - Z a z + - / * $ % 1 2 3 etc Total numbers of characters 28 = 256 Character set are the set of alphabets, letters and some special characters that are valid in C language. Data Types Function Input: Type Input: Value Output: Type Output: Value abs() int int int int fabs() float float float float ceil() float int / float float int floor() float int / float float int fmod() int / float int / float float int / float Sqrt() float int float Int/float Pow() Int/float int / float float int / float Log() Int/float Int/float float Int / float Exp() float float Alphabet Alphabets: Uppercase: A B C .................................... X Y Z Lowercase: a b c ...................................... x y z Digits: 0 1 2 3 4 5 6 8 9 Special Characters: White space Characters: blank space, new line, horizontal tab, carriage return and form feed Special Characters in C language , < > . _ ( ) ; $ : % [ ] # ? ' & { } " ^ ! * / | -~ + Integer Type Turbo C++ (16 Bit) Visual C++ (32 Bit) GCC / g++ 64 Bit short 2 Byte (16 Bit) 2 2 - int 2 4 4 8 long 4 4 4 - long long - 8 8 8 Entity Size in Bytes NULL 2 EOF 2 1 1 1 2 1 char 1 Int 2 Float 4
  6. 6. Range Signed short/int/long/long long Unsigned short/int/long/long long Usage Decimal Hexa-Decimal int + float int 1 Byte/B 8 Bit 1 KB 1024 Byte 1 MB 1024 KB 1 GB 1024 MB 1 TB 1024 GB Int Float /Fractional Character 1 Byte short 2 int 2/4 long 4 float 4 long long 8 double 8 long double 10 Brackets ( ) Parentheses { } Curly Brackets / Braces [ ] Squarebrackets Type conversion Examples small + small = large small + large = large large + large = extra large minimum low result: int & float (char & float & short) char + char =int float + float = double int + float = double double da = 3.3; double db = 3.3; double dc = 3.4; int result = (int)da + (int)db + (int)dc; //result == 9 char + int =int float +double = double long + double = double int + int =long int double +long double=long double int + char = int int + long int=long int int + long long = long long 1st Operand Type Operator 2nd Operand Type Expression Type char / int + - * / int / char int short int / int int / short int int long int / int int / long int long int char / int / float float float char / int / float double double float / double double double double, double / long double long double long double
  7. 7. 32 Bit / 4 Byte { 1Bit (contains = 0,1)} 65536 32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2^31 2^30 2^29 2^28 2^27 2^26 2^25 2^24 2^23 2^22 2^21 2^20 2^19 2^18 2^17 2^16 2^15 2^14 2^13 2^12 2^11 2^10 2^9 2^8 2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
  8. 8. ASCII Character set/ American Standard Code for Information Interchange A = 65 a = 97 0 = 48 Total character = 256 ( 0 -> 255) Space = 32 Escape Sequence Escape Sequence Represents a Bell / (alert) / beep / b Backspace / non-erase f Formfeed / clear screen / new page / n New line r Carriage return t Horizontal tab v Vertical tab ' Single quotation mark" Double quotation markBackslash ? Literal question mark 0 Nullooo ASCII character in octal notation x hh ASCII character in hexadecimal notation x hhhh Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal. For example, WCHAR f = L'x4e00' or WCHAR b[] = L"The Chinese character for one is x4e00". Library/Built-In Function Serial Name Description Parameters Return Value Example & output
  9. 9. 1 abs() Absolute value Returns the absolute value of parameter n ( /n/ ). In C++, this function is also overloaded in header for floating- point types (see cmath abs), in header for complex numbers (see complex abs), and in header for valarrays (see valarray abs). double abs (double x); float abs (float x); long double abs (long double x); Integral value. The absolute value of n. 1. Absolute value for int input & 2. int value for output Like( abs(-3)=3 ) 1 2 3 4 5 6 7 8 9 10 11 12 13 /* abs example */ #include /* printf */ #include /* abs */ int main () { int n,m; n=abs(23); // 23 m=abs(-11); // 11 printf ("n=%dn",n); printf ("m=%dn",m); return 0; } 2 fabs() Compute absolute value Returns the absolute value of x: |x|. double fabs (double x); float fabsf (float x); long double fabsl (long double x); Value whose absolute value is returned. The absolute value of x. 1. Absolute value for floating point input but 2. Int value for output Like( fabs(-3.5)=3.5 ) 1 2 3 4 5 6 7 8 9 10 /* fabs example */ #include /* printf */ #include /* fabs */ int main () { printf ("The absolute value of 3.1416 is %fn", fabs (3.1416) ); printf ("The absolute value of -10.6 is %fn", fabs (-10.6) ); return 0; } Result::::::: The absolute value of 3.1416 is 3.141600 The absolute value of -10.6 is 10.600000 3 Ceil() Round up value Rounds x upward, returning the smallest integral value that is not less than x. double ceil (double x); float ceilf (float x); long double ceill (long double x); Value to round up. The smallest integral value that is not less than x (as a floating-point value). 1. To get Larger int output 2. Value int 3. Type floating Like( ceil(2.5)=3.0 ) 1 2 3 4 5 6 7 8 9 10 11 12 /* ceil example */ #include /* printf */ #include /* ceil */ int main () { printf ( "ceil of 2.3 is %.1fn", ceil(2.3) ); printf ( "ceil of 3.8 is %.1fn", ceil(3.8) ); printf ( "ceil of -2.3 is %.1fn", ceil(-2.3) ); printf ( "ceil of -3.8 is %.1fn", ceil(-3.8) ); return 0; } Output: ceil of 2.3 is 3.0 ceil of 3.8 is 4.0 ceil of -2.3 is -2.0 ceil of -3.8 is -3.0 4 floor() double floor (double x); float floorf (float x); long double floorl (long double x); Round down value Rounds x downward, returning the largest integral value that is not greater than x. Header provides a type-generic macro version of this function. Value to round down. The value of x rounded downward (as a floating-point value). 1. To get smaller int output but 2. Value int 3. Type floating point Like( floor(2.5)=2.0 ) 1 2 3 4 5 6 7 8 9 10 11 12 /* floor example */ #include /* printf */ #include /* floor */ int main () { printf ( "floor of 2.3 is %.1lfn", floor (2.3) ); printf ( "floor of 3.8 is %.1lfn", floor (3.8) ); printf ( "floor of -2.3 is %.1lfn", floor (-2.3) ); printf ( "floor of -3.8 is %.1lfn", floor (-3.8) ); return 0; } Output: floor of 2.3 is 2.0 floor of 3.8 is 3.0 floor of -2.3 is -3.0 floor of -3.8 is -4.0 5 fmod() double fmod(double x, double y); The C library function double fmod(double x, double y) returns the remainder of x divided by y. The C library function double fmod(double x, double y) returns the remainder of x divided by y. 1. Type floating point 2. Value int / floating point 1 2 3 4 5 6 7 8 9 10 /* fmod example */ #include /* printf */ #include /* fmod */ int main () { printf ("fmod of 2.5 / 2 is %lfn", fmod(2.5,2)); printf ( "fmod of 5.3 / 2 is %fn", fmod (5.3,2) ); printf ( "fmod of 18.5 / 4.2 is %fn", fmod (18.5,4.2) ); printf ( "fmod of 18.5 / 4.2 is %fn", fmod (5,2) ); return 0; } Output: fmod of 2.5 / 2 is 0.500000 fmod of 5.3 / 2 is 1.300000 fmod of 18.5 / 4.2 is 1.700000 6 sqrt() Returns the square root of x. Additional overloads are provided in this header () for the integral types: These overloads effectively cast x to a double before calculations (defined for T being any integral type). This function is also overloaded in and (see complex sqrt and valarray sqrt). 1 2 3 4 5 6 7 8 9 10 11 12 /* sqrt example */ #include /* printf */ #include /* sqrt */ int main () { double param, result; param = 1024.0; result = sqrt (param); printf ("sqrt(%f) = %fn", param, result ); return 0; } Output: sqrt(1024.000000) = 32.000000 7 pow() base Base value. exponent Exponent value. The result of raising base to the power exponent. If x is finite negative and y is finite but not an integer value, it causes a domain error. If both x and y are zero, it may also cause a domain error. If x is zero and y is negative, it may cause a domain error or a pole error (or none, depending on the library implementation). The function may also cause a range error if the result is too great or too small to be represented by a value of the return type. 1 2 3 4 5 6 7 8 9 10 11 /* pow example */ #include /* printf */ #include /* pow */ int main () { printf ("7 ^ 3 = %fn", pow (7.0, 3.0) ); printf ("4.73 ^ 12 = %fn", pow (4.73, 12.0) ); printf ("32.01 ^ 1.54 = %fn", pow (32.01, 1.54) ); return 0; } Output:
  10. 10. 7 ^ 3 = 343.000000 4.73 ^ 12 = 125410439.217423 32.01 ^ 1.54 = 208.036691 8 log() double log (double x); float log (float x); long double log (long double x); double log (T x); // additional overloads for integral types Returns the natural logarithm of x. The natural logarithm is the base-e logarithm: the inverse of the natural exponential function (exp). For common (base-10) logarithms, see log10. Value whose logarithm is calculated. If the argument is negative, a domain error occurs. 1 2 3 4 5 6 7 8 9 10 11 12 /* log example */ #include /* printf */ #include /* log */ int main () { double param, result; param = 5.5; result = log (param); printf ("log(%f) = %fn", param, result ); return 0; } Output: log(5.500000) = 1.704748 9 exp() double exp (double x); float exp (float x); long double exp (long double x); double exp (T x); // additional overloads for integral types Compute exponential function Returns the base-e exponential function of x, which is e raised to the power x: ex. Additional overloads are provided in this header () for the integral types: These overloads effectively cast x to a double before calculations. This function is also overloaded in and (see complex exp and valarray exp). Value of the exponent. Exponential value of x. If the magnitude of the result is too large to be represented by a value of the return type, the function returnsHUGE_VAL (or HUGE_VALF or HUGE_VALL) with the proper sign, and an overflow range error occurs: 1 2 3 4 5 6 7 8 9 10 11 12 /* exp example */ #include /* printf */ #include /* exp */ int main () { double param, result; param = 5.0; result = exp (param); printf ("The exponential value of %f is %f.n", param, result ); return 0; } Output: The exponential value of 5.000000 is 148.413159. 10 rand() int rand (void); Generate random number Returnsa pseudo-randomintegral numberinthe range between0 andRAND_MAX. Thisnumberisgeneratedbyan algorithmthatreturnsa sequence of apparently non-relatednumberseachtime itiscalled.This algorithmusesaseedtogenerate the series,whichshouldbe initializedtosome distinctivevalueusing functionsrand. RAND_MAXisa constantdefinedin . A typical wayto generate trivial pseudo-randomnumbersinadeterminedrange usingrandis to use the moduloof the returnedvalue bythe range spanand add the initial value of the range: 1 2 3 v1 = rand() % 100; // v1 in the range 0 to 99 v2 = rand() % 100 + 1; // v2 in the range 1 to 100 v3 = rand() % 30 + 1985; // v3 in the range 1985-2014 Notice thoughthatthismodulooperationdoesnotgenerate uniformlydistributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely). C++ supports a wide range of powerful tools to generate random and pseudo- random numbers (see for more info). An integer value between 0 and RAND_MAX. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 /* rand example: guess the number */ #include /* printf, scanf, puts, NULL */ #include /* srand, rand */ #include /* time */ int main () { int iSecret, iGuess; /* initialize random seed: */ srand (time(NULL)); /* generate secret number between 1 and 10: */ iSecret = rand() % 10 + 1; do { printf ("Guess the number (1 to 10): "); scanf ("%d",&iGuess); if (iSecretiGuess) puts ("The secret number is higher"); } while (iSecret!=iGuess); puts ("Congratulations!"); return 0; } In thisexample,the randomseedisinitializedtoavalue representingthe currenttime (callingtime) togenerate adifferentvalue everytime the programisrun. Possible output: Guess the number (1 to 10): 5 The secret number is higher Guess the number (1 to 10): 8 The secret number is lower Guess the number (1 to 10): 7 Congratulations! 11 srand() void srand (unsigned int seed); Initialize random number generator The pseudo-random number generator is initialized using the argument passed as seed. For everydifferentseed value usedinacall to srand,the pseudo-randomnumber generator can be expected to generate a different succession of results in the subsequent calls to rand. Two differentinitializationswiththe same seed will generate the same succession of results in subsequent calls torand. If seed is setto 1, the generatorisreinitializedto its initial value and produces the same values as before any call to rand or srand. In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header ). This is distinctive enough for most trivial randomization needs. An integer value to be used as seed by the pseudo- random number generator algorithm. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 /* srand example */ #include /* printf, NULL */ #include /* srand, rand */ #include /* time */ int main () { printf ("First number: %dn", rand()%100); srand (time(NULL)); printf ("Random number: %dn", rand()%100); srand (1); printf ("Again the first number: %dn", rand()%100); return 0; } Possible output: First number: 41 Random number: 13 Again the first number: 41 12 tolower() short _tolower (short c); Translates uppercase characters to lowercase. _tolower does the same conversion as tolower or toextlower, except that it should be used only when c is known to be uppercase (either ordinary or foreign). It is faster, and generates much shorter code than tolower. _tolower returns the converted
  11. 11. value of c if it is uppercase; otherwise, the result is undefined. _tolower is a simple macro. short tolower (short c); Translates characters to lowercase. tolower is a function that converts an integer c to its lowercase value ('a' to 'z') if it was uppercase ('A' to 'Z'). All others are left unchanged. Returns the converted value of c. tolower is a relatively small inline function which is implemented using GNU C smart macros. 13 toupper() short _toupper (short c); Translates uppercase characters to lowercase. _toupper does the same conversion as toupper or toextupper, except that it should be used only when c is known to be lowercase (either ordinary or foreign). It is faster, and generates much shorter code than toupper. _toupper returns the converted value of c if it is lowercase; otherwise, the result is undefined. _toupper is a simple macro. short toupper (short c); Translates characters to uppercase. toupper is a function that converts an integer c to its uppercase value ('A' to 'Z') if it was lowercase ('a' to 'z'). All others are left unchanged. Returns the converted value of c. toupper is a relatively small inline function which is implemented using GNU C smart macros. 14 isalnum() short isalnum (short c); Checks whether a character is an alphanumeric. isalnum returns nonzero if c is a letter ('A' to 'Z' or 'a' to 'z') or a digit ('0' to '9'), otherwise it returns zero. It is an inline function which is implemented using GNU C smart macros, which expands to a medium- sized code. 15 isalpha() short isalpha (short c); Checks whether a character is a letter. isalpha returns nonzero if c is a letter ('A' to 'Z' or 'a' to 'z'), otherwise it returns zero. It is an inline function which is implemented using GNU C smart macros, which expands to a relatively small code. 16 isascii() short isascii (short c); Checks whether a character is an ASCII character. isascii returns nonzero if c is in the range 0 to 127 (0x00-0x7F), otherwise it returns zero. It is a simple macro. 17 islower() short islower (short c); Checks whether a character is a lowercase. islower returns nonzero if c is a lowercase letter ('a' to 'z'), otherwise it returns zero. It is a small inline function which is implemented using GNU C smart macros.
  12. 12. 18 isupper() short isupper (short c); Checks whether a character is an uppercase. isupper returns nonzero if c is an uppercase letter ('A' to 'Z'), otherwise it returns zero. It is a small inline function which is implemented using GNU C smart macros. 19 toascii() short toascii (short c); Translates characters to ASCII format. toascii converts the integer c to ASCII by clearing all but the lower 7 bits. This gives a value in the range 0 to 127. Returns the converted value of c. toascii is a simple macro. 20 printf(); printf("hello world"); 21 fprintf(); fprintf(stdout, "hello world"); fprintf(stderr,"hello world"); PRECEDENCE GROUPS
  13. 13. OperatorName Associativity Operators Primary scoperesolution left to right :: Primary left to right () [ ] . -> dynamic_cast typeid Unary right to left ++ -- + - ! ~ & * (type_name) sizeof new delete C++ Pointer to Member left to right .*->* Multiplicative left to right * / % Additive left to right + - Bitwise Shift left to right > Relational left to right < > = Equality left to right == != Bitwise AND left to right & Bitwise Exclusive OR left to right ^ Bitwise Inclusive OR left to right | Logical AND left to right && Logical OR left to right || Conditional right to left ? : Assignment right to left = += -= *= /= = %= &= ^= |= Comma left to right ,
  14. 14. printf scanf I/O of floats in C #include int main(){ float a; printf("Enter value: "); scanf("%f",&a); printf("Value=%f",a); //%f is used for floats instead of %d return 0; } Output Enter value: 23.45 Value=23.450000 The scanf() function is used to take input from user. In this program, the user is asked a input and value is stored in variable a. Note the '&' sign before a. &a denotes the address of a and value is stored in that address. Conversion specifier printf scanf %c char (single character) %d integer %d integer %f float or double %e ,%f, %g float %h short %s string (char array) %lf double (first character is l, not one 1)
  15. 15. %c char (single character) %i Decimal, hexadecimal, octal integer %o Octal integer %s string (char array) %u Unsigned %lu Long unsigned %x Hexa-decimal integer %ld long integer %hd Short integer Left shift operation Right shift operation Operand Left shift operation Right shift operation 1st shift 2nd shift 3rd shift 1st shift 2nd shift 3rd shift a = 2 a3 = 0 b = 4 b3 = 0 #include int avg_result(int a[], int); int main(){ int a=0,a1=1,a2=2,a3=3,a4=4,a5=5,a6=6,a7=7,a8=8,a9=9, a10=10; printf("a= %dt && a> 3 = %dt a5>> 4 = %dt a5>> 5 = %dt ",a5, a5>> 1,a5>> 2,a5>> 3,a5>> 4,a5>> 5); printf("na6= %dt && a6>> 1 = %dt a6>> 2 = %dt a6>> 3 = %dt a6>> 4 = %dt a6>> 5 = %dt ",a6, a6>> 1,a6>> 2,a6>> 3,a6>> 4,a6>> 5); printf("na7= %dt && a7>> 1 = %dt a7>> 2 = %dt a7>> 3 = %dt a7>> 4 = %dt a7>> 5 = %dt ",a7, a7>> 1,a7>> 2,a7>> 3,a7>> 4,a7>> 5); printf("na8= %dt && a8>> 1 = %dt a8>> 2 = %dt a8>> 3 = %dt a8>> 4 = %dt a8>> 5 = %dt ",a8, a8>> 1,a8>> 2,a8>> 3,a8>> 4,a8>> 5); printf("na9= %dt && a9>> 1 = %dt a9>> 2 = %dt a9>> 3 = %dt a9>> 4 = %dt a9>> 5 = %dt ",a9, a9>> 1,a9>> 2,a9>> 3,a9>> 4,a9>> 5); printf("na10= %dt && a10>>1 = %d a10>>2 = %dt a10>> 3 = %dt a10>>4 = %dt a10>>5 = %dt ",a10, a10>> 1,a10>> 2,a10>> 3,a10>> 4,a10>> 5); }
  16. 16. a= 0 && a> 3 = 1 a10>>4 = 0 a10>>5 = 0 Cheat sheet #include Using angle bracket #includestdio.h Using quotation mark For Knowledge Prime numbers Those numbers Which we can divide by 2 numbers (1)by 1 & (2)by own number 2 3 5 7 11 13 17 19 23 29 31 37 39 41 43 47 51 http://www.crazyengineers.com/threads/c-c-difference-between- while-loop-and-for-loop.29738/ Definition of perfect number or What is perfect number? Perfect number is a positive number which sum of all positive divisors excluding that number is equal to that number. For example 6 is perfect number since divisor of 6 are 1, 2 and 3. Sum of its divisor is 1 + 2+ 3 =6 Note: 6 is the smallest perfect number.
  17. 17. Next perfect number is 28 since 1+ 2 + 4 + 7 + 14 = 28 Some more perfect numbers: 496, 8128 http://www.cquestions.com/2008/01/write-c-program-to-find-perfect-number.html Best Link http://www.cquestions.com/2010/10/c-interview-questions-and- answers.html http://www.inf.unideb.hu/kmitt/konvkmitt/programming _languages/book.xml.html http://www.cprogrammingexpert.com/C/Tutorial/simple_c_pro gram.aspx All in One #include int main() { int a=123456; float b=3.1416789; char c='f', c1='saifur'; printf("1 int=%d %0d %3d %15d %015d %0x15dn",a,a,a,a,a,a); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("1 long int=%ld %0ld %3ld %15ld %015ld %0x15ldn",a,a,a,a,a,a); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("1 short int=%hd %0hd %3hd %15hd %015hd %0x15hdn",a,a,a,a,a,a); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("2 float=%f %0f %3f %15.10f %15.0f %015.2f %f %0x15fn",b,b,b,b,b,b,(double)(int)b,b); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("3 double=%lf %0lf %3lf %15.10lf %15.0lf %015.2lf %0x15lfn",b,b,b,b,b,b,b); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("4 exponential notation=%e %0e %3e %15.10e %15.0e %015.2e %0x15en",b,b,b,b,b,b,b); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("5 long exponential notation.=%le %0le %3le %15.10le %15.0le %015.2le %0x15len",b,b,b,b,b,b,b); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("6 string=%s %0s %3s %15.10s %15.0s %15.2s %015.2sn","saifur","saifur","saifur","saifur","saifur","saifur","saifur","saifur"); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++n"); printf("nLateral stringn"); printf("%snn", "This is a string"); printf("7 char=%c %0c %3c %15.10c %15.0c %15.2c %015.2cn",c,c,c,c,c,c,c); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("7 char1=%c %0c %3c %15.10c %15.0c %15.2c %015.2cn",c1,c1,c1,c1,c1,c1,c1); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); printf("7 char=%c %0c %3c %15.10c %15.0c %15.2c %015.2cn",65,66,67,69,'65',"65",70); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++nn"); } 1 int=123456 123456 123456 123456 000000000123456 1e24015d +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 long int=123456 123456 123456 123456 000000000123456 1e24015ld +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 short int=-7616 -7616 -7616 -7616 -00000000007616 1e24015hd +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 float=3.141679 3.141679 3.141679 3.1416788101 3 000000000003.14 3.000000 8000000015f ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 double=3.141679 3.141679 3.141679 3.1416788101 3 000000000003.14 8000000015lf ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 exponential notation=3.141679e+000 3.141679e+000 3.141679e+000 3.1416788101e+000 3e+000 0000003.14e+000 8000000015e +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 long exponential notation.=3.141679e+000 3.141679e+000 3.141679e+000 3.1416788101e+000 3e+000 0000003.14e+000 8000000015le ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 6 string=saifur saifur saifur saifur sa 0000000000000sa ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Lateral string This is a string 7 char=f f f f f f 00000000000000f ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 7 char1=r r r r r r 00000000000000r ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 7 char=A B C E 5 00000000000000F ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  18. 18. Best Example #include int main(){ double a=35.65, b=36.548; printf("%lf %5lf %15.2lf %1.1lfn", a,b,a*b,a/b); printf("%le%15le%15.2le%1.1len",a,b,a*b,a/b); } output:: 1. 35.65000036.548000 1302.941.0 2. 3.565000e+001 3.654800e+001 1.30e+003 9.8e-001 Description::::: %e = Display a floating-pointvalue in exponential notation. %f = Display floating-point values. %lf = double (after point it can contain 6 charecters) %le = justlike double but after like double it has (e+ / e-) 1. 35.65000036.548000 1302.941.0 double a=35.65, b=36.548; printf("%lf %5lf %15.2lf %1.1lfn", a,b,a*b,a/b); a=35.65, b=36.548; when we write double a=35.65, b=36.548; then a=35.650000, b=36.548000 %lf = 35.650000(for a) %5lf = 36.548000 (for b) ( Total minimum 5 characters ) %15.2lf= 1302.94 (for a*b)(%15.2lf=itwants total minimum 15 characters & after point it wants 2 characters) (1302.94total7 characters butquestion asked for 15 characters. So we have extra 15-7=8 characters. This 8 characters wil be held before1302.94) %1.1lf=1.0 (for a/b) (%1.1lf=it wants total minimum 1 characters & after point it wants 1 characters) (1.0 total3 characters butquestion asked for 1 characters. So we don't have extra characters) 2. 3.565000e+001 3.654800e+001 1.30e+003 9.8e-001 double a=35.65, b=36.548; printf("%le%5le%15.2le%1.1len", a,b,a*b,a/b); a=35.65, b=36.548; when we write double a=35.65, b=36.548; then a=35.650000, b=36.548000 %le = 3.565000e+001 (fora) (for %e/ %le before floating point .) %15le = 3.654800e+001 (for b) ( Total minimum 15 characters but 3.654800e+001 has 13 characters so wehave15-13=2 characters. This 2 character will be helod before 3.654800e+001 as "blank space") %15.2le= 1.30e+003 (for a*b)(%15.2le=it wants total minimum 15 characters & after point it wants 2 characters. 15-9=6) %1.1le=9.8e-001 (for a/b) (%1.1lf=itwants total minimum 1 characters & after point it wants 1 characters) (9.8e-001 total3 characters but question asked for 1 characters. So we don't have extra characters) #include
  19. 19. int main(){ float a=65.678, b=65.456,c=65.345; printf("%lf %2.3lf %2.1lfn", a,a,a); printf("------------------------------------n"); printf("%lf %2.3lf %2.1lfn", b,b,b); printf("------------------------------------n"); printf("%lf %2.3lf %2.1lfn", c,c,c); printf("------------------------------------n"); }
  20. 20. http://www.cprogrammingexpert.com/C/example.aspx main() { } void main() { } int main() { return 0; } int main(void) { return 0; } void main(void) { return 0; } int main () { printf ("Welcome to C language"); return 0; } #include #include int main () { clrscr(); printf (Welcome to C language); return 0; } #include #include int main () { clrscr(); printf (Welcome to C language); getch(); retun 0; } String: strlen() #include #include int main() { char str[30]="C PROGRAMMING"; clrscr(); printf("nnstr : %snn",str); printf("nLength of the string, strlen(str) is %dn",strlen(str)); getch(); return 0; } String: strlwr() #include #include int main() { char str[30]="C PROGRAMMING"; clrscr(); printf("nnstr : %snn",str); printf("strlwr(str) : %sn",strlwr(str)); getch(); return 0; } String: strupr() #include #include int main() { char str[30]="C Programming"; clrscr(); printf("nnstr : %snn",str); printf("strupr(str) : %sn",strupr(str)); getch(); return 0; } String: strncat() #include #include int main() { char str1[25]="I LIKE "; char str2[15]="C PROGRAMMIG"; clrscr(); printf("nnstr1 : %stttstr2 : %snn",str1,str2); printf("nnstrcat(str1,str2) : %snn",strcat(str1,str2)); printf("nnstr1 : %sttstr2 : %snn",str1,str2); getch(); return 0; } String: strncat() #include #include int main() { char str1[25]="I LIKE "; char str2[13]="C PROGRAMMIG"; clrscr(); printf("nnBEFORE:nnstr1 : %stttstr2 : %snn",str1,str2); printf("nnstrncat(str1,str2,5) : %snn",strncat(str1,str2,5)); printf("nnAFTER:nnstr1 : %sttstr2 : %snn",str1,str2); getch(); return 0; } String: strcpy() #include #include int main() { char str1[15]="I LIKE "; char str2[15]="C PROGRAMMIG"; clrscr(); printf("nnBEFORE:nnstr1 : %stttstr2 : %snn",str1,str2); strcpy(str1,str2); printf("nnAFTER:nnstr1 : %sttstr2 : %snn",str1,str2); getch(); return 0; } String: strncpy() #include #include int main() { char str1[25]="I LIKE "; char str2[15]="C PROGRAMMIG"; clrscr(); printf("nnBEFORE:nnstr1 : %stttstr2 : %snn",str1,str2); strncpy(str1,str2,4); printf("nnAFTER:nnstr1 : %sttstr2 : %snn",str1,str2); getch(); return 0; } String: strcmp() #include #include int main() { char str1[]="I LIKE"; char str2[]="C Expert"; int i; clrscr(); i=strcmp(str1,str2); if(i==0) printf("nnstr1 and str2 are identical"); else if(i= 0.0: sqrt(2.25) = 1.5 Floor Function - floor(x): o Floor function floor(x) has only one parameter o floor(x) returns value of type double o floor(x) calculates largest whole number not greater than x: floor(48.79) = 48.0
  21. 25. C Reference Card (ANSI) 2(cheat sheet) ANSI Standard Libraries Mathematical Functions Arguments and returned values are double trig functions sin(x), cos(x), tan(x) inversetrig functions asin(x), acos(x), atan(x) arctan(y/z) atan2(y,x) hyperbolic trig functions sinh(x), cosh(x), tanh(x) exponentials & logs exp(x), log(x), log10(x) exponentials & logs (2 power) ldexp(x,n), frexp(x,&e) division & remainder modf(x,ip), fmod(x,y) powers pow(x,y), sqrt(x) rounding ceil(x), floor(x), fabs(x) Control flow if ( conditional ) { // do something } if ( conditional ){ // do something else{ // do something } if ( conditional ){ // do something Else if(another_condition){ // do something } else{ // do something } While(conditional) { //do something } placing "break;" inside a while loop breaks out of the loop placing "continue;" inside a while loop jumps to the start of the next loop for ( initialization; test; command ) { // do something } "break;" and "continue;" can be used within for loops as well with identical effects this is equivalent to: initialization; while( test ) { // do something command; } switch ( variable ) { case value1: // do something break; case value2: // do something else break; default: // do something by default break; } this is equivalent to: if ( variable == value 1 ){ // do something } else if ( variable = value2 ) { // do something } Else{ // do something by default }
  22. 26. libraries #include input and output functions #include string related functions #include memory allocation, rand, and other functions #include math functions #include time related functions Working With Numbers int i = 0; // convertfroma string int i = int.Parse("1"); // convertfroma string and dont throw exceptions if (int.TryParse("1", outi)) {} i++; // increment by one i--; // decrement by one i +=10; // add 10 i -=10; // subtract10 i *=10; // multiply by 10 i /=10; // divide by 10 i = checked(i*2) // check for overflow i = unchecked(i*2) // ignoreoverflow A C++ program is a collection of function, object, and type declarations. Every program must have a function int main() { ... } where the curly braces enclose a block, a sequence of declarations and statements ending in semicolons which are executed in order. A statement is an expression, block, or control statement that alters the order of execution, such as if, while, for, break, return. Some types (std::string), objects (std::cout), and functions are defined in header files, requiring the line #include before use. Items defined in the standard headers are in the namespace std. The std:: prefix may be dropped after the statement using namespace std; A program consists of a collection of functions (one of which must be int main() {...}) and type and object declarations. A function may contain declarations and statements. Statements have the following forms, where s is a statement, and t is a true/false expression. Integer types Bits Range bool 1 false (0) or true (1) signed char 8 'x80' to 'x7f' (-128 to 127) unsigned char 8 'x00' to 'XFF' (0 to 255) char 8 Usually signed short 16 -32768 to 32767 unsigned short 16 0u to 65535U int 32 Usually -2147483648 to 2147483647 unsigned int 32 Usually 0 to 4294967295U long 32-64 At least -2147483648l to 2147483647L unsigned long 32-64 0ul to at least 4294967295LU Floating point types Bits Range float 32 -1.7e38f to 1.7E38F, 6 significant digits double 64 -1.8e308 to 1.8E308, 14 significant digits long double 64-80 At least double Functions A function has a list of parameter declarations, a return type, and a block of statements. Execution must end with a return statement returning an expression that can be converted to the return type, unless void, in which case there is an implied return; at the end. Arguments passed to a function must match the parameters or allow implicit conversion (such as int to double). Functions must be defined before use, or have a matching declaration that replaces the block with a semicolon and may optionally omit parameter names. Functions are always global (not defined in other functions). void f(double x, double); // Declaration double g() { // Definition return 3; // Implied conversion to double (3.0) } Data input or output getchar() single character input character variable = getchar(); char c; .. c = getchar(); putchar() single character output Putchar(character variable) Char c; .. Putchar(c); scanf() printf() Gets Puts
  23. 27. For making logical expression we use the four relational operators() & two equality operators() that are either true or false Equality operators ==, != Relational operators = ALL STRING METHODS Functions[edit] Byte string Wide string Description[note 1] String manipulation strcpy wcscpy copies one string to another strncpy wcsncpy writes exactly n bytes/wchar_t, copying from source or adding nulls strcat wcscat appends one string to another strncat wcsncat appends no more than n bytes/wchar_t from one string to another strxfrm wcsxfrm transforms a string according to the current locale String examination strlen wcslen returns the length of the string strcmp wcscmp compares two strings strncmp wcsncmp compares a specific number of bytes/wchar_t in two strings strcoll wcscoll compares two strings according to the current locale strchr wcschr finds the first occurrence of a byte/wchar_t in a string strrchr wcsrchr finds the last occurrence of a byte/wchar_t in a string strspn wcsspn finds in a string the first occurrence of a byte/wchar_t not in a set strcspn wcscspn finds in a string the last occurrence of a byte/wchar_t not in a set strpbrk wcspbrk finds in a string the first occurrence of a byte/wchar_t in a set strstr wcsstr finds the first occurrence of a substring in a string strtok wcstok splits string into tokens Miscellaneous strerror N/A returns a string containing a message derived from an error code Memory manipulation memset wmemset fills a buffer with a repeated byte/wchar_t memcpy wmemcpy copies one buffer to another memmove wmemmove copies one buffer to another, possibly overlapping, buffer
  24. 28. memcmp wmemcmp compares two buffers memchr wmemchr finds the first occurrence of a byte/wchar_t in a buffer Multibyte functions[edit] Name Description mblen returns the number of bytes in the next multibyte character mbtowc converts the next multibyte character to a wide character wctomb converts a wide character to its multibyte representation mbstowcs converts a multibyte string to a wide string wcstombs converts a wide string to a multibyte string btowc convert a single-byte character to wide character, if possible wctob convert a wide character to a single-byte character, if possible mbsinit checks if a state object represents initial state mbrlen returns the number of bytes in the next multibyte character, given state mbrtowc converts the next multibyte character to a wide character, given state wcrtomb converts a wide character to its multibyte representation, given state mbsrtowcs converts a multibyte string to a wide string, given state wcsrtombs converts a wide string to a multibyte string, given state "state" is used by encodings that rely on history such as shift states. This is not needed by UTF-8 or UTF-32. UTF-16 uses them to keep track of surrogate pairs and to hide the fact that it actually is a multi-word encoding. Numeric conversions[edit] The C standard library contains several functions for numeric conversions. The functions that deal with byte strings are defined in the stdlib.h header (cstdlib header in C++). The functions that deal with wide strings are defined in the wchar.h header (cwchar header in C++). Note that the strtoxxx functions are not const-correct, since they accept a const string pointer and return a non-const pointer within the string. Byte string Wide string Description[note 1] atof N/A converts a string to a floating-point value atoi atol atoll N/A converts a string to an integer (C99) strtof(C99) strtod strtold(C99) wcstof(C99) wcstod wcstold(C99) converts a string to a floating-point value strtol strtoll wcstol wcstoll converts a string to a signed integer strtoul strtoull wcstoul wcstoull converts a string to an unsigned integer
  25. 29. http://www.tutorialspoint.com/ C++ Operators: An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provides following type of operators: Arithmetic Operators ( +, -, , *,++, -- ) Relational Operators (==, !=, >.=,