SlideShare ist ein Scribd-Unternehmen logo
1 von 129
Author: Md. Saifur Rahman
Education: 4th semester at CSE Department in Southeast University
Banani, Dhaka, Bangladesh.
Md. Saifur Rahman C Programming Language
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<stdio.h>
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 X’s 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.
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 & it’s values.
Variable’s 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.
string integer floating point
saifur 67 67.0
A+ 4 4.0
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
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
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
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 mark
 Backslash
? Literal question mark
0 Null
 ooo 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
1
abs() Absolute value
Returns the absolute value of parameter n ( /n/ ).
In C++, this function is also overloaded in header <cmath> for floating-
point types (see cmath abs), in header<complex> for complex numbers
(see complex abs), and in header <valarray> 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 <stdio.h> /* printf */
#include <stdlib.h> /* 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 <stdio.h> /* printf */
#include <math.h> /* 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 <stdio.h> /* printf */
#include <math.h> /* 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 <tgmath.h> 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 <stdio.h> /* printf */
#include <math.h> /* 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 <stdio.h> /* printf */
#include <math.h> /* 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 (<cmath>) 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 <complex> and <valarray> (see complex
sqrt and valarray sqrt).
1
2
3
4
5
6
7
8
9
10
11
12
/* sqrt example */
#include <stdio.h> /* printf */
#include <math.h> /* 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 <stdio.h> /* printf */
#include <math.h> /* 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:
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 <stdio.h> /* printf */
#include <math.h> /* 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 (<cmath>) for the integral types:
These overloads effectively cast x to a double before calculations.
This function is also overloaded in <complex> and <valarray> (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 <stdio.h> /* printf */
#include <math.h> /* 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 <cstdlib>.
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 <random>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 <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* 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 (iSecret<iGuess) puts ("The secret number is lower");
else if (iSecret>iGuess) 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 <ctime>). 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 <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* 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
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.
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
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 ,
printf scanf
I/O of floats in C
#include <stdio.h>
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)
%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 a<<1 = 4 a<<2 = 8 a<<3 = 16 a>>1 = 1 a>>2 = 0 a>>3 = 0
b = 4 b<<1 = 8 b<<2 = 16 b<<3 = 32 b>>1 = 2 b>>2 = 1 b>>3 = 0
#include <stdio.h>
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<< 1 = %dt a<< 2 = %dt a<< 3 = %dt a<< 4 = %dt a<< 5 = %dt ",a, a<<1,a<<2,a<<3,a<<4,a<<5);
printf("na1= %dt && a1<<1 = %dt a1<<2 = %dt a1<<3 = %dt a1<<4 = %dt a1<<5 = %dt ",a1, a1<<1,a1<<2,a1<<3,a1<<4,a1<<5);
printf("na2= %dt && a2<<1 = %dt a2<<2 = %dt a2<<3 = %dt a2<<4 = %dt a2<<5 = %dt ",a2, a2<<1,a2<<2,a2<<3,a2<<4,a2<<5);
printf("na3= %dt && a3<<1 = %dt a3<<2 = %dt a3<<3 = %dt a3<<4 = %dt a3<<5 = %dt ",a3, a3<<1,a3<<2,a3<<3,a3<<4,a3<<5);
printf("na4= %dt && a4<<1 = %dt a4<<2 = %dt a4<<3 = %dt a4<<4 = %dt a4<<5 = %dt ",a4, a4<<1,a4<<2,a4<<3,a4<<4,a4<<5);
printf("na5= %dt && a5<<1 = %dt a5<<2 = %dt a5<<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);
}
#include <stdio.h>
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>> 1 = %dt a>> 2 = %dt a>> 3 = %dt a>> 4 = %dt a>> 5 = %dt ",a, a>> 1,a>> 2,a>> 3,a>> 4,a>> 5);
printf("na1= %dt && a1>> 1 = %dt a1>> 2 = %dt a1>> 3 = %dt a1>> 4 = %dt a1>> 5 = %dt ",a1, a1>> 1,a1>> 2,a1>> 3,a1>> 4,a1>> 5);
printf("na2= %dt && a2>> 1 = %dt a2>> 2 = %dt a2>> 3 = %dt a2>> 4 = %dt a2>> 5 = %dt ",a2, a2>> 1,a2>> 2,a2>> 3,a2>> 4,a2>> 5);
printf("na3= %dt && a3>> 1 = %dt a3>> 2 = %dt a3>> 3 = %dt a3>> 4 = %dt a3>> 5 = %dt ",a3, a3>> 1,a3>> 2,a3>> 3,a3>> 4,a3>> 5);
printf("na4= %dt && a4>> 1 = %dt a4>> 2 = %dt a4>> 3 = %dt a4>> 4 = %dt a4>> 5 = %dt ",a4, a4>> 1,a4>> 2,a4>> 3,a4>> 4,a4>> 5);
printf("na5= %dt && a5>> 1 = %dt a5>> 2 = %dt a5>> 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);
}
a= 0 && a<< 1 = 0 a<< 2 = 0 a<< 3 = 0 a<< 4 = 0 a<< 5 = 0
a1= 1 && a1<<1 = 2 a1<<2 = 4 a1<<3 = 8 a1<<4 = 16 a1<<5 = 32
a2= 2 && a2<<1 = 4 a2<<2 = 8 a2<<3 = 16 a2<<4 = 32 a2<<5 = 64
a3= 3 && a3<<1 = 6 a3<<2 = 12 a3<<3 = 24 a3<<4 = 48 a3<<5 = 96
a4= 4 && a4<<1 = 8 a4<<2 = 16 a4<<3 = 32 a4<<4 = 64 a4<<5 = 128
a5= 5 && a5<<1 = 10 a5<<2 = 20 a5<<3 = 40 a5<<4 = 80 a5<<5 = 160
a6= 6 && a6<<1 = 12 a6<<2 = 24 a6<<3 = 48 a6<<4 = 96 a6<<5 = 192
a7= 7 && a7<<1 = 14 a7<<2 = 28 a7<<3 = 56 a7<<4 = 112 a7<<5 = 224
a8= 8 && a8<<1 = 16 a8<<2 = 32 a8<<3 = 64 a8<<4 = 128 a8<<5 = 256
a9= 9 && a9<<1 = 18 a9<<2 = 36 a9<<3 = 72 a9<<4 = 144 a9<<5 = 288
a10=10 && a10<<1= 20 a10<<2= 40 a10<<3= 80 a10<<4= 160 a10<<5= 320
a= 0 && a>> 1 = 0 a>> 2 = 0 a>> 3 = 0 a>> 4 = 0 a>> 5 = 0
a1= 1 && a1>> 1 = 0 a1>> 2 = 0 a1>> 3 = 0 a1>> 4 = 0 a1>> 5 = 0
a2= 2 && a2>> 1 = 1 a2>> 2 = 0 a2>> 3 = 0 a2>> 4 = 0 a2>> 5 = 0
a3= 3 && a3>> 1 = 1 a3>> 2 = 0 a3>> 3 = 0 a3>> 4 = 0 a3>> 5 = 0
a4= 4 && a4>> 1 = 2 a4>> 2 = 1 a4>> 3 = 0 a4>> 4 = 0 a4>> 5 = 0
a5= 5 && a5>> 1 = 2 a5>> 2 = 1 a5>> 3 = 0 a5>> 4 = 0 a5>> 5 = 0
a6= 6 && a6>> 1 = 3 a6>> 2 = 1 a6>> 3 = 0 a6>> 4 = 0 a6>> 5 = 0
a7= 7 && a7>> 1 = 3 a7>> 2 = 1 a7>> 3 = 0 a7>> 4 = 0 a7>> 5 = 0
a8= 8 && a8>> 1 = 4 a8>> 2 = 2 a8>> 3 = 1 a8>> 4 = 0 a8>> 5 = 0
a9= 9 && a9>> 1 = 4 a9>> 2 = 2 a9>> 3 = 1 a9>> 4 = 0 a9>> 5 = 0
a10= 10 && a10>>1 = 5 a10>>2 = 2 a10>> 3 = 1 a10>>4 = 0 a10>>5 = 0
Cheat sheet
#include<stdio.h>
Using angle bracket
#include”stdio.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.
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<stdio.h>
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
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Best Example
#include<stdio.h>
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<stdio.h>
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");
}
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 <stdio.h>
#include <conio.h>
int main ()
{
clrscr();
printf (“Welcome to C language”);
return 0;
}
#include <stdio.h>
#include <conio.h>
int main ()
{
clrscr();
printf (“Welcome to C language”);
getch();
retun 0;
}
String: strlen()
#include <stdio.h>
#include <conio.h>
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 <stdio.h>
#include <conio.h>
int main()
{
char str[30]="C PROGRAMMING";
clrscr();
printf("nnstr : %snn",str);
printf("strlwr(str) : %sn",strlwr(str));
getch();
return 0;
}
String: strupr()
#include <stdio.h>
#include <conio.h>
int main()
{
char str[30]="C Programming";
clrscr();
printf("nnstr : %snn",str);
printf("strupr(str) : %sn",strupr(str));
getch();
return 0;
}
String: strncat()
#include <stdio.h>
#include <conio.h>
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 <stdio.h>
#include <conio.h>
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 <stdio.h>
#include <conio.h>
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 <stdio.h>
#include <conio.h>
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 <stdio.h>
#include <conio.h>
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)
printf("nnstr1< str2");
else
printf("nnstr1< str2");
getch();
return 0;
}
2nd
Term
Conversion characters
5.4 Printing Integers
 Integer is a whole number, such as 880 or –456, that contains no decimal point.
 Table 5.1 is a summary of an integer conversion specifier.
Conversion
specifier
Description
d Display a signed decimal integer
i Display a signed decimal integer. (Note: The i and d specifiers are different when used with scanf().)
o Display an unsigned octal integer.
u Display an unsigned decimal integer.
x or X
Display an unsigned decimal integer. x causes the digit 0-9 and the letters A-F to be displayed, and xcauses
the digits 0-9 and a–f to be displayed.
h or l (letter l) Place before any integer conversion specifier to indicate that a short or long integer is displayed respectively.
Table 5.1: Integer conversion specifiers
 Let explore through a program example.
// using the integer conversion specifiers
#include <stdio.h>
int main()
{
printf("Various format for integer printingn");
printf("-------------------------------------n");
printf("%dn", 455);
printf("%in", 455); //i same as d in printf()
printf("%dn", +455);
printf("%dn", -455);
printf("%hdn", 32000);
printf("%ldn", 2000000000L);
printf("%on", 455);
printf("%un", 455);
printf("%un", -455);
//-455 is read by %u and converted to the unsigned
//value 4294966841 by 4 bytes integer
printf("%xn", 455);
printf("%Xn", 455);
return 0;
}
Output:
5.5 Printing Floating-point Number
 Contains the decimal point such as 35.5 or 7456.945.
 Table 5.2 summarizes the floating-point conversion specifiers.
Conversion
specifier
Description
e or E Display a floating-point value in exponential notation.
f Display floating-point values.
g or G Display a floating-point value in either the floating-point form f or the exponential form e ( or E)
l
Place before any floating-point conversion specifier to indicate that a long double floating-point value is
displayed.
Table 5.2: Floating-point conversion specifiers
 Exponential notation is the computer equivalent of scientific notation used in mathematics. For example, 150.2352 is represented in scientific notation as:
1.502352 x 102
 And is represented in exponential notation as:
1.502352E+02 by computer
 So, 150.2352 = 1.502352 x 102 = 1.502352E+02
 E stand for exponent.
 e, E and f will output with 6 digits of precision to the right of the decimal point by default.
 Let try a program example.
// printing floating-point numbers with floating-point conversion specifiers
#include <stdio.h>
void main()
{
printf("Printing floating-point numbers withn");
printf("floating-point conversion specifiers.n");
printf("Compare the output with source codenn");
printf("1. %en", 1234567.89);
printf("2. %en", +1234567.89);
printf("3. %en", -1234567.89);
printf("4. %En", 1234567.89);
printf("5. %fn", 1234567.89);
printf("6. %gn", 1234567.89);
printf("7. %Gn", 1234567.89);
}
Output:
5.6 Printing Strings And Characters
 c and s conversion specifiers are used to print individual characters and strings respectively.
 Conversion specifier c requires a char argument and s requires a pointer to char as an argument.
 s causes characters to be printed until a terminating NULL (‘0’) character is encountered.
 A program example.
// printing strings and characters
#include <stdio.h>
int main()
{
char character = 'A';
char string[ ] = "This is a string";
char *stringPtr = "This is also a string";
printf("---------------------------------n");
printf("---Character and String format---n");
printf("---------------------------------nn");
printf("%c <--This one is charactern", character);
printf("nLateral stringn");
printf("%sn", "This is a string");
printf("nUsing array name, the pointer to the first array's elementn");
printf("%sn", string);
printf("nUsing pointer, pointing to the first character of stringn");
printf("%sn", stringPtr);
return 0;
}
5.7 Other Conversion Specifiers
 p, n and % are summarized in table 5.3 followed by the program example.
Conversion
specifier
Description
p Display a pointer value (memory address) in an implementation defined manner.
n
Store the number of characters already output in the current printf() statement. A
pointer to an integer is supplied as the corresponding argument. Nothing is displayed.
% Display the percent character.
Table 5.3: Other conversion specifiers
// using the p, n, and % conversion specifiers
#include <stdio.h>
int main()
{
// pointer variable
int *ptr;
int x = 12345, y;
// assigning address of variable x to variable ptr
ptr = &x;
printf("nUsing the p, n, and %% conversion specifiers.n");
printf("Compare the output with the source coden");
printf("-----------------------------------------------nn");
printf("The value of pointer ptr is %pn", ptr);
printf("The address of variable x is %pnn", &x);
printf("Total characters printed on this line is:%n", &y);
printf(" %dnn", y);
y = printf("This line has 28 charactersn");
printf("%d characters were printednn", y);
printf("Printing a %% in a format control stringn");
return 0;
}
5.8 Printing With Field Widths And Precisions
 A field width determines the exact size of a field in which data is printed.
 If the field width is larger then the data being printed, the data will normally be right-justified within that field.
 An integer representing the field width is inserted between the percent sign (%) and the conversion specifier in the conversion specification.
 Function printf() also provides the ability to specify the precision with which data is printed.
 Precision has different meanings for different data types.
 The following is a program example.
// printing integers right-justified
#include <stdio.h>
int main()
{
printf(" Printing integers right-justified.n");
printf("Compare the output with the source coden");
printf("---------------------------------------nn");
printf("%4dn", 1);
printf("%4dn", 12);
printf("%4dn", 123);
printf("%4dn", 1234);
printf("%4dnn", 12345);
printf("%4dn", -1);
printf("%4dn", -12);
printf("%4dn", -123);
printf("%4dn", -1234);
printf("%4dn", -12345);
return 0;
}
Output:
 Another example:
// using precision while printing integers, floating-point numbers and strings
#include <stdio.h>
int main()
{
int i = 873;
float f = 123.94536;
chars[ ] = "Happy Birthday";
printf("Using precision while printing integers,n");
printf(" floating-point numbers, and strings.n");
printf("Compare the output with the source coden");
printf("----------------------------------------nn");
printf("Using precision for integersn");
printf("t%.4dnt%.9dnn", i, i);
printf("Using precision for floating-point numbersn");
printf("t%.3fnt%.3ent%.3gnn", f, f, f);
printf("Using precision for stringsn");
printf("t%.11sn", s);
return 0;
}
Output:
 By using asterisk (*), it is also can be like this:
printf("%*.*f", 7, 2, 98.736)
 This statement uses 7 for the field width, 2 for the precision and will output the value 98.74 right-justified.
5.9 Using Flags In The printf() Format Control String
 Flags used to supplement its output formatting capabilities.
 Five flags are available to be used in format control string as shown in table 5.4 then followed by program examples.
Flag Description
- (minus sign) Left-justify the output within the specified field
+ (plus sign) Display a plus sign preceding positive values and a minus sign preceding negative values.
space Print a space before a positive value not printed with the + flag.
#
Prefix 0 to the output value when used with the octal conversion
specifier o. Prefix 0x or 0X to the output value when used with the hexadecimal conversion
specifiers x or X. Force a decimal points for a floating-point number printed with e, E, f, g,
or G that does not contain a fractional part. (Normally the decimal point is only printed if a
digit follows it). For g and Gspecifiers, trailing zeros are not eliminated.
0 (zero) Pad a field with leading zeros.
Table 5.4: Format control string flags
// right justifying and left justifying values
#include <stdio.h>
int main()
{
printf("Right justifying and left justifying values.n");
printf(" Compare the output with the source code.n");
printf("--------------------------------------------nn");
printf("%10s%10d%10c%10fnn", "hello", 7, 'a', 1.23);
printf("%-10s%-10d%-10c%-10fn", "hello", 7, 'a', 1.23);
return 0;
}
Output:
 More program example:
// printing numbers with and without the + flag
#include <stdio.h>
int main()
{
printf("Printing numbers with and without the + flag.n");
printf(" Compare the output with the source coden");
printf("---------------------------------------------nn");
printf("%dn%dn", 786, -786);
printf("%+dn%+dn", 786, -786);
return 0;
}
Output:
 Another example:
// printing a space before signed values not preceded by + or -
#include <stdio.h>
int main()
{
printf("Printing a space before signed valuesn");
printf(" not preceded by + or -nn");
printf("--------------------------------------nn");
printf("% dn% dn", 877, -877);
return 0;
}
Output:
 More program example:
// o, x, X, and any floating-point specifier
#include <stdio.h >
int main()
{
int c = 1427;
float p = 1427.0;
printf("o, x, X, and any floating-point specifiersn");
printf("Compare the output with the source coden");
printf("-----------------------------------------nn");
printf("%#on", c);
printf("%#xn", c);
printf("%#Xn", c);
printf("n%#gn", p);
printf("%#Gn", p);
return 0;
}
Output:
 Program example again.
// printing with the 0 (zero) flag fills in leading zeros
#include <stdio.h>
int main()
{
printf("Printing with the 0 (zero) flag fills in leading zerosn");
printf(" Compare the output with the source coden");
printf("-------------------------------------------------------nn");
printf("%+09dn", 762);
printf("%09d", 762);
printf("n");
return 0;
}
Pr ed ef i n ed F u n c ti o n s
Using predefined functions:
 C++ Standard Library contains many predefined functions to perform various operations
 Predefined functions are organized into separate libraries
 I/O functions are in iostream header
 Math functions are in cmath header
 Some predefined C++ mathematical functions:
o pow(x,y)
o sqrt(x)
o floor(x)
 Power Function - pow(x,y):
o Power function pow(x,y) has two parameters
o pow(x,y) returns value of type double
o pow(x,y) calculates x to the power of y: pow(2,3) = 8.0
o x and y called parameters (or arguments) of function pow
 Square Root Function - sqrt(x):
o Square root function sqrt(x) has only one parameter
o sqrt(x) returns value of type double
o sqrt(x) calculates non-negative square root of x, for x >= 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
C Reference Card (ANSI) 2(cheat sheet)
ANSI Standard Libraries
<assert.h> <ctype.h> <errno.h> <float.h> <limits.h>
<locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h>
<stddef.h> <stdio.h> <stdlib.h> <string.h> <time.h>
Mathematical Functions <math.h>
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
}
libraries
#include <stdio.h> input and output functions
#include <string.h> string related functions
#include <stdlib.h> memory allocation, rand, and other functions
#include <math.h> math functions
#include <time.h> time related functions
Working With Numbers
int i = 0;
// convertfroma string int i = int.Parse("1");
// convertfroma string and don’t 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 <header> 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
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
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
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 (==, !=, >.<, >=, <=)
• Logical Operators (&&, ||, ! )
• Bitwise Operators (& |, ^
, ~, <<, >>)
• Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^
=, |=)
• Misc Operators ( sizeof, & cast, comma, conditional etc.)
Loop Type C++ Decision Making
While loop If statement
Do-while loop If…else statement
For loop switch statement
Nested loop Nested if statement
Nested switch statement
A C++ function definition consists of a function header and a function body. Here are all the parts of a function:
 Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that
is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that define what the function does.
statements
One way Return way
Statements
A statement is a building block of a program
Conditional control statements(if, if else, ladder if, switch.. case ) Iterative control statements ( for, while, do .. while) Unconditional control statements (goto, continue, break)
flow control/ control statements
Branching Looping
Branching is deciding what actions to take looping is deciding how many times to take a certain action
Difference between three loops
If you use "continue" in a "for" loop, it will still increment the variable. But if you use continue inside a "while" loop with counter, then it will turn into an infinite loop.
While Do-while for
a while loop repeats as long as a certain condition is true a for loop repeats for a predefined number of times
http://www.programiz.com/c-programming/c-do-while-loops http://www.programiz.com/c-programming/c-do-while-loops
loop in c programming
http://www.programiz.com/c-programming/c-for-loop
for (Start value; continue or end condition; increase value)
statement;
prefix incrementing (++i) or postfix incrementing (i++)
Looping Classification(i++, i=i+1, ++i, i+=1)
While loop Do-while loop For loop Result
while(){} do{}
while();
for(){}
http://www.c4learn.com/c-programming/c-while-loop/ http://www.c4learn.com/c-programming/c-do-while-loop/ http://www.c4learn.com/c-programming/c-for-loop-types/
While Loop Syntax :
initialization;
while(condition)
{
----------
----------
----------
----------
----------
Do-While Loop Syntax :
initialization;
do
{
--------------
--------------
--------------
--------------
incrementation;
Understanding Looping Statement :
Whenever we need to execute certain action multiple times, we need to wrap
programming statement in the loop body. Take an example we are computing the
sum of 2 numbers 5 times then we need to write code in the loop body. Consider the
following trailer -
for(i=0; i<5; i++)
{
printf("nEnter two Numbers : ");
scanf("%d %d",num1,num2);
ans = num1 + num2;
------
incrementation;
}
Note :
 For Single Line of Code – Opening and Closing braces are not needed.
 while(1) is used for Infinite Loop
 Initialization , Incrementation and Condition steps are on different Line.
 While Loop is also Entry Controlled Loop.[i.e conditions are checked if found
true then and then only code is executed ]
}while(condition);
Note :
 It is Exit Controlled Loop.
 Initialization , Incrementation and Condition steps are on different Line.
 It is also called Bottom Tested [i.e Condition is tested at bottom and Body has
to execute at least once ]
printf("nAddition of 2 Numbers is %d");
}
Syntax of the For Loop :
for(initial expression; test expression; update expression)
{
body of loop;
}
We will get better idea after looking at above for loop flowchart.
Flowchart of For Loop :
Explanation of For Loop :
1. Firstly the for loop executes the initialize statement in which the subscript
variable will be initialized with the initial value.
2. After the initialize statement the condition part of the loop will be executed if
the condition becomes true then body of the loop will be executed otherwise the
loop will be terminated
3. If the loop condition becomes true then body of the loop will be executed. After
the execution of the for loop body the control goes to the third part of the loop
statement i.e Expression Updation
4. After updating subscript variable control again goes to execute condition
statement.
For Loop : Dry Run
Consider the following image then -
Sequence of the execution will be as below -
Seq. No Statement Flow Explanation
01 Flow No 1 will be executed i = 0
02 Flow No 2 will be executed Condition Checking
03 Flow No 3 will be executed True Condition
04 Flow No 4 will be executed -
05 Flow No 5 will be executed i = 1
06 Flow No 3 will be executed True Condition
07 Flow No 4 will be executed -
08 Flow No 5 will be executed i = 2
09 Flow No 3 will be executed True Condition
10 Flow No 4 will be executed -
11 Flow No 5 will be executed i = 3
12 Flow No 3 will be executed True Condition
13 Flow No 4 will be executed -
14 Flow No 5 will be executed i = 4
15 Flow No 3 will be executed True Condition
16 Flow No 4 will be executed -
17 Flow No 5 will be executed i = 5
18 Flow No 3 will be executed False Condition
Note :
1. For Single Line of Code – Opening and Closing braces are not needed.
2. There can Exist For Loop without body.
3. Initialization , Incrementation and Condition steps are on same Line.
4. Like While loop , For Loop is Entry Controlled Loop.[i.e conditions are
checked if found true then and then only code is executed ]
Different Ways of Infinite While Loop in C
We can use While loop for looping purpose. We can use infinite while loop in C to
iterate loop for infinite times. We can Even use Infinite while loop for operation in
which we cannot decide how many iteration does it take at compile time.
Way 1 : Semicolon at the end of While
#include<stdio.h>
void main()
{
int num=300;
while(num>255); //Note it Carefully
printf("Hello");
}
Output :
It won't Print anything
Explanation of Above Infinite Loop :
1. In the above program , Condition is specified in the While Loop
2. Semicolon at the end of while indicated while without body.
3. In the program variable num doesn’t get incremented , condition remains true
forever.
4. As Above program does not have Loop body , It won’t print anything
Way 2 : Non-Zero Number as a Parameter
#include<stdio.h>
void main()
{
while(1)
printf("Hello");
}
Output :
Infinite Time "Hello" word
How ?
1. Note : We can specify any Non-Zero Positive Number inside while
2. Non Zero is specified in the While Loop means Loop will have always TRUE
condition specified inside.
3. As condition inside loop doesn’t get changed ,condition inside while remains
true forever.
Way 3 : Subscript Variable Remains the same
#include<stdio.h>
void main()
Different Ways of Using For Loop in C Programming
In order to do certain actions multiple times , we use loop control statements.
For loop can be implemented in different verities of using for loop -
1. Single Statement inside For Loop
2. Multiple Statements inside For Loop
3. No Statement inside For Loop
4. Semicolon at the end of For Loop
5. Multiple Initialization Statement inside For
6. Missing Initialization in For Loop
7. Missing Increment/Decrement Statement
8. Infinite For Loop
9. Condition with no Conditional Operator.
Way 1 : Single Statement inside For Loop
for(i=0;i<5;i++)
printf("Hello");
1. Above code snippet will print Hello word 5 times.
2. We have single statement inside for loop body.
3. No need to wrap printf inside opening and closing curly block.
4. Curly Block is Optional.
Way 2 : Multiple Statements inside For Loop
for(i=0;i<5;i++)
{
printf("Statement 1");
printf("Statement 2");
printf("Statement 3");
if(condition)
{
int num=20;
while(num>10)
{
printf("Hello");
printf(" C ");
}
}
Output :
Infinite Time "Hello C" word
How ?
1. Condition is specified in while Loop ,but Terminating Condition is not
specified
2. Also Subscript Variable [Variable used to Repeat action] is also not either
incremented or decremented
3. so while remains true forever.
Way 4 : Character as a Parameter in While Loop
#include<stdio.h>
void main()
{
while('A')
printf("Hello");
}
Output :
Infinite Time "Hello" word
How ?
1. Character is Represented in integer in the form of ASCII internally.
2. Any Character is Converted into Non-zero Integer ASCII value
3. Any Non-zero ASCII value is TRUE condition , that is why Loop executes
forever
How to Break Infinite While Loop :
Whenever you decide to use infinite while loop while writing code , you must include
terminating or ending condition in a while loop to ensure that your code will be
terminated at some moment of time.
while(1) {
ch = fgetc(fp);
printf("%c",ch);
fp++;
if(ch == 'EOF')
break;
}
In the Above program we cannot decide , size of file while writing program so we
decided to go with infinite while loop. Our main purpose is to read file so we have
provided breaking condition inside loop which will takes control out of loop.
{
--------
--------
}
}
If we have block of code that is to be executed multiple times then we can use curly
braces to wrap multiple statement in for loop.
Way 3 : No Statement inside For Loop
for(i=0;i<5;i++)
{
}
this is bodyless for loop. It is used to increment value of “i”.This verity of for loop is
not used generally.
At the end of above for loop value of i will be 5.
Way 4 : Semicolon at the end of For Loop
for(i=0;i<5;i++);
1. Generally beginners thought that , we will get compile error if we write
semicolon at the end of for loop.
2. This is perfectly legal statement in C Programming.
3. This statement is similar to bodyless for loop. (Way 3)
Way 5 : Multiple Initialization Statement inside For
for(i=0,j=0;i<5;i++)
{
statement1;
statement2;
statement3;
}
Multiple initialization statements must be seperated by Comma in for loop.
Way 6 : Missing Increment/Decrement Statement
for(i=0;i<5;)
{
statement1;
statement2;
statement3;
i++;
}
however we have to explicitly alter the value i in the loop body.
Way 7 : Missing Initialization in For Loop
i = 0;
for(;i<5;i++)
{
statement1;
statement2;
statement3;
}
we have to set value of ‘i’ before entering in the loop otherwise it will take garbage
value of ‘i’.
Way 8 : Infinite For Loop
i = 0;
for(;;)
{
statement1;
statement2;
statement3;
if(breaking condition)
break;
i++;
}
Infinite for loop must have breaking condition in order to break for loop. otherwise it
will cause overflow of stack.
Summary of Different Ways of Implementing For Loop
Form Comment
for ( i=0 ; i < 10 ; i++ )
Statement1;
Single Statement
for ( i=0 ;i <10; i++)
{
Statement1;
Statement2;
Statement3;
}
Multiple Statements within for
for ( i=0 ; i < 10;i++) ; For Loop with no Body ( Carefully Look at the
Semicolon )
for
(i=0,j=0;i<100;i++,j++)
Statement1;
Multiple initialization & Multiple
Update Statements Separated by Comma
for ( ; i<10 ; i++) Initialization not used
for ( ; i<10 ; ) Initialization & Update not used
for ( ; ; ) Infinite Loop,Never Terminates
#include<stdio.h>
int main(void){
int a=2;
while(a<21){
printf("%dn",a);
a=a+1;
}
}
#include<stdio.h>
int main(void){
int a=2;
do{
printf("%dn",a);
a=a+1;
}
while(a<21);
}
#include<stdio.h>
int main(void){
int a;
for(a=2;a<21;a++){
printf("%dn",a);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<stdio.h>
int main(void){
int a=9;
while(a>0){
printf("%dn",a);
a--;
}
}
#include<stdio.h>
int main(void){
int a=9;
do{
printf("%dn",a);
a--;
}
while(a>0);
}
#include<stdio.h>
int main(void){
int a;
for(a=9;a>0;a--){
printf("%dn",a);
}
}
9
8
7
6
5
4
3
2
1
#include<stdio.h>
int main(void){
int a=0;
while(a<12){
printf("%dn",a);
a=a+2;
}
}
#include<stdio.h>
int main(void){
int a=0;
do{
printf("%dn",a);
a=a+2;
}
while(a<12);
}
#include<stdio.h>
int main(void){
int a;
for(a=0;a<12;a=a+2){
printf("%dn",a);
}
}
0
2
4
6
8
10
#include<stdio.h>
int main(void){
int a=12;
while(a>0){
printf("%dn",a);
a=a-2;
}
}
#include<stdio.h>
int main(void){
int a=12;
do{
printf("%dn",a);
a=a-2;
}
while(a>0);
}
#include<stdio.h>
int main(void){
int a;
for(a=12;a>0;a=a-2){
printf("%dn",a);
}
}
12
10
8
6
4
2
#include<stdio.h>
int main(void){
int a;
for(a=1;a<=15;a++){
printf("%dn", (a%2)*(-4)+2);
}
}
-2
2
-2
2
-2
2
-2
2
-2
2
-2
2
-2
2
-2
#include<stdio.h>
int main(void){
#include<stdio.h>
int main(void){
#include<stdio.h>
int main(void){
1
-1
1
int a=0;
while(a<10){
printf("%dn", (a%2)*(-2)+1);
a++;
}
}
int a=0;
do{
printf("%dn", (a%2)*(-2)+1);
a++;
}
while(a<10);
}
int a;
for(a=0;a<10;a++){
printf("%dn", (a%2)*(-2)+1);
}
}
-1
1
-1
1
-1
1
-1
#include<stdio.h>
int main(void){
int a=0;
while(a<10){
printf("%dn", (a%2)*6+4);
a++;
}
}
#include<stdio.h>
int main(void){
int a=0;
do{
printf("%dn", (a%2)*6+4);
a++;
}
while(a<10);
}
#include<stdio.h>
int main(void){
int a;
for(a=0;a<10;a++){
printf("%dn", (a%2)*6+4);
}
}
4
10
4
10
4
10
4
10
4
10
#include<stdio.h>
int main(void){
int a=0;
while(a<10){
printf("%cn", a%4+97);
a++;
}
}
#include<stdio.h>
int main(void){
int a=0;
do{
printf("%cn", a%4+97);
a++;
}
while(a<10);
}
#include<stdio.h>
int main(void){
int a;
for(a=0;a<10;a++){
printf("%cn", a%4+97);
}
}
a
b
c
d
a
b
c
d
a
b
#include<stdio.h>
int main(void){
int a=0;
while(a<10){
printf("%cn", (a%2)*6+97);
a++;
}
}
#include<stdio.h>
int main(void){
int a=0;
do{
printf("%cn", (a%2)*6+97);
a++;
}
while(a<10);
}
#include<stdio.h>
int main(void){
int a;
for(a=0;a<10;a++){
printf("%cn", (a%2)*6+97);
}
}
a
g
a
g
a
g
a
g
a
g
#include<stdio.h>
int main(void){
int a=1;
while(a<10){
printf("%cn", a%4+97);
a++;
}
}
#include<stdio.h>
int main(void){
int a=1;
do{
printf("%cn", a%4+97);
a++;
}
while(a<10);
}
#include<stdio.h>
int main(void){
int a;
for(a=1;a<10;a++){
printf("%cn", a%4+97);
}
}
b
c
d
a
b
c
d
a
b
#include<stdio.h>
int main(){
int a;
for(a=0;a<20;a++){
printf("%dn", (a%6)*(-4)+10);
}
}
10
6
2
-2
-6
-10
10
6
2
-2
-6
-10
10
6
2
-2
-6
-10
10
6
#include<stdio.h>
int main(void){
int a;
for(a=0;a<10;a++){
printf("%c", a%4+65);
Abcd Bbcd Cbcd Dbcd Abcd Bbcd Cbcd
Dbcd Abcd Bbcd
printf("bcd ");
}
}
#include<stdio.h>
int main(void){
int a;
for(a=0;a<10;a++){
printf(""%c", a%4+65);
printf("bcd" ");
}
}
"Abcd" "Bbcd" "Cbcd" "Dbcd" "Abcd"
"Bbcd" "Cbcd" "Dbcd" "Abcd" "Bbcd"
#include<stdio.h>
int main(void){
int i='d';
while(i>='a'){
printf("%cn", i);
i--;
}
}
#include<stdio.h>
int main(void){
int i='d';
do{
printf("%cn", i);
i--;
}
while(i>='a');
}
#include<stdio.h>
int main(void){
int i;
for(i='d';i>='a';i--){
printf("%cn", i);
}
}
#include<stdio.h>
int main(void){
int a,b;
for(a=0;a>-4;a--){
printf("%cn", (a%4)+100);
}
}
d
c
b
a
#include<stdio.h>
int main(void){
int i=0;
while(i<6){
printf("%dn", i+i*1+1);
i++;
}
}
#include<stdio.h>
int main(void){
int i=0;
do{
printf("%dn", i+i*1+1);
i++;
}
while(i<6);
}
#include<stdio.h>
int main(void){
int i;
for(i=0;i<6;i++){
printf("%dn", i+i*1+1);
}
}
#include<stdio.h>
int main(void){
int i;
for(i=1;i<12;i+=2){ // i+=2/i=i+2
printf("%dn", i);
}
}
1
3
5
7
9
11
#include<stdio.h>
int main(void){
int i='d';
while(i>='a'){
printf("%cn", i);
i--;
}
}
#include<stdio.h>
int main(void){
int i='d';
do{
printf("%cn", i);
i--;
}
while(i>='a');
}
#include<stdio.h>
int main(void){
int i;
for(i='d';i>='a';i--){
printf("%cn", i);
}
}
d
c
b
a
#include<stdio.h>
int main(void){
int i=0;
while(i<6){
printf("%dn", i+i*1+1);
i++;
}
}
#include<stdio.h>
int main(void){
int i=0;
do{
printf("%dn", i+i*1+1);
i++;
}
while(i<6);
}
#include<stdio.h>
int main(void){
int i;
for(i=0;i<6;i++){
printf("%dn", i+i*1+1);
}
}
1
3
5
7
9
11
#include<stdio.h>
int main(void){
int i=0;
while(i<=5){
printf("%dn", i+i*1+2);
i++;
}
}
#include<stdio.h>
int main(void){
int i=0;
do{
printf("%dn", i+i*1+2);
i++;
}
while(i<=5);
}
#include<stdio.h>
int main(void){
int i;
for(i=0;i<=5;i++){
printf("%dn", i+i*1+2);
}
}
2
4
6
8
10
12
#include<stdio.h>
int main(void){
int i=0,j=1;
while(i<=5,j<=6){
printf("%dn",(i%2*(-2)+1)*j );
i++,j++;
}
#include<stdio.h>
int main(void){
int i=0,j=1;
do {
printf("%dn",(i%2*(-2)+1)*j );
i++,j++;
}
#include<stdio.h>
int main(void){
int i,j;
for(i=0,j=1;i<=5,j<=6;i++,j++){
printf("%dn",(i%2*(-2)+1)*j );
}
1
-2
3
-4
5
-6
} while(i<=5,j<=6);
}
}
#include<stdio.h>
int main(void){
int i=0,j=1;
while(i<=5,j<=6){
printf("%dn",(i%2*(-2)+1)*j );
i++,j++;
}
}
#include<stdio.h>
int main(void){
int i=0,j=1;
do {
printf("%dn",(i%2*(-2)+1)*j );
i++,j++;
}
while(i<=5,j<=6);
}
#include<stdio.h>
int main(void){
int i,j;
for(i=0,j=1;i<=5,j<=6;i++,j++){
printf("%dn",(i%2*(-2)+1)*j );
}
}
#include<stdio.h>
int main(void){
int i;
for(i=1; i<=6; i++){
if(i%2==0){
printf("%dn", -i);
}
else
printf("%dn", i);
}
}
1
-2
3
-4
5
-6
# l.oidus<edulcni<
int main(void){
int i;
for(i=1; i<=10; i++){
if(i<4){
printf(""a%c" ", i%3+97);
}
else if(i<7){
printf(""b%c" ", i%3+97);
}
else if(i<10){
printf(""c%c" ", i%3+97);
}
else
printf(""d%c" ", i%3+97);
}
}
"ab" "ac" "aa" "bb" "bc" "ba" "cb" "cc"
"ca" "db"
#include<stdio.h>
int main()
{
int i = 0;;
while( i < 10)
{
printf ("Hello worldn");
i++;
}
}
#include<stdio.h>
int main()
{
int i = 0;;
do
{
printf ("Hello worldn");
i++;
}
while( i < 10);
}
#include<stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf ("Hello worldn");
}
}
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
#include<stdio.h>
int main()
{
int i = 0;;
while( i < 10)
{
printf ("Hello worldn");
printf ("I'mdown heren");
i++;
}
}
#include<stdio.h>
int main()
{
int i = 0;
do
{
printf ("Hello worldn");
printf ("I'mdown heren");
i++;
}
while( i < 10);
}
#include<stdio.h>
int main()
{
int i;
for(i= 0; i < 10; i++)
{
printf ("Hello worldn");
printf ("I'mdown heren");
}
}
Hello world
I'mdown here
Hello world
I'mdown here
Hello world
I'mdown here
Hello world
I'mdown here
Hello world
I'mdown here
Hello world
I'mdown here
Hello world
I'mdown here
Hello world
I'mdown here
Hello world
I'mdown here
Hello world
I'mdown here
#include<stdio.h>
int main()
#include<stdio.h>
int main()
#include<stdio.h>
While, do while(6) For(6)
{
int counter = 0, howmuch;
scanf("%d", &howmuch);
while ( counter < howmuch)
{
counter++;
printf("%dn", counter);
}
}
{
int counter = 0, howmuch;
scanf("%d", &howmuch);
do
{
counter++;
printf("%dn", counter);
}
while ( counter < howmuch);
}
int main()
{
int counter, howmuch;
scanf("%d", &howmuch);
for(counter=0 ;counter < howmuch;++counter)
{
printf("%dn", counter);
}
}
1
2
3
4
5
6
0
1
2
3
4
5
#include<stdio.h>
int main(void) {
int i;
i = 0;
while(i++ < 5) {
printf("%dn", i);
}
printf("n");
i = 0;
while(++i < 5) {
printf("%dn", i);
}
}
#include<stdio.h>
int main(void) {
int i;
i = 0;
do
{
printf("%dn", i);
}
while(i++ < 5);
printf("n");
i = 0;
do
{
printf("%dn", i);
}
while(++i < 5);
}
#include<stdio.h>
int main(void) {
int i;
for(i = 0;i++ < 5;)
{
printf("%dn", i);
}
printf("n");
for(i=0;++i<5;)
{
printf("%dn", i);
}
}
While/for
1
2
3
4
5
1
2
3
4
Do while
0
1
2
3
4
5
0
1
2
3
4
#include<stdio.h>
int main()
{
int i=0,j=2;
while (i<=11){
printf("%d ",(i%4)*j+j);
i++;
}
}
#include<stdio.h>
int main()
{
int i=0,j=2;
do
{
printf("%d ",(i%4)*j+j);
i++;
}
while (i<=11);
}
#include<stdio.h>
int main()
{
int i,j;
for (i=0,j=2;i<=11;i++)
printf("%d ",(i%4)*j+j);
}
2 4 6 8 2 4 6 8 2 4 6 8
#include <stdio.h>
int main(){
int a;
for(a=0;a<14;a++){
if(a%3==0){
printf("%d ", a%3+2);
}
else if(a%3==1){
printf("%d ", a%3+6);
}
else if (a%3==2){
printf("%d ", a%3+1);
}
}
}
2 7 3 2 7 3 2 7 3 2 7 3 2 7 #include <stdio.h>
int main(){
int a;
for(a=0;a<14;a++){
if(a%3==0){
printf("%d ", a%3+2);
}
else if(a%3==1){
printf("%d ", a%3+6);
}
else{
printf("%d ", a%3+1);
}
}
}
2 7 3 2 7 3 2 7 3 2 7 3 2 7
#l.oidus <stdio.h>
int main(){
int a;
for(a=2; a<=9; a++)
{
if(!(a==2 || a==7 || a==9) ){
continue;
}
else {
printf("%d ", a);
}
}
}
2 7 9 #include <stdio.h>
int main(){
int a;
for(a=2; a<=9; a++)
{
if(a>2 && a<7){
continue;
}
else if(a==7){
printf("%d ",a);
}
else if(a==8){
continue;
}
else{
printf("%d ",a);
2 7 9
// for “and” every condition mustbe true if we wantit's a true
// for “or” only one condition has to be true
}
}
}
#include<stdio.h>
int main(viod){
int f1, f2, f;
printf("1 ");
for(f1=0,f2=1,f=f1+f2; f<=99; ){
printf("%d ", f);
f1 = f2;
f2 = f;
f = f1+2*f2;
}
}
1 1 3 7 17 41 99
#include<stdio.h>
int main(){
int a = 0, b = 1, c ;
printf("0 1 ");
for(c = 1; c<100; ){
printf("%d ", c);
a = b;
b = c;
c = a+b;
}
}
#include<stdio.h>
int main(){
int a = -1, b = 0, c;
printf("0 ");
for(c = 1; c<100; ){
printf("%d ", c);
a = b;
b = c;
c = a+b;
}
}
0 1 1 2 3 5 8 13 21 34 55 89
Fibonacci series
Nested loop in c
While nested loop Do-while nested loop For nested loop Result
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
"nested for loop statement"
for(initialization condition; increment/decrement)
{
for(initialization;condition;increment/decrement)
{
statement perform while the condition is true
}
statement perform while the condition is true
}
for ( initialization ; condition ; updating)
{ // Starting of outer loop
for ( initialization ; condition ; updating)
{ // Starting of inner loop
Statement / Statements ;
}
Statement / Statements ;
}
Outer = column
Inner = row
#include <stdio.h>
int main()
{
int k, j, i,l, m, n;
for(i=0; i<1; i++)
for(k=1; k<9; k++) printf("%d",k);
12345678
23456789
345678910
4567891011
56789101112
#include <stdio.h>
int main ()
{
int i,j;
for(i=1; i<6; i++)
{
for(j=5; j>=i; j--)
54321
5432
543
54
5
printf("nn");
for(j=2; j<10; j++) printf("%d",j);
printf("nn");
for(l=3; l<11; l++) printf("%d", l);
printf("nn");
for(m=4; m<12; m++) printf("%d", m);
printf("nn");
for(n=5; n<13; n++) printf("%d", n);
return 0;
}
{
printf("%d",j);
}
printf("n");
}
}
#include <stdio.h>
int main ()
{
int i,j;
for(i=1; i<6; i++)
{
for(j=5; j>=i; j--)
{
printf("%d",i);
}
printf("n");
}
}
11111
2222
333
44
5
#include <stdio.h>
int main(void)
{
int a = 1;
int b = 0;
int c = 8;
for(a = 1; a <= 5; a++)
{
for(b = a; b <= c; b++)
{
printf("%d ", b);
}
c++;
putchar('n');
}
getchar();
return 0;
}
1 2 3 4 5 6 7 8
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9 10
4 5 6 7 8 9 10 11
5 6 7 8 9 10 11 12
#include <stdio.h>
int main ()
{
int i,j;
for(i=1; i<6; i++)
{
for(j=5; j>=i; j--)
{
printf("%d",i);
}
printf("n");
}
}
11111
2222
333
44
5
#include <stdio.h>
int main(void)
{
int a;
for(a = 0; a <= 19; a++)
{
if (a%8>=0 && a%8<=2){
a a a c c h h h a a a c c h h h a a a c #include <stdio.h>
int main ()
{
int i, j;
for(i=1; i<6; i++)
{
1
12
123
1234
12345
printf("a ");
}
else if (a%8>=3 && a%8<=4){
printf("c ");
}
else if (a%8>=5 && a%8<=7){
printf("h ");
}
}
}
for(j=1; j<=i; j++)
{
printf("%d", j);
}
printf("n");
}
}
#include <stdio.h>
int main(void)
{
int a,b;
for(a = 0, b=6; a <= 21; a++)
{
if (a%6>=0 && a%6<=2){
printf("a ");
}
else if (a%6>=3 && a%6<=4){
printf("b ");
}
else{
printf("%d ",b);
b++;
}
}
}
a a a b b 6 a a a b b 7 a a a b b 8 a a a b #include <stdio.h>
int main ()
{
int i,j;
for(i=1; i<6; i++)
{
for(j=1; j<=i; j++)
{
printf("%d",j);
}
printf("n");
}
}
1
12
123
1234
12345
#include <stdio.h>
int main ()
{
int i,j;
for(i=1; i<6; i++)
{
for(j=1; j<=i; j++)
{
printf("%d",i);
}
printf("n");
}
}
1
22
333
4444
55555
#include <stdio.h>
int main(void)
{
int a,b;
for(a = 0, b=5; a <= 23; a++)
{
if (a%8>=0 && a%8<=1){
printf("a ");
}
else if (a%8>=2 && a%8<=4){
printf("k ");
}
else if (a%8>=5 && a%8<=6){
printf("m ");
}
a a k k k m m 5 a a k k k m m 7 a a k k k m m 9 #include <stdio.h>
int main ()
{
int col,row;
for(row=1;row<8;row++){
for(col=1;col<=row;col++){
printf("%d ", row);
}
printf("n");
}
}
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
else {
printf("%d ",b);
b+=2;
}
}
}
#include <stdio.h>
int main(void)
{
int a,b;
for(a = 0; a <= 15; a++)
{
printf("%d ", a/4+4);
}
}
4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 #include <stdio.h>
int main ()
{
for( int row=1;row<8;row++){
for( int col=1;col<=row;col++){
printf("%d ", col);
}
printf("n");
}
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
#include <stdio.h>
int main(void)
{
int a,b;
for(a = 0; a <= 15; a++)
{
printf("%c ", a/3*2+97);
}
}
a a a c c c e e e g g g i i i k #include <stdio.h>
int main ()
{
int col,row;
for(row=1;row<=8;row++){
for(col=1;col<=row;col++){
printf("*");
}
printf("n");
}
}
*
**
***
****
*****
******
*******
********
#include <stdio.h>
int main ()
{
int col,row;
for(row=0;row>-4;row--){
for(col=0;col>=row;col--){
printf("%c",row*2+90);
}
printf("Dn");
}
}
ZD
XXD
VVVD
TTTTD
http://www.cquestions.com/2009/10/nested-
loop-in-c-programming.html
#include <stdio.h>
int main ()
{
int col,row;
for(row=1;row<=6;row++){
for(col=6;col>=row;col--){
printf("%d ",col);
}
printf("n");
}
}
6 5 4 3 2 1
6 5 4 3 2
6 5 4 3
6 5 4
6 5
6
#include <stdio.h>
int main(void)
{
int c, r;
for(c = 5; c >= 1; c--)
{
for(r = 5; r >= c; r--){
5
5 4
5 4 3
5 4 3 2
#include <stdio.h>
int main(void)
{
int c;
static r;
for(c = 1; c <= 6; c++)
{
*
*
*
*
*
*
printf("%d ", r);
}
printf("n");
}
}
5 4 3 2 1 for(r = 1; r <= 6-c; r++){
printf(" ");
}
printf("* ", r);
printf("n");
}
}
#include <stdio.h>
int main(void)
{
int c;
static r;
for(c = 1; c <= 6; c++)
{
for(r = 1; r <= 6-c; r++){
printf(" ");
printf("* ", r);
}
printf("n");
}
}
* * * * *
* * * *
* * *
* *
*
#include <stdio.h>
int main(void)
{
int c, r;
for(c = 1; c <= 6; c++)
{
for(r = 1; r <= 6-c; r++){
printf(" ", r);
}
for(r = 1; r <= c+c-1; r++){
printf("*");
}
printf("n");
}
}
*
***
*****
*******
*********
***********
#include <stdio.h>
int main(void)
{
int c, r;
for(c = 5; c >= 1; c--)
{
for(r = 5; r >= c; r--){
printf("%d ", r);
}
printf("n");
}
}
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
#include <stdio.h>
int main(void)
{
int c;
static r;
for(c = 0; c <= 20; c++)
{
for(r = 0; r <=20 ; r++){
if (r%4-1 == (c+r-1)%4 ){
printf("*", r);
}
else
printf("O");
}
printf("n");
}
}
#include <stdio.h>
int main(void)
{
int c;
static r;
for(c = 0; c <= 20; c++)
{
for(r = 0; r <=20 ; r++){
if ( ((r/4)%2 == 0) || ((c/4)%2 == 0) ){
printf("*", r);
}
else
printf("O");
}
printf("n");
}
}
#include <stdio.h>
int main(void)
{
int c;
static r;
for(c = 0; c <= 20; c++)
{
for(r = 0; r <=20 ; r++){
if ( ((r/4)%2 == 0)){
printf("*", r);
}
else
printf("O");
}
printf("n");
}
}
#include <stdio.h>
int main(void)
{
int c;
static r;
for(c = 0; c <= 20; c++)
{
for(r = 0; r <=20 ; r++){
if ( ((r/4)%2 == 0) || ((c/4)%2 != 0) ){
printf("*", r);
}
else
printf("O");
}
printf("n");
}
}
#include <stdio.h>
int main(void)
{
int c,r;
for(c = 0; c <= 20; c++)
{
for(r = 0; r <=20 ; r++){
if ( ((r/4)%2 == 0) && ((c/4)%2 != 0) ){
printf("*", r);
}
else if ( ((r/4)%2 == 0) || ((c/4)%2 != 0) ){
printf("O");
}
else
printf("*", r);
}
printf("n");
}
}
#include<stdio.h>
int main(){
int r, c, n;
printf("Enter the numbersyou wants to
multiplication = ");
scanf("%d",&n);
for(r=1; r<=n; r++){
for(c=1; c<=n;c++){
if(r<2){
printf("%dt", c);
}
else{
printf("%dt", r*c);
}
}
printf("n");
}
}
Enter the numbers you wants to multiplication = 5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
#include<stdio.h>
int main(){
Enter the numbers you wants to
multiplication= 5
#include<stdio.h>
int main(){
Enter the numbers you wants to
multiplication= 5
int r, c, n;
printf("Enter the numbersyou wants to
multiplication = ");
scanf("%d",&n);
printf("n");
for(r=1; r<=n; r++){
printf("%dt", r);
}
printf("n");
for(r=1; r<=n; r++){
printf("========");
}
printf("n");
for(r=1; r<=n; r++){
for(c=1; c<=n;c++){
if(r<2){
printf("%dt", c);
}
else{
printf("%dt", r*c);
}
}
printf("n");
}
}
1 2 3 4 5
====================
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
int r, c, n;
printf("Enter the numbersyou wants to multiplication =
");
scanf("%d",&n);
printf("n t");
for(r=1; r<=n; r++){
printf("%dt", r);
}
printf("n");
for(r=1; r<=n; r++){
printf("=========");
}
printf("n");
for(r=1; r<=n; r++){
printf("%d |t",r);
for(c=1; c<=n;c++){
if(r<2){
printf("%dt", c);
}
else{
printf("%dt", r*c);
}
}
printf("n");
}
}
1 2 3 4 5
=========================
1 | 1 2 3 4 5
2 | 2 4 6 8 10
3 | 3 6 9 12 15
4 | 4 8 12 16 20
5 | 5 10 15 20 25
break continue
The break statement will immediately jump to the end of the current block of code. The continue statement will skip the rest of the code in the current loop block and will return to the evaluation
#include <stdio.h>
int main(){
int i;
for(i=0; i<10; i++)
{
if(i>5)
break;
printf("%d ", i);
}
}
#include<stdio.h>
int main(){
int a;
for (a=0;a<=30;a++){
if(a==5){
printf("Fiven");
}
else if(a==10){
printf("Tenn");
}
else if(a==15){
printf("Fifteenn");
}
else if(a==20){
printf("Twentyn");
}
else if(a==25 ){
printf("Twenty-Fiven");
}
else if(a==30){
printf("Thirtyn");
}
if(a %5==0){
continue;
}
printf("%dn", a);
}
}
http://www.programmingsimplified.com/c-program-examples
#include <stdio.h>
int main()
{
printf("Hello worldn");
}
#include <stdio.h>
int main()
{
//char a="hello world"; this will not work
char a[]="hello world";
printf("%s",a);
}
#include <stdio.h>
int main()
{
if(printf("hello world")){}
}
hello world
#include<stdio.h>
main()
{
int n;
printf("Enter an integer = ");
#include<stdio.h>
main()
{
int n;
printf("Enter an integer = ");
#include<stdio.h>
main()
{
int n;
printf("Enter an integer = ");
ODD or EVEN
scanf("%d",&n);
if ( n%2 == 0 )
printf("%d is a Even numbern",n);
else
printf("%d is a ODD numbern",n);
}
scanf("%d",&n);
if ( n & 1== 1)
printf("%d is an odd numbern",n);
else
printf("%d is an even numbern",n);
}
scanf("%d",&n);
( n & 1== 1)? printf("%d is an odd numbern",n): printf("%d is an even numbern",n);
}
#include<stdio.h>
main()
{
int n;
printf("Enter an integer = ");
scanf("%d",&n);
if ( (n/2)*2 == n )
printf("Evenn");
else
printf("Oddn");
}
#include <stdio.h>
int main()
{
int year;
printf("Enter a year to check if it is a leap yearn");
scanf("%d", &year);
if ( year%400 == 0)
printf("%d is a leap year.n", year);
else if ( year%100 == 0)
printf("%d is not a leap year.n", year);
else if ( year%4 == 0 )
printf("%d is a leap year.n", year);
else
printf("%d is not a leap year.n", year);
}
#include <stdio.h>
int main(){
int a ;
printf("Input a number of a year to know if it is a leap year or not = ");
scanf("%d", &a );
if(a%400==0){
printf(" leap year");
}
else if(a%100==0){
printf("not leap year");
}
else if (a%4==0){
printf("leap year");
}
else if(a%4!=0){
printf("not leap year");
}
else
printf("not leap year");
}
Leap Year
#include <stdio.h>
#include <stdlib.h>
main()
{
char ch;
printf("Do you want to know yourip address (y/n) = ");
scanf("%c",&ch);
if (ch == 'y' )
system("c:windowssystem32ipconfig");
}
Ip Address
#include <stdio.h>
#include <stdlib.h>
main()
{
char ch;
printf("Do you want to shutdown yourcomputer (y/n) = ");
scanf("%c",&ch);
if(ch=='y')
system("c:windowssystem32shutdown /s");
else
printf("Thanks");
return 0;
}
Shutdown
#include <stdio.h>
main()
{
char ch[10000];
printf("Input an string line to reverse = ");
gets(ch);
strrev(ch);
printf("%s",ch);
}
string line to reverse #include <stdio.h>
#include <stdlib.h>
main()
{
char ch;
printf("Do you want to know yourip address (y/n) = ");
scanf("%c",&ch);
if (ch == 'y' )
system("c:windowssystem32ping");
}
Ping
ipconfig
ping
msinfo32
cmdkey.exe
calc.exe
ARP.EXE
attrib.exe
auditpol.exe
cacls.exe
net user
net user saifur *
net user saifur (look what’s the user name of you computer)*
Best pictures
1. Write a for loop to print the following:
-4 -3 -2 -1 0 1 2 3 4 5 6 7
#include <stdio.h>
int main(){
int i;
for(i=-4; i<=7; i++)
{
printf("%d ", i);
}
}
2. Write a loop to print the following:
3 4 5 6 7 3 4 5 6 7 3 4 5 6 7 3 4 5 6 7 3 4 5
#include <stdio.h>
int main(){
int i;
for(i=0; i<23; i++)
{
printf("%d ", i%5+3);
}
}
3.Write a loop to print the following:
2 4 6 8 2 4 6 8 2 4 6 8
#include <stdio.h>
int main(){
int i;
for(i=0; i<=11; i++)
{
printf("%d ", i%4*2+2);
4.Write a loop to print the following:
a c e g a c e g a c e
#include <stdio.h>
int main(){
int i;
for(i=0; i<11; i++)
{
printf("%c ", i%4*2+97);
}
}
}
}
Built In Functions
#include<stdio.h>
int main()
{
printf("It is :: %s", ctime(t));
}
#include<stdio.h>
#include<time.h>
int main()
{
time_t t = time(NULL);
printf("It is :: %s", ctime(&t));
}It is :: Wed Feb 04 02:46:25 2004
It is :: Sat May 24 13:50:39 2014
FUNCTION
Syntax : Function Definitionin C Programming
return-type function-name(parameter lists)
{
declarations
statements
return value;
}
/*include header file*/
/*function prototype here*/
int main(viod){
/* */
}
ret-type f1(param-list){
/* */
}
ret-type f2(param-list){
/* */
}
#include<stdio.h>
int f1(int, int);
int main(viod){
int a=10, b=20, sum;
sum= f1(a, b);
printf("Thesumof the two integers is = %d", sum);
}
int f1(intx, int y){
return x+y;
}
#include<stdio.h>
int f1(int x, int y);
int main(viod){
int a=10, b=20;
printf("The sum of the two integers is = %d", f1(a, b));
}
int f1(int x, int y){
return x+y;
}
Function prototype
Function prototypeis the declaration of user defined
function. Which is declared before it is used & terminated by a semicolon.
Only main function does not needa prototype , because it is predefinedby the C
language
Function Definition in C Programming I Defining a function:
What is Function Definition in C Programming?
1. Functiondefinition isnothing but actualFunction.
2. FunctionCall is short term used, however functiondefinitionis“Actual
Broad Elaboration” offunctioncall.
3. Functiondefinitionisdifferent from macroexpansion.
4. It contain ExecutableCode ( Executablestatements)
5. First Line is called as FunctionHeader .
6. FunctionHeader should be identicaltofunctionPrototypewith
the exceptionof semicolon
7. Argument nameshasto specify here !!
Syntax : Function Definitionin C Programming
return-type function-name(parameter lists)
{
declarations
statements
return value;
}
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}1. Return type
2. Function name
3. Parameters list
4. statement
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)

Weitere ähnliche Inhalte

Was ist angesagt? (20)

C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Managing console input
Managing console inputManaging console input
Managing console input
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
CS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic ServicesCS4200 2019 | Lecture 4 | Syntactic Services
CS4200 2019 | Lecture 4 | Syntactic Services
 
Theory1&amp;2
Theory1&amp;2Theory1&amp;2
Theory1&amp;2
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
L6
L6L6
L6
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 

Andere mochten auch

23. Open Government - Plattform Wien
23. Open Government - Plattform Wien23. Open Government - Plattform Wien
23. Open Government - Plattform WienStadt Wien
 
Curso Atención Temprana en Contextos Naturales - Comunicación y lenguaje en b...
Curso Atención Temprana en Contextos Naturales - Comunicación y lenguaje en b...Curso Atención Temprana en Contextos Naturales - Comunicación y lenguaje en b...
Curso Atención Temprana en Contextos Naturales - Comunicación y lenguaje en b...cinsalta
 
Guia seguridad productosinfantilesGuía de Seguridad de los Productos Infantil...
Guia seguridad productosinfantilesGuía de Seguridad de los Productos Infantil...Guia seguridad productosinfantilesGuía de Seguridad de los Productos Infantil...
Guia seguridad productosinfantilesGuía de Seguridad de los Productos Infantil...Cristobal Buñuel
 
Memoria Cto Spain Alevin
Memoria Cto Spain AlevinMemoria Cto Spain Alevin
Memoria Cto Spain Alevinguestdca39e
 
Tugas iv kritik review disertasi sofi mubarok
Tugas iv kritik review disertasi sofi mubarokTugas iv kritik review disertasi sofi mubarok
Tugas iv kritik review disertasi sofi mubarokMuhamad Sofi Mubarok
 
Products, Services, and Brands and Real Marketing (Chapter – 08).docx
Products, Services, and Brands and Real Marketing (Chapter – 08).docxProducts, Services, and Brands and Real Marketing (Chapter – 08).docx
Products, Services, and Brands and Real Marketing (Chapter – 08).docxMd. Moazzem Hossain
 
Jungletrainingcamp
JungletrainingcampJungletrainingcamp
Jungletrainingcampsumitra66
 
Nenad Andrakovic - Changing the way frontend developers think and work - Mage...
Nenad Andrakovic - Changing the way frontend developers think and work - Mage...Nenad Andrakovic - Changing the way frontend developers think and work - Mage...
Nenad Andrakovic - Changing the way frontend developers think and work - Mage...Meet Magento Italy
 
EGGER Worktops Contemporary Collection
EGGER Worktops Contemporary CollectionEGGER Worktops Contemporary Collection
EGGER Worktops Contemporary CollectionEGGER UK
 
Cv Enrique Videla 2011 Eng
Cv Enrique Videla 2011 EngCv Enrique Videla 2011 Eng
Cv Enrique Videla 2011 Engevidela
 
GRATE COOLER (IN CEMENT PRODUCTION)
GRATE COOLER (IN CEMENT PRODUCTION)GRATE COOLER (IN CEMENT PRODUCTION)
GRATE COOLER (IN CEMENT PRODUCTION)Anggi Sagitha
 
G indicadores de-gestion-jb
G indicadores de-gestion-jbG indicadores de-gestion-jb
G indicadores de-gestion-jbYemelin Perez
 
Presentación sobre terapia floral
Presentación sobre terapia floralPresentación sobre terapia floral
Presentación sobre terapia floralgasper1234
 
Information Management Life Cycle
Information Management Life CycleInformation Management Life Cycle
Information Management Life CycleCollabor8now Ltd
 
Manual de trituracion
Manual de trituracionManual de trituracion
Manual de trituracionalejamarinm1
 

Andere mochten auch (20)

23. Open Government - Plattform Wien
23. Open Government - Plattform Wien23. Open Government - Plattform Wien
23. Open Government - Plattform Wien
 
Curso Atención Temprana en Contextos Naturales - Comunicación y lenguaje en b...
Curso Atención Temprana en Contextos Naturales - Comunicación y lenguaje en b...Curso Atención Temprana en Contextos Naturales - Comunicación y lenguaje en b...
Curso Atención Temprana en Contextos Naturales - Comunicación y lenguaje en b...
 
Guia seguridad productosinfantilesGuía de Seguridad de los Productos Infantil...
Guia seguridad productosinfantilesGuía de Seguridad de los Productos Infantil...Guia seguridad productosinfantilesGuía de Seguridad de los Productos Infantil...
Guia seguridad productosinfantilesGuía de Seguridad de los Productos Infantil...
 
Peticao dz
Peticao dzPeticao dz
Peticao dz
 
Memoria Cto Spain Alevin
Memoria Cto Spain AlevinMemoria Cto Spain Alevin
Memoria Cto Spain Alevin
 
Dragon Cave - Nº01
Dragon Cave - Nº01Dragon Cave - Nº01
Dragon Cave - Nº01
 
Tugas iv kritik review disertasi sofi mubarok
Tugas iv kritik review disertasi sofi mubarokTugas iv kritik review disertasi sofi mubarok
Tugas iv kritik review disertasi sofi mubarok
 
Poster presentation Royal Society Of Medicine London
Poster presentation Royal Society Of Medicine LondonPoster presentation Royal Society Of Medicine London
Poster presentation Royal Society Of Medicine London
 
Guia diete web
Guia diete webGuia diete web
Guia diete web
 
Products, Services, and Brands and Real Marketing (Chapter – 08).docx
Products, Services, and Brands and Real Marketing (Chapter – 08).docxProducts, Services, and Brands and Real Marketing (Chapter – 08).docx
Products, Services, and Brands and Real Marketing (Chapter – 08).docx
 
Jungletrainingcamp
JungletrainingcampJungletrainingcamp
Jungletrainingcamp
 
Dossier Rafael Medina Barbero 2015
Dossier Rafael Medina Barbero 2015Dossier Rafael Medina Barbero 2015
Dossier Rafael Medina Barbero 2015
 
Nenad Andrakovic - Changing the way frontend developers think and work - Mage...
Nenad Andrakovic - Changing the way frontend developers think and work - Mage...Nenad Andrakovic - Changing the way frontend developers think and work - Mage...
Nenad Andrakovic - Changing the way frontend developers think and work - Mage...
 
EGGER Worktops Contemporary Collection
EGGER Worktops Contemporary CollectionEGGER Worktops Contemporary Collection
EGGER Worktops Contemporary Collection
 
Cv Enrique Videla 2011 Eng
Cv Enrique Videla 2011 EngCv Enrique Videla 2011 Eng
Cv Enrique Videla 2011 Eng
 
GRATE COOLER (IN CEMENT PRODUCTION)
GRATE COOLER (IN CEMENT PRODUCTION)GRATE COOLER (IN CEMENT PRODUCTION)
GRATE COOLER (IN CEMENT PRODUCTION)
 
G indicadores de-gestion-jb
G indicadores de-gestion-jbG indicadores de-gestion-jb
G indicadores de-gestion-jb
 
Presentación sobre terapia floral
Presentación sobre terapia floralPresentación sobre terapia floral
Presentación sobre terapia floral
 
Information Management Life Cycle
Information Management Life CycleInformation Management Life Cycle
Information Management Life Cycle
 
Manual de trituracion
Manual de trituracionManual de trituracion
Manual de trituracion
 

Ähnlich wie C cheat sheet for varsity (extreme edition)

Ähnlich wie C cheat sheet for varsity (extreme edition) (20)

T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 
7512635.ppt
7512635.ppt7512635.ppt
7512635.ppt
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
 
Cbasic
CbasicCbasic
Cbasic
 
Cbasic
CbasicCbasic
Cbasic
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
Cbasic
CbasicCbasic
Cbasic
 
programming language in c&c++
programming language in c&c++programming language in c&c++
programming language in c&c++
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Tut1
Tut1Tut1
Tut1
 
2 data and c
2 data and c2 data and c
2 data and c
 
2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt
 
C language
C languageC language
C language
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Clanguage
ClanguageClanguage
Clanguage
 

Kürzlich hochgeladen

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 

Kürzlich hochgeladen (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

C cheat sheet for varsity (extreme edition)

  • 1. Author: Md. Saifur Rahman Education: 4th semester at CSE Department in Southeast University Banani, Dhaka, Bangladesh. Md. Saifur Rahman C Programming Language
  • 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<stdio.h> 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 X’s 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. 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 & it’s values. Variable’s 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. string integer floating point saifur 67 67.0 A+ 4 4.0
  • 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. 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. 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. 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 mark Backslash ? Literal question mark 0 Null ooo 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. 1 abs() Absolute value Returns the absolute value of parameter n ( /n/ ). In C++, this function is also overloaded in header <cmath> for floating- point types (see cmath abs), in header<complex> for complex numbers (see complex abs), and in header <valarray> 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 <stdio.h> /* printf */ #include <stdlib.h> /* 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 <stdio.h> /* printf */ #include <math.h> /* 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 <stdio.h> /* printf */ #include <math.h> /* 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 <tgmath.h> 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 <stdio.h> /* printf */ #include <math.h> /* 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 <stdio.h> /* printf */ #include <math.h> /* 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 (<cmath>) 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 <complex> and <valarray> (see complex sqrt and valarray sqrt). 1 2 3 4 5 6 7 8 9 10 11 12 /* sqrt example */ #include <stdio.h> /* printf */ #include <math.h> /* 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 <stdio.h> /* printf */ #include <math.h> /* 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. 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 <stdio.h> /* printf */ #include <math.h> /* 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 (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations. This function is also overloaded in <complex> and <valarray> (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 <stdio.h> /* printf */ #include <math.h> /* 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 <cstdlib>. 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 <random>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 <stdio.h> /* printf, scanf, puts, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> /* 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 (iSecret<iGuess) puts ("The secret number is lower"); else if (iSecret>iGuess) 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 <ctime>). 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 <stdio.h> /* printf, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> /* 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. 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. 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. 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. printf scanf I/O of floats in C #include <stdio.h> 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. %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 a<<1 = 4 a<<2 = 8 a<<3 = 16 a>>1 = 1 a>>2 = 0 a>>3 = 0 b = 4 b<<1 = 8 b<<2 = 16 b<<3 = 32 b>>1 = 2 b>>2 = 1 b>>3 = 0 #include <stdio.h> 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<< 1 = %dt a<< 2 = %dt a<< 3 = %dt a<< 4 = %dt a<< 5 = %dt ",a, a<<1,a<<2,a<<3,a<<4,a<<5); printf("na1= %dt && a1<<1 = %dt a1<<2 = %dt a1<<3 = %dt a1<<4 = %dt a1<<5 = %dt ",a1, a1<<1,a1<<2,a1<<3,a1<<4,a1<<5); printf("na2= %dt && a2<<1 = %dt a2<<2 = %dt a2<<3 = %dt a2<<4 = %dt a2<<5 = %dt ",a2, a2<<1,a2<<2,a2<<3,a2<<4,a2<<5); printf("na3= %dt && a3<<1 = %dt a3<<2 = %dt a3<<3 = %dt a3<<4 = %dt a3<<5 = %dt ",a3, a3<<1,a3<<2,a3<<3,a3<<4,a3<<5); printf("na4= %dt && a4<<1 = %dt a4<<2 = %dt a4<<3 = %dt a4<<4 = %dt a4<<5 = %dt ",a4, a4<<1,a4<<2,a4<<3,a4<<4,a4<<5); printf("na5= %dt && a5<<1 = %dt a5<<2 = %dt a5<<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); } #include <stdio.h> 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>> 1 = %dt a>> 2 = %dt a>> 3 = %dt a>> 4 = %dt a>> 5 = %dt ",a, a>> 1,a>> 2,a>> 3,a>> 4,a>> 5); printf("na1= %dt && a1>> 1 = %dt a1>> 2 = %dt a1>> 3 = %dt a1>> 4 = %dt a1>> 5 = %dt ",a1, a1>> 1,a1>> 2,a1>> 3,a1>> 4,a1>> 5); printf("na2= %dt && a2>> 1 = %dt a2>> 2 = %dt a2>> 3 = %dt a2>> 4 = %dt a2>> 5 = %dt ",a2, a2>> 1,a2>> 2,a2>> 3,a2>> 4,a2>> 5); printf("na3= %dt && a3>> 1 = %dt a3>> 2 = %dt a3>> 3 = %dt a3>> 4 = %dt a3>> 5 = %dt ",a3, a3>> 1,a3>> 2,a3>> 3,a3>> 4,a3>> 5); printf("na4= %dt && a4>> 1 = %dt a4>> 2 = %dt a4>> 3 = %dt a4>> 4 = %dt a4>> 5 = %dt ",a4, a4>> 1,a4>> 2,a4>> 3,a4>> 4,a4>> 5); printf("na5= %dt && a5>> 1 = %dt a5>> 2 = %dt a5>> 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. a= 0 && a<< 1 = 0 a<< 2 = 0 a<< 3 = 0 a<< 4 = 0 a<< 5 = 0 a1= 1 && a1<<1 = 2 a1<<2 = 4 a1<<3 = 8 a1<<4 = 16 a1<<5 = 32 a2= 2 && a2<<1 = 4 a2<<2 = 8 a2<<3 = 16 a2<<4 = 32 a2<<5 = 64 a3= 3 && a3<<1 = 6 a3<<2 = 12 a3<<3 = 24 a3<<4 = 48 a3<<5 = 96 a4= 4 && a4<<1 = 8 a4<<2 = 16 a4<<3 = 32 a4<<4 = 64 a4<<5 = 128 a5= 5 && a5<<1 = 10 a5<<2 = 20 a5<<3 = 40 a5<<4 = 80 a5<<5 = 160 a6= 6 && a6<<1 = 12 a6<<2 = 24 a6<<3 = 48 a6<<4 = 96 a6<<5 = 192 a7= 7 && a7<<1 = 14 a7<<2 = 28 a7<<3 = 56 a7<<4 = 112 a7<<5 = 224 a8= 8 && a8<<1 = 16 a8<<2 = 32 a8<<3 = 64 a8<<4 = 128 a8<<5 = 256 a9= 9 && a9<<1 = 18 a9<<2 = 36 a9<<3 = 72 a9<<4 = 144 a9<<5 = 288 a10=10 && a10<<1= 20 a10<<2= 40 a10<<3= 80 a10<<4= 160 a10<<5= 320 a= 0 && a>> 1 = 0 a>> 2 = 0 a>> 3 = 0 a>> 4 = 0 a>> 5 = 0 a1= 1 && a1>> 1 = 0 a1>> 2 = 0 a1>> 3 = 0 a1>> 4 = 0 a1>> 5 = 0 a2= 2 && a2>> 1 = 1 a2>> 2 = 0 a2>> 3 = 0 a2>> 4 = 0 a2>> 5 = 0 a3= 3 && a3>> 1 = 1 a3>> 2 = 0 a3>> 3 = 0 a3>> 4 = 0 a3>> 5 = 0 a4= 4 && a4>> 1 = 2 a4>> 2 = 1 a4>> 3 = 0 a4>> 4 = 0 a4>> 5 = 0 a5= 5 && a5>> 1 = 2 a5>> 2 = 1 a5>> 3 = 0 a5>> 4 = 0 a5>> 5 = 0 a6= 6 && a6>> 1 = 3 a6>> 2 = 1 a6>> 3 = 0 a6>> 4 = 0 a6>> 5 = 0 a7= 7 && a7>> 1 = 3 a7>> 2 = 1 a7>> 3 = 0 a7>> 4 = 0 a7>> 5 = 0 a8= 8 && a8>> 1 = 4 a8>> 2 = 2 a8>> 3 = 1 a8>> 4 = 0 a8>> 5 = 0 a9= 9 && a9>> 1 = 4 a9>> 2 = 2 a9>> 3 = 1 a9>> 4 = 0 a9>> 5 = 0 a10= 10 && a10>>1 = 5 a10>>2 = 2 a10>> 3 = 1 a10>>4 = 0 a10>>5 = 0 Cheat sheet #include<stdio.h> Using angle bracket #include”stdio.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. 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<stdio.h> 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. Best Example #include<stdio.h> 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<stdio.h>
  • 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. 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 <stdio.h> #include <conio.h> int main () { clrscr(); printf (“Welcome to C language”); return 0; } #include <stdio.h> #include <conio.h> int main () { clrscr(); printf (“Welcome to C language”); getch(); retun 0; } String: strlen() #include <stdio.h> #include <conio.h> 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 <stdio.h> #include <conio.h> int main() { char str[30]="C PROGRAMMING"; clrscr(); printf("nnstr : %snn",str); printf("strlwr(str) : %sn",strlwr(str)); getch(); return 0; } String: strupr() #include <stdio.h> #include <conio.h> int main() { char str[30]="C Programming"; clrscr(); printf("nnstr : %snn",str); printf("strupr(str) : %sn",strupr(str)); getch(); return 0; } String: strncat() #include <stdio.h> #include <conio.h> 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 <stdio.h> #include <conio.h> 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 <stdio.h> #include <conio.h> 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 <stdio.h> #include <conio.h> 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 <stdio.h> #include <conio.h> 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) printf("nnstr1< str2"); else printf("nnstr1< str2"); getch(); return 0; }
  • 21. 2nd Term Conversion characters 5.4 Printing Integers  Integer is a whole number, such as 880 or –456, that contains no decimal point.  Table 5.1 is a summary of an integer conversion specifier. Conversion specifier Description d Display a signed decimal integer i Display a signed decimal integer. (Note: The i and d specifiers are different when used with scanf().) o Display an unsigned octal integer. u Display an unsigned decimal integer. x or X Display an unsigned decimal integer. x causes the digit 0-9 and the letters A-F to be displayed, and xcauses the digits 0-9 and a–f to be displayed. h or l (letter l) Place before any integer conversion specifier to indicate that a short or long integer is displayed respectively. Table 5.1: Integer conversion specifiers  Let explore through a program example. // using the integer conversion specifiers #include <stdio.h> int main() { printf("Various format for integer printingn"); printf("-------------------------------------n"); printf("%dn", 455); printf("%in", 455); //i same as d in printf() printf("%dn", +455); printf("%dn", -455); printf("%hdn", 32000); printf("%ldn", 2000000000L); printf("%on", 455); printf("%un", 455); printf("%un", -455); //-455 is read by %u and converted to the unsigned //value 4294966841 by 4 bytes integer printf("%xn", 455); printf("%Xn", 455); return 0; } Output: 5.5 Printing Floating-point Number  Contains the decimal point such as 35.5 or 7456.945.  Table 5.2 summarizes the floating-point conversion specifiers. Conversion specifier Description e or E Display a floating-point value in exponential notation. f Display floating-point values. g or G Display a floating-point value in either the floating-point form f or the exponential form e ( or E) l Place before any floating-point conversion specifier to indicate that a long double floating-point value is displayed. Table 5.2: Floating-point conversion specifiers  Exponential notation is the computer equivalent of scientific notation used in mathematics. For example, 150.2352 is represented in scientific notation as: 1.502352 x 102  And is represented in exponential notation as: 1.502352E+02 by computer  So, 150.2352 = 1.502352 x 102 = 1.502352E+02  E stand for exponent.  e, E and f will output with 6 digits of precision to the right of the decimal point by default.
  • 22.  Let try a program example. // printing floating-point numbers with floating-point conversion specifiers #include <stdio.h> void main() { printf("Printing floating-point numbers withn"); printf("floating-point conversion specifiers.n"); printf("Compare the output with source codenn"); printf("1. %en", 1234567.89); printf("2. %en", +1234567.89); printf("3. %en", -1234567.89); printf("4. %En", 1234567.89); printf("5. %fn", 1234567.89); printf("6. %gn", 1234567.89); printf("7. %Gn", 1234567.89); } Output: 5.6 Printing Strings And Characters  c and s conversion specifiers are used to print individual characters and strings respectively.  Conversion specifier c requires a char argument and s requires a pointer to char as an argument.  s causes characters to be printed until a terminating NULL (‘0’) character is encountered.  A program example. // printing strings and characters #include <stdio.h> int main() { char character = 'A'; char string[ ] = "This is a string"; char *stringPtr = "This is also a string"; printf("---------------------------------n"); printf("---Character and String format---n"); printf("---------------------------------nn"); printf("%c <--This one is charactern", character); printf("nLateral stringn"); printf("%sn", "This is a string"); printf("nUsing array name, the pointer to the first array's elementn"); printf("%sn", string); printf("nUsing pointer, pointing to the first character of stringn"); printf("%sn", stringPtr); return 0; } 5.7 Other Conversion Specifiers  p, n and % are summarized in table 5.3 followed by the program example. Conversion specifier Description p Display a pointer value (memory address) in an implementation defined manner. n Store the number of characters already output in the current printf() statement. A pointer to an integer is supplied as the corresponding argument. Nothing is displayed. % Display the percent character. Table 5.3: Other conversion specifiers // using the p, n, and % conversion specifiers #include <stdio.h> int main() { // pointer variable int *ptr; int x = 12345, y; // assigning address of variable x to variable ptr ptr = &x; printf("nUsing the p, n, and %% conversion specifiers.n"); printf("Compare the output with the source coden"); printf("-----------------------------------------------nn"); printf("The value of pointer ptr is %pn", ptr); printf("The address of variable x is %pnn", &x); printf("Total characters printed on this line is:%n", &y); printf(" %dnn", y); y = printf("This line has 28 charactersn"); printf("%d characters were printednn", y); printf("Printing a %% in a format control stringn"); return 0; } 5.8 Printing With Field Widths And Precisions  A field width determines the exact size of a field in which data is printed.
  • 23.  If the field width is larger then the data being printed, the data will normally be right-justified within that field.  An integer representing the field width is inserted between the percent sign (%) and the conversion specifier in the conversion specification.  Function printf() also provides the ability to specify the precision with which data is printed.  Precision has different meanings for different data types.  The following is a program example. // printing integers right-justified #include <stdio.h> int main() { printf(" Printing integers right-justified.n"); printf("Compare the output with the source coden"); printf("---------------------------------------nn"); printf("%4dn", 1); printf("%4dn", 12); printf("%4dn", 123); printf("%4dn", 1234); printf("%4dnn", 12345); printf("%4dn", -1); printf("%4dn", -12); printf("%4dn", -123); printf("%4dn", -1234); printf("%4dn", -12345); return 0; } Output:  Another example: // using precision while printing integers, floating-point numbers and strings #include <stdio.h> int main() { int i = 873; float f = 123.94536; chars[ ] = "Happy Birthday"; printf("Using precision while printing integers,n"); printf(" floating-point numbers, and strings.n"); printf("Compare the output with the source coden"); printf("----------------------------------------nn"); printf("Using precision for integersn"); printf("t%.4dnt%.9dnn", i, i); printf("Using precision for floating-point numbersn"); printf("t%.3fnt%.3ent%.3gnn", f, f, f); printf("Using precision for stringsn"); printf("t%.11sn", s); return 0; } Output:  By using asterisk (*), it is also can be like this: printf("%*.*f", 7, 2, 98.736)  This statement uses 7 for the field width, 2 for the precision and will output the value 98.74 right-justified. 5.9 Using Flags In The printf() Format Control String  Flags used to supplement its output formatting capabilities.  Five flags are available to be used in format control string as shown in table 5.4 then followed by program examples. Flag Description - (minus sign) Left-justify the output within the specified field + (plus sign) Display a plus sign preceding positive values and a minus sign preceding negative values. space Print a space before a positive value not printed with the + flag. # Prefix 0 to the output value when used with the octal conversion specifier o. Prefix 0x or 0X to the output value when used with the hexadecimal conversion specifiers x or X. Force a decimal points for a floating-point number printed with e, E, f, g, or G that does not contain a fractional part. (Normally the decimal point is only printed if a digit follows it). For g and Gspecifiers, trailing zeros are not eliminated. 0 (zero) Pad a field with leading zeros. Table 5.4: Format control string flags // right justifying and left justifying values #include <stdio.h> int main() {
  • 24. printf("Right justifying and left justifying values.n"); printf(" Compare the output with the source code.n"); printf("--------------------------------------------nn"); printf("%10s%10d%10c%10fnn", "hello", 7, 'a', 1.23); printf("%-10s%-10d%-10c%-10fn", "hello", 7, 'a', 1.23); return 0; } Output:  More program example: // printing numbers with and without the + flag #include <stdio.h> int main() { printf("Printing numbers with and without the + flag.n"); printf(" Compare the output with the source coden"); printf("---------------------------------------------nn"); printf("%dn%dn", 786, -786); printf("%+dn%+dn", 786, -786); return 0; } Output:  Another example: // printing a space before signed values not preceded by + or - #include <stdio.h> int main() { printf("Printing a space before signed valuesn"); printf(" not preceded by + or -nn"); printf("--------------------------------------nn"); printf("% dn% dn", 877, -877); return 0; } Output:  More program example: // o, x, X, and any floating-point specifier #include <stdio.h > int main() { int c = 1427; float p = 1427.0; printf("o, x, X, and any floating-point specifiersn"); printf("Compare the output with the source coden"); printf("-----------------------------------------nn"); printf("%#on", c); printf("%#xn", c); printf("%#Xn", c); printf("n%#gn", p); printf("%#Gn", p); return 0; } Output:  Program example again. // printing with the 0 (zero) flag fills in leading zeros #include <stdio.h> int main() { printf("Printing with the 0 (zero) flag fills in leading zerosn"); printf(" Compare the output with the source coden"); printf("-------------------------------------------------------nn"); printf("%+09dn", 762); printf("%09d", 762); printf("n"); return 0; } Pr ed ef i n ed F u n c ti o n s Using predefined functions:  C++ Standard Library contains many predefined functions to perform various operations  Predefined functions are organized into separate libraries  I/O functions are in iostream header  Math functions are in cmath header  Some predefined C++ mathematical functions: o pow(x,y) o sqrt(x) o floor(x)  Power Function - pow(x,y): o Power function pow(x,y) has two parameters o pow(x,y) returns value of type double o pow(x,y) calculates x to the power of y: pow(2,3) = 8.0 o x and y called parameters (or arguments) of function pow  Square Root Function - sqrt(x): o Square root function sqrt(x) has only one parameter o sqrt(x) returns value of type double o sqrt(x) calculates non-negative square root of x, for x >= 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
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31. C Reference Card (ANSI) 2(cheat sheet) ANSI Standard Libraries <assert.h> <ctype.h> <errno.h> <float.h> <limits.h> <locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h> <stddef.h> <stdio.h> <stdlib.h> <string.h> <time.h> Mathematical Functions <math.h> 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 }
  • 32. libraries #include <stdio.h> input and output functions #include <string.h> string related functions #include <stdlib.h> memory allocation, rand, and other functions #include <math.h> math functions #include <time.h> time related functions Working With Numbers int i = 0; // convertfroma string int i = int.Parse("1"); // convertfroma string and don’t 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 <header> 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
  • 33. 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
  • 34. 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
  • 35.
  • 36. 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 (==, !=, >.<, >=, <=) • Logical Operators (&&, ||, ! ) • Bitwise Operators (& |, ^ , ~, <<, >>) • Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^ =, |=) • Misc Operators ( sizeof, & cast, comma, conditional etc.) Loop Type C++ Decision Making While loop If statement Do-while loop If…else statement For loop switch statement Nested loop Nested if statement Nested switch statement A C++ function definition consists of a function header and a function body. Here are all the parts of a function:  Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.  Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.  Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.  Function Body: The function body contains a collection of statements that define what the function does. statements One way Return way Statements A statement is a building block of a program Conditional control statements(if, if else, ladder if, switch.. case ) Iterative control statements ( for, while, do .. while) Unconditional control statements (goto, continue, break) flow control/ control statements Branching Looping Branching is deciding what actions to take looping is deciding how many times to take a certain action
  • 37. Difference between three loops If you use "continue" in a "for" loop, it will still increment the variable. But if you use continue inside a "while" loop with counter, then it will turn into an infinite loop. While Do-while for a while loop repeats as long as a certain condition is true a for loop repeats for a predefined number of times http://www.programiz.com/c-programming/c-do-while-loops http://www.programiz.com/c-programming/c-do-while-loops loop in c programming http://www.programiz.com/c-programming/c-for-loop for (Start value; continue or end condition; increase value) statement; prefix incrementing (++i) or postfix incrementing (i++) Looping Classification(i++, i=i+1, ++i, i+=1) While loop Do-while loop For loop Result while(){} do{} while(); for(){} http://www.c4learn.com/c-programming/c-while-loop/ http://www.c4learn.com/c-programming/c-do-while-loop/ http://www.c4learn.com/c-programming/c-for-loop-types/ While Loop Syntax : initialization; while(condition) { ---------- ---------- ---------- ---------- ---------- Do-While Loop Syntax : initialization; do { -------------- -------------- -------------- -------------- incrementation; Understanding Looping Statement : Whenever we need to execute certain action multiple times, we need to wrap programming statement in the loop body. Take an example we are computing the sum of 2 numbers 5 times then we need to write code in the loop body. Consider the following trailer - for(i=0; i<5; i++) { printf("nEnter two Numbers : "); scanf("%d %d",num1,num2); ans = num1 + num2;
  • 38. ------ incrementation; } Note :  For Single Line of Code – Opening and Closing braces are not needed.  while(1) is used for Infinite Loop  Initialization , Incrementation and Condition steps are on different Line.  While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then only code is executed ] }while(condition); Note :  It is Exit Controlled Loop.  Initialization , Incrementation and Condition steps are on different Line.  It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute at least once ] printf("nAddition of 2 Numbers is %d"); } Syntax of the For Loop : for(initial expression; test expression; update expression) { body of loop; } We will get better idea after looking at above for loop flowchart. Flowchart of For Loop : Explanation of For Loop : 1. Firstly the for loop executes the initialize statement in which the subscript variable will be initialized with the initial value. 2. After the initialize statement the condition part of the loop will be executed if the condition becomes true then body of the loop will be executed otherwise the loop will be terminated 3. If the loop condition becomes true then body of the loop will be executed. After the execution of the for loop body the control goes to the third part of the loop statement i.e Expression Updation 4. After updating subscript variable control again goes to execute condition statement. For Loop : Dry Run Consider the following image then - Sequence of the execution will be as below - Seq. No Statement Flow Explanation 01 Flow No 1 will be executed i = 0 02 Flow No 2 will be executed Condition Checking 03 Flow No 3 will be executed True Condition 04 Flow No 4 will be executed - 05 Flow No 5 will be executed i = 1 06 Flow No 3 will be executed True Condition 07 Flow No 4 will be executed - 08 Flow No 5 will be executed i = 2
  • 39. 09 Flow No 3 will be executed True Condition 10 Flow No 4 will be executed - 11 Flow No 5 will be executed i = 3 12 Flow No 3 will be executed True Condition 13 Flow No 4 will be executed - 14 Flow No 5 will be executed i = 4 15 Flow No 3 will be executed True Condition 16 Flow No 4 will be executed - 17 Flow No 5 will be executed i = 5 18 Flow No 3 will be executed False Condition Note : 1. For Single Line of Code – Opening and Closing braces are not needed. 2. There can Exist For Loop without body. 3. Initialization , Incrementation and Condition steps are on same Line. 4. Like While loop , For Loop is Entry Controlled Loop.[i.e conditions are checked if found true then and then only code is executed ] Different Ways of Infinite While Loop in C We can use While loop for looping purpose. We can use infinite while loop in C to iterate loop for infinite times. We can Even use Infinite while loop for operation in which we cannot decide how many iteration does it take at compile time. Way 1 : Semicolon at the end of While #include<stdio.h> void main() { int num=300; while(num>255); //Note it Carefully printf("Hello"); } Output : It won't Print anything Explanation of Above Infinite Loop : 1. In the above program , Condition is specified in the While Loop 2. Semicolon at the end of while indicated while without body. 3. In the program variable num doesn’t get incremented , condition remains true forever. 4. As Above program does not have Loop body , It won’t print anything Way 2 : Non-Zero Number as a Parameter #include<stdio.h> void main() { while(1) printf("Hello"); } Output : Infinite Time "Hello" word How ? 1. Note : We can specify any Non-Zero Positive Number inside while 2. Non Zero is specified in the While Loop means Loop will have always TRUE condition specified inside. 3. As condition inside loop doesn’t get changed ,condition inside while remains true forever. Way 3 : Subscript Variable Remains the same #include<stdio.h> void main() Different Ways of Using For Loop in C Programming In order to do certain actions multiple times , we use loop control statements. For loop can be implemented in different verities of using for loop - 1. Single Statement inside For Loop 2. Multiple Statements inside For Loop 3. No Statement inside For Loop 4. Semicolon at the end of For Loop 5. Multiple Initialization Statement inside For 6. Missing Initialization in For Loop 7. Missing Increment/Decrement Statement 8. Infinite For Loop 9. Condition with no Conditional Operator. Way 1 : Single Statement inside For Loop for(i=0;i<5;i++) printf("Hello"); 1. Above code snippet will print Hello word 5 times. 2. We have single statement inside for loop body. 3. No need to wrap printf inside opening and closing curly block. 4. Curly Block is Optional. Way 2 : Multiple Statements inside For Loop for(i=0;i<5;i++) { printf("Statement 1"); printf("Statement 2"); printf("Statement 3"); if(condition)
  • 40. { int num=20; while(num>10) { printf("Hello"); printf(" C "); } } Output : Infinite Time "Hello C" word How ? 1. Condition is specified in while Loop ,but Terminating Condition is not specified 2. Also Subscript Variable [Variable used to Repeat action] is also not either incremented or decremented 3. so while remains true forever. Way 4 : Character as a Parameter in While Loop #include<stdio.h> void main() { while('A') printf("Hello"); } Output : Infinite Time "Hello" word How ? 1. Character is Represented in integer in the form of ASCII internally. 2. Any Character is Converted into Non-zero Integer ASCII value 3. Any Non-zero ASCII value is TRUE condition , that is why Loop executes forever How to Break Infinite While Loop : Whenever you decide to use infinite while loop while writing code , you must include terminating or ending condition in a while loop to ensure that your code will be terminated at some moment of time. while(1) { ch = fgetc(fp); printf("%c",ch); fp++; if(ch == 'EOF') break; } In the Above program we cannot decide , size of file while writing program so we decided to go with infinite while loop. Our main purpose is to read file so we have provided breaking condition inside loop which will takes control out of loop. { -------- -------- } } If we have block of code that is to be executed multiple times then we can use curly braces to wrap multiple statement in for loop. Way 3 : No Statement inside For Loop for(i=0;i<5;i++) { } this is bodyless for loop. It is used to increment value of “i”.This verity of for loop is not used generally. At the end of above for loop value of i will be 5. Way 4 : Semicolon at the end of For Loop for(i=0;i<5;i++); 1. Generally beginners thought that , we will get compile error if we write semicolon at the end of for loop. 2. This is perfectly legal statement in C Programming. 3. This statement is similar to bodyless for loop. (Way 3) Way 5 : Multiple Initialization Statement inside For for(i=0,j=0;i<5;i++) { statement1; statement2; statement3; } Multiple initialization statements must be seperated by Comma in for loop. Way 6 : Missing Increment/Decrement Statement for(i=0;i<5;) { statement1; statement2; statement3; i++; } however we have to explicitly alter the value i in the loop body. Way 7 : Missing Initialization in For Loop i = 0; for(;i<5;i++) { statement1; statement2; statement3; } we have to set value of ‘i’ before entering in the loop otherwise it will take garbage value of ‘i’. Way 8 : Infinite For Loop i = 0; for(;;) { statement1; statement2; statement3; if(breaking condition) break; i++; } Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause overflow of stack. Summary of Different Ways of Implementing For Loop Form Comment for ( i=0 ; i < 10 ; i++ ) Statement1; Single Statement for ( i=0 ;i <10; i++) { Statement1; Statement2; Statement3; } Multiple Statements within for for ( i=0 ; i < 10;i++) ; For Loop with no Body ( Carefully Look at the Semicolon )
  • 41. for (i=0,j=0;i<100;i++,j++) Statement1; Multiple initialization & Multiple Update Statements Separated by Comma for ( ; i<10 ; i++) Initialization not used for ( ; i<10 ; ) Initialization & Update not used for ( ; ; ) Infinite Loop,Never Terminates #include<stdio.h> int main(void){ int a=2; while(a<21){ printf("%dn",a); a=a+1; } } #include<stdio.h> int main(void){ int a=2; do{ printf("%dn",a); a=a+1; } while(a<21); } #include<stdio.h> int main(void){ int a; for(a=2;a<21;a++){ printf("%dn",a); } } 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include<stdio.h> int main(void){ int a=9; while(a>0){ printf("%dn",a); a--; } } #include<stdio.h> int main(void){ int a=9; do{ printf("%dn",a); a--; } while(a>0); } #include<stdio.h> int main(void){ int a; for(a=9;a>0;a--){ printf("%dn",a); } } 9 8 7 6 5 4 3 2 1 #include<stdio.h> int main(void){ int a=0; while(a<12){ printf("%dn",a); a=a+2; } } #include<stdio.h> int main(void){ int a=0; do{ printf("%dn",a); a=a+2; } while(a<12); } #include<stdio.h> int main(void){ int a; for(a=0;a<12;a=a+2){ printf("%dn",a); } } 0 2 4 6 8 10 #include<stdio.h> int main(void){ int a=12; while(a>0){ printf("%dn",a); a=a-2; } } #include<stdio.h> int main(void){ int a=12; do{ printf("%dn",a); a=a-2; } while(a>0); } #include<stdio.h> int main(void){ int a; for(a=12;a>0;a=a-2){ printf("%dn",a); } } 12 10 8 6 4 2 #include<stdio.h> int main(void){ int a; for(a=1;a<=15;a++){ printf("%dn", (a%2)*(-4)+2); } } -2 2 -2 2 -2 2 -2 2 -2 2 -2 2 -2 2 -2 #include<stdio.h> int main(void){ #include<stdio.h> int main(void){ #include<stdio.h> int main(void){ 1 -1 1
  • 42. int a=0; while(a<10){ printf("%dn", (a%2)*(-2)+1); a++; } } int a=0; do{ printf("%dn", (a%2)*(-2)+1); a++; } while(a<10); } int a; for(a=0;a<10;a++){ printf("%dn", (a%2)*(-2)+1); } } -1 1 -1 1 -1 1 -1 #include<stdio.h> int main(void){ int a=0; while(a<10){ printf("%dn", (a%2)*6+4); a++; } } #include<stdio.h> int main(void){ int a=0; do{ printf("%dn", (a%2)*6+4); a++; } while(a<10); } #include<stdio.h> int main(void){ int a; for(a=0;a<10;a++){ printf("%dn", (a%2)*6+4); } } 4 10 4 10 4 10 4 10 4 10 #include<stdio.h> int main(void){ int a=0; while(a<10){ printf("%cn", a%4+97); a++; } } #include<stdio.h> int main(void){ int a=0; do{ printf("%cn", a%4+97); a++; } while(a<10); } #include<stdio.h> int main(void){ int a; for(a=0;a<10;a++){ printf("%cn", a%4+97); } } a b c d a b c d a b #include<stdio.h> int main(void){ int a=0; while(a<10){ printf("%cn", (a%2)*6+97); a++; } } #include<stdio.h> int main(void){ int a=0; do{ printf("%cn", (a%2)*6+97); a++; } while(a<10); } #include<stdio.h> int main(void){ int a; for(a=0;a<10;a++){ printf("%cn", (a%2)*6+97); } } a g a g a g a g a g #include<stdio.h> int main(void){ int a=1; while(a<10){ printf("%cn", a%4+97); a++; } } #include<stdio.h> int main(void){ int a=1; do{ printf("%cn", a%4+97); a++; } while(a<10); } #include<stdio.h> int main(void){ int a; for(a=1;a<10;a++){ printf("%cn", a%4+97); } } b c d a b c d a b #include<stdio.h> int main(){ int a; for(a=0;a<20;a++){ printf("%dn", (a%6)*(-4)+10); } } 10 6 2 -2 -6 -10 10 6 2 -2 -6 -10 10 6 2 -2 -6 -10 10 6 #include<stdio.h> int main(void){ int a; for(a=0;a<10;a++){ printf("%c", a%4+65); Abcd Bbcd Cbcd Dbcd Abcd Bbcd Cbcd Dbcd Abcd Bbcd
  • 43. printf("bcd "); } } #include<stdio.h> int main(void){ int a; for(a=0;a<10;a++){ printf(""%c", a%4+65); printf("bcd" "); } } "Abcd" "Bbcd" "Cbcd" "Dbcd" "Abcd" "Bbcd" "Cbcd" "Dbcd" "Abcd" "Bbcd" #include<stdio.h> int main(void){ int i='d'; while(i>='a'){ printf("%cn", i); i--; } } #include<stdio.h> int main(void){ int i='d'; do{ printf("%cn", i); i--; } while(i>='a'); } #include<stdio.h> int main(void){ int i; for(i='d';i>='a';i--){ printf("%cn", i); } } #include<stdio.h> int main(void){ int a,b; for(a=0;a>-4;a--){ printf("%cn", (a%4)+100); } } d c b a #include<stdio.h> int main(void){ int i=0; while(i<6){ printf("%dn", i+i*1+1); i++; } } #include<stdio.h> int main(void){ int i=0; do{ printf("%dn", i+i*1+1); i++; } while(i<6); } #include<stdio.h> int main(void){ int i; for(i=0;i<6;i++){ printf("%dn", i+i*1+1); } } #include<stdio.h> int main(void){ int i; for(i=1;i<12;i+=2){ // i+=2/i=i+2 printf("%dn", i); } } 1 3 5 7 9 11 #include<stdio.h> int main(void){ int i='d'; while(i>='a'){ printf("%cn", i); i--; } } #include<stdio.h> int main(void){ int i='d'; do{ printf("%cn", i); i--; } while(i>='a'); } #include<stdio.h> int main(void){ int i; for(i='d';i>='a';i--){ printf("%cn", i); } } d c b a #include<stdio.h> int main(void){ int i=0; while(i<6){ printf("%dn", i+i*1+1); i++; } } #include<stdio.h> int main(void){ int i=0; do{ printf("%dn", i+i*1+1); i++; } while(i<6); } #include<stdio.h> int main(void){ int i; for(i=0;i<6;i++){ printf("%dn", i+i*1+1); } } 1 3 5 7 9 11 #include<stdio.h> int main(void){ int i=0; while(i<=5){ printf("%dn", i+i*1+2); i++; } } #include<stdio.h> int main(void){ int i=0; do{ printf("%dn", i+i*1+2); i++; } while(i<=5); } #include<stdio.h> int main(void){ int i; for(i=0;i<=5;i++){ printf("%dn", i+i*1+2); } } 2 4 6 8 10 12 #include<stdio.h> int main(void){ int i=0,j=1; while(i<=5,j<=6){ printf("%dn",(i%2*(-2)+1)*j ); i++,j++; } #include<stdio.h> int main(void){ int i=0,j=1; do { printf("%dn",(i%2*(-2)+1)*j ); i++,j++; } #include<stdio.h> int main(void){ int i,j; for(i=0,j=1;i<=5,j<=6;i++,j++){ printf("%dn",(i%2*(-2)+1)*j ); } 1 -2 3 -4 5 -6
  • 44. } while(i<=5,j<=6); } } #include<stdio.h> int main(void){ int i=0,j=1; while(i<=5,j<=6){ printf("%dn",(i%2*(-2)+1)*j ); i++,j++; } } #include<stdio.h> int main(void){ int i=0,j=1; do { printf("%dn",(i%2*(-2)+1)*j ); i++,j++; } while(i<=5,j<=6); } #include<stdio.h> int main(void){ int i,j; for(i=0,j=1;i<=5,j<=6;i++,j++){ printf("%dn",(i%2*(-2)+1)*j ); } } #include<stdio.h> int main(void){ int i; for(i=1; i<=6; i++){ if(i%2==0){ printf("%dn", -i); } else printf("%dn", i); } } 1 -2 3 -4 5 -6 # l.oidus<edulcni< int main(void){ int i; for(i=1; i<=10; i++){ if(i<4){ printf(""a%c" ", i%3+97); } else if(i<7){ printf(""b%c" ", i%3+97); } else if(i<10){ printf(""c%c" ", i%3+97); } else printf(""d%c" ", i%3+97); } } "ab" "ac" "aa" "bb" "bc" "ba" "cb" "cc" "ca" "db" #include<stdio.h> int main() { int i = 0;; while( i < 10) { printf ("Hello worldn"); i++; } } #include<stdio.h> int main() { int i = 0;; do { printf ("Hello worldn"); i++; } while( i < 10); } #include<stdio.h> int main() { int i; for (i = 0; i < 10; i++) { printf ("Hello worldn"); } } Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world #include<stdio.h> int main() { int i = 0;; while( i < 10) { printf ("Hello worldn"); printf ("I'mdown heren"); i++; } } #include<stdio.h> int main() { int i = 0; do { printf ("Hello worldn"); printf ("I'mdown heren"); i++; } while( i < 10); } #include<stdio.h> int main() { int i; for(i= 0; i < 10; i++) { printf ("Hello worldn"); printf ("I'mdown heren"); } } Hello world I'mdown here Hello world I'mdown here Hello world I'mdown here Hello world I'mdown here Hello world I'mdown here Hello world I'mdown here Hello world I'mdown here Hello world I'mdown here Hello world I'mdown here Hello world I'mdown here #include<stdio.h> int main() #include<stdio.h> int main() #include<stdio.h> While, do while(6) For(6)
  • 45. { int counter = 0, howmuch; scanf("%d", &howmuch); while ( counter < howmuch) { counter++; printf("%dn", counter); } } { int counter = 0, howmuch; scanf("%d", &howmuch); do { counter++; printf("%dn", counter); } while ( counter < howmuch); } int main() { int counter, howmuch; scanf("%d", &howmuch); for(counter=0 ;counter < howmuch;++counter) { printf("%dn", counter); } } 1 2 3 4 5 6 0 1 2 3 4 5 #include<stdio.h> int main(void) { int i; i = 0; while(i++ < 5) { printf("%dn", i); } printf("n"); i = 0; while(++i < 5) { printf("%dn", i); } } #include<stdio.h> int main(void) { int i; i = 0; do { printf("%dn", i); } while(i++ < 5); printf("n"); i = 0; do { printf("%dn", i); } while(++i < 5); } #include<stdio.h> int main(void) { int i; for(i = 0;i++ < 5;) { printf("%dn", i); } printf("n"); for(i=0;++i<5;) { printf("%dn", i); } } While/for 1 2 3 4 5 1 2 3 4 Do while 0 1 2 3 4 5 0 1 2 3 4 #include<stdio.h> int main() { int i=0,j=2; while (i<=11){ printf("%d ",(i%4)*j+j); i++; } } #include<stdio.h> int main() { int i=0,j=2; do { printf("%d ",(i%4)*j+j); i++; } while (i<=11); } #include<stdio.h> int main() { int i,j; for (i=0,j=2;i<=11;i++) printf("%d ",(i%4)*j+j); } 2 4 6 8 2 4 6 8 2 4 6 8 #include <stdio.h> int main(){ int a; for(a=0;a<14;a++){ if(a%3==0){ printf("%d ", a%3+2); } else if(a%3==1){ printf("%d ", a%3+6); } else if (a%3==2){ printf("%d ", a%3+1); } } } 2 7 3 2 7 3 2 7 3 2 7 3 2 7 #include <stdio.h> int main(){ int a; for(a=0;a<14;a++){ if(a%3==0){ printf("%d ", a%3+2); } else if(a%3==1){ printf("%d ", a%3+6); } else{ printf("%d ", a%3+1); } } } 2 7 3 2 7 3 2 7 3 2 7 3 2 7 #l.oidus <stdio.h> int main(){ int a; for(a=2; a<=9; a++) { if(!(a==2 || a==7 || a==9) ){ continue; } else { printf("%d ", a); } } } 2 7 9 #include <stdio.h> int main(){ int a; for(a=2; a<=9; a++) { if(a>2 && a<7){ continue; } else if(a==7){ printf("%d ",a); } else if(a==8){ continue; } else{ printf("%d ",a); 2 7 9
  • 46. // for “and” every condition mustbe true if we wantit's a true // for “or” only one condition has to be true } } } #include<stdio.h> int main(viod){ int f1, f2, f; printf("1 "); for(f1=0,f2=1,f=f1+f2; f<=99; ){ printf("%d ", f); f1 = f2; f2 = f; f = f1+2*f2; } } 1 1 3 7 17 41 99 #include<stdio.h> int main(){ int a = 0, b = 1, c ; printf("0 1 "); for(c = 1; c<100; ){ printf("%d ", c); a = b; b = c; c = a+b; } } #include<stdio.h> int main(){ int a = -1, b = 0, c; printf("0 "); for(c = 1; c<100; ){ printf("%d ", c); a = b; b = c; c = a+b; } } 0 1 1 2 3 5 8 13 21 34 55 89 Fibonacci series
  • 47.
  • 48.
  • 49.
  • 50. Nested loop in c While nested loop Do-while nested loop For nested loop Result
  • 51. while(condition) { while(condition) { statement(s); } statement(s); } do { statement(s); do { statement(s); }while( condition ); }while( condition ); for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } "nested for loop statement" for(initialization condition; increment/decrement) { for(initialization;condition;increment/decrement) { statement perform while the condition is true } statement perform while the condition is true } for ( initialization ; condition ; updating) { // Starting of outer loop for ( initialization ; condition ; updating) { // Starting of inner loop Statement / Statements ; } Statement / Statements ; } Outer = column Inner = row #include <stdio.h> int main() { int k, j, i,l, m, n; for(i=0; i<1; i++) for(k=1; k<9; k++) printf("%d",k); 12345678 23456789 345678910 4567891011 56789101112 #include <stdio.h> int main () { int i,j; for(i=1; i<6; i++) { for(j=5; j>=i; j--) 54321 5432 543 54 5
  • 52. printf("nn"); for(j=2; j<10; j++) printf("%d",j); printf("nn"); for(l=3; l<11; l++) printf("%d", l); printf("nn"); for(m=4; m<12; m++) printf("%d", m); printf("nn"); for(n=5; n<13; n++) printf("%d", n); return 0; } { printf("%d",j); } printf("n"); } } #include <stdio.h> int main () { int i,j; for(i=1; i<6; i++) { for(j=5; j>=i; j--) { printf("%d",i); } printf("n"); } } 11111 2222 333 44 5 #include <stdio.h> int main(void) { int a = 1; int b = 0; int c = 8; for(a = 1; a <= 5; a++) { for(b = a; b <= c; b++) { printf("%d ", b); } c++; putchar('n'); } getchar(); return 0; } 1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9 10 4 5 6 7 8 9 10 11 5 6 7 8 9 10 11 12 #include <stdio.h> int main () { int i,j; for(i=1; i<6; i++) { for(j=5; j>=i; j--) { printf("%d",i); } printf("n"); } } 11111 2222 333 44 5 #include <stdio.h> int main(void) { int a; for(a = 0; a <= 19; a++) { if (a%8>=0 && a%8<=2){ a a a c c h h h a a a c c h h h a a a c #include <stdio.h> int main () { int i, j; for(i=1; i<6; i++) { 1 12 123 1234 12345
  • 53. printf("a "); } else if (a%8>=3 && a%8<=4){ printf("c "); } else if (a%8>=5 && a%8<=7){ printf("h "); } } } for(j=1; j<=i; j++) { printf("%d", j); } printf("n"); } } #include <stdio.h> int main(void) { int a,b; for(a = 0, b=6; a <= 21; a++) { if (a%6>=0 && a%6<=2){ printf("a "); } else if (a%6>=3 && a%6<=4){ printf("b "); } else{ printf("%d ",b); b++; } } } a a a b b 6 a a a b b 7 a a a b b 8 a a a b #include <stdio.h> int main () { int i,j; for(i=1; i<6; i++) { for(j=1; j<=i; j++) { printf("%d",j); } printf("n"); } } 1 12 123 1234 12345 #include <stdio.h> int main () { int i,j; for(i=1; i<6; i++) { for(j=1; j<=i; j++) { printf("%d",i); } printf("n"); } } 1 22 333 4444 55555 #include <stdio.h> int main(void) { int a,b; for(a = 0, b=5; a <= 23; a++) { if (a%8>=0 && a%8<=1){ printf("a "); } else if (a%8>=2 && a%8<=4){ printf("k "); } else if (a%8>=5 && a%8<=6){ printf("m "); } a a k k k m m 5 a a k k k m m 7 a a k k k m m 9 #include <stdio.h> int main () { int col,row; for(row=1;row<8;row++){ for(col=1;col<=row;col++){ printf("%d ", row); } printf("n"); } } 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7
  • 54. else { printf("%d ",b); b+=2; } } } #include <stdio.h> int main(void) { int a,b; for(a = 0; a <= 15; a++) { printf("%d ", a/4+4); } } 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 #include <stdio.h> int main () { for( int row=1;row<8;row++){ for( int col=1;col<=row;col++){ printf("%d ", col); } printf("n"); } } 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 #include <stdio.h> int main(void) { int a,b; for(a = 0; a <= 15; a++) { printf("%c ", a/3*2+97); } } a a a c c c e e e g g g i i i k #include <stdio.h> int main () { int col,row; for(row=1;row<=8;row++){ for(col=1;col<=row;col++){ printf("*"); } printf("n"); } } * ** *** **** ***** ****** ******* ******** #include <stdio.h> int main () { int col,row; for(row=0;row>-4;row--){ for(col=0;col>=row;col--){ printf("%c",row*2+90); } printf("Dn"); } } ZD XXD VVVD TTTTD http://www.cquestions.com/2009/10/nested- loop-in-c-programming.html #include <stdio.h> int main () { int col,row; for(row=1;row<=6;row++){ for(col=6;col>=row;col--){ printf("%d ",col); } printf("n"); } } 6 5 4 3 2 1 6 5 4 3 2 6 5 4 3 6 5 4 6 5 6 #include <stdio.h> int main(void) { int c, r; for(c = 5; c >= 1; c--) { for(r = 5; r >= c; r--){ 5 5 4 5 4 3 5 4 3 2 #include <stdio.h> int main(void) { int c; static r; for(c = 1; c <= 6; c++) { * * * * * *
  • 55. printf("%d ", r); } printf("n"); } } 5 4 3 2 1 for(r = 1; r <= 6-c; r++){ printf(" "); } printf("* ", r); printf("n"); } } #include <stdio.h> int main(void) { int c; static r; for(c = 1; c <= 6; c++) { for(r = 1; r <= 6-c; r++){ printf(" "); printf("* ", r); } printf("n"); } } * * * * * * * * * * * * * * * #include <stdio.h> int main(void) { int c, r; for(c = 1; c <= 6; c++) { for(r = 1; r <= 6-c; r++){ printf(" ", r); } for(r = 1; r <= c+c-1; r++){ printf("*"); } printf("n"); } } * *** ***** ******* ********* *********** #include <stdio.h> int main(void) { int c, r; for(c = 5; c >= 1; c--) { for(r = 5; r >= c; r--){ printf("%d ", r); } printf("n"); } } 5 5 4 5 4 3 5 4 3 2 5 4 3 2 1 #include <stdio.h> int main(void) { int c; static r; for(c = 0; c <= 20; c++) { for(r = 0; r <=20 ; r++){ if (r%4-1 == (c+r-1)%4 ){ printf("*", r); } else printf("O"); } printf("n"); } }
  • 56. #include <stdio.h> int main(void) { int c; static r; for(c = 0; c <= 20; c++) { for(r = 0; r <=20 ; r++){ if ( ((r/4)%2 == 0) || ((c/4)%2 == 0) ){ printf("*", r); } else printf("O"); } printf("n"); } } #include <stdio.h> int main(void) { int c; static r; for(c = 0; c <= 20; c++) { for(r = 0; r <=20 ; r++){ if ( ((r/4)%2 == 0)){ printf("*", r); } else printf("O"); } printf("n"); } } #include <stdio.h> int main(void) { int c; static r; for(c = 0; c <= 20; c++) { for(r = 0; r <=20 ; r++){ if ( ((r/4)%2 == 0) || ((c/4)%2 != 0) ){ printf("*", r); } else printf("O"); } printf("n"); } } #include <stdio.h> int main(void) { int c,r; for(c = 0; c <= 20; c++) { for(r = 0; r <=20 ; r++){ if ( ((r/4)%2 == 0) && ((c/4)%2 != 0) ){ printf("*", r); } else if ( ((r/4)%2 == 0) || ((c/4)%2 != 0) ){ printf("O"); } else printf("*", r); } printf("n"); } } #include<stdio.h> int main(){ int r, c, n; printf("Enter the numbersyou wants to multiplication = "); scanf("%d",&n); for(r=1; r<=n; r++){ for(c=1; c<=n;c++){ if(r<2){ printf("%dt", c); } else{ printf("%dt", r*c); } } printf("n"); } } Enter the numbers you wants to multiplication = 5 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 #include<stdio.h> int main(){ Enter the numbers you wants to multiplication= 5 #include<stdio.h> int main(){ Enter the numbers you wants to multiplication= 5
  • 57. int r, c, n; printf("Enter the numbersyou wants to multiplication = "); scanf("%d",&n); printf("n"); for(r=1; r<=n; r++){ printf("%dt", r); } printf("n"); for(r=1; r<=n; r++){ printf("========"); } printf("n"); for(r=1; r<=n; r++){ for(c=1; c<=n;c++){ if(r<2){ printf("%dt", c); } else{ printf("%dt", r*c); } } printf("n"); } } 1 2 3 4 5 ==================== 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 int r, c, n; printf("Enter the numbersyou wants to multiplication = "); scanf("%d",&n); printf("n t"); for(r=1; r<=n; r++){ printf("%dt", r); } printf("n"); for(r=1; r<=n; r++){ printf("========="); } printf("n"); for(r=1; r<=n; r++){ printf("%d |t",r); for(c=1; c<=n;c++){ if(r<2){ printf("%dt", c); } else{ printf("%dt", r*c); } } printf("n"); } } 1 2 3 4 5 ========================= 1 | 1 2 3 4 5 2 | 2 4 6 8 10 3 | 3 6 9 12 15 4 | 4 8 12 16 20 5 | 5 10 15 20 25
  • 58.
  • 59.
  • 60. break continue The break statement will immediately jump to the end of the current block of code. The continue statement will skip the rest of the code in the current loop block and will return to the evaluation #include <stdio.h> int main(){ int i; for(i=0; i<10; i++) { if(i>5) break; printf("%d ", i); } } #include<stdio.h> int main(){ int a; for (a=0;a<=30;a++){ if(a==5){ printf("Fiven"); } else if(a==10){ printf("Tenn"); } else if(a==15){ printf("Fifteenn"); } else if(a==20){
  • 61. printf("Twentyn"); } else if(a==25 ){ printf("Twenty-Fiven"); } else if(a==30){ printf("Thirtyn"); } if(a %5==0){ continue; } printf("%dn", a); } }
  • 62.
  • 63. http://www.programmingsimplified.com/c-program-examples #include <stdio.h> int main() { printf("Hello worldn"); } #include <stdio.h> int main() { //char a="hello world"; this will not work char a[]="hello world"; printf("%s",a); } #include <stdio.h> int main() { if(printf("hello world")){} } hello world #include<stdio.h> main() { int n; printf("Enter an integer = "); #include<stdio.h> main() { int n; printf("Enter an integer = "); #include<stdio.h> main() { int n; printf("Enter an integer = "); ODD or EVEN
  • 64. scanf("%d",&n); if ( n%2 == 0 ) printf("%d is a Even numbern",n); else printf("%d is a ODD numbern",n); } scanf("%d",&n); if ( n & 1== 1) printf("%d is an odd numbern",n); else printf("%d is an even numbern",n); } scanf("%d",&n); ( n & 1== 1)? printf("%d is an odd numbern",n): printf("%d is an even numbern",n); } #include<stdio.h> main() { int n; printf("Enter an integer = "); scanf("%d",&n); if ( (n/2)*2 == n ) printf("Evenn"); else printf("Oddn"); } #include <stdio.h> int main() { int year; printf("Enter a year to check if it is a leap yearn"); scanf("%d", &year); if ( year%400 == 0) printf("%d is a leap year.n", year); else if ( year%100 == 0) printf("%d is not a leap year.n", year); else if ( year%4 == 0 ) printf("%d is a leap year.n", year); else printf("%d is not a leap year.n", year); } #include <stdio.h> int main(){ int a ; printf("Input a number of a year to know if it is a leap year or not = "); scanf("%d", &a ); if(a%400==0){ printf(" leap year"); } else if(a%100==0){ printf("not leap year"); } else if (a%4==0){ printf("leap year"); } else if(a%4!=0){ printf("not leap year"); } else printf("not leap year"); } Leap Year #include <stdio.h> #include <stdlib.h> main() { char ch; printf("Do you want to know yourip address (y/n) = "); scanf("%c",&ch); if (ch == 'y' ) system("c:windowssystem32ipconfig"); } Ip Address #include <stdio.h> #include <stdlib.h> main() { char ch; printf("Do you want to shutdown yourcomputer (y/n) = "); scanf("%c",&ch); if(ch=='y') system("c:windowssystem32shutdown /s"); else printf("Thanks"); return 0; } Shutdown #include <stdio.h> main() { char ch[10000]; printf("Input an string line to reverse = "); gets(ch); strrev(ch); printf("%s",ch); } string line to reverse #include <stdio.h> #include <stdlib.h> main() { char ch; printf("Do you want to know yourip address (y/n) = "); scanf("%c",&ch); if (ch == 'y' ) system("c:windowssystem32ping"); } Ping ipconfig ping msinfo32 cmdkey.exe calc.exe ARP.EXE attrib.exe auditpol.exe cacls.exe net user net user saifur * net user saifur (look what’s the user name of you computer)*
  • 66.
  • 67.
  • 68.
  • 69.
  • 70. 1. Write a for loop to print the following: -4 -3 -2 -1 0 1 2 3 4 5 6 7 #include <stdio.h> int main(){ int i; for(i=-4; i<=7; i++) { printf("%d ", i); } } 2. Write a loop to print the following: 3 4 5 6 7 3 4 5 6 7 3 4 5 6 7 3 4 5 6 7 3 4 5 #include <stdio.h> int main(){ int i; for(i=0; i<23; i++) { printf("%d ", i%5+3); } } 3.Write a loop to print the following: 2 4 6 8 2 4 6 8 2 4 6 8 #include <stdio.h> int main(){ int i; for(i=0; i<=11; i++) { printf("%d ", i%4*2+2); 4.Write a loop to print the following: a c e g a c e g a c e #include <stdio.h> int main(){ int i; for(i=0; i<11; i++) { printf("%c ", i%4*2+97);
  • 72.
  • 73. Built In Functions #include<stdio.h> int main() { printf("It is :: %s", ctime(t)); } #include<stdio.h> #include<time.h> int main() { time_t t = time(NULL); printf("It is :: %s", ctime(&t)); }It is :: Wed Feb 04 02:46:25 2004 It is :: Sat May 24 13:50:39 2014
  • 74.
  • 75. FUNCTION Syntax : Function Definitionin C Programming return-type function-name(parameter lists) { declarations statements return value; } /*include header file*/ /*function prototype here*/ int main(viod){ /* */ } ret-type f1(param-list){ /* */ } ret-type f2(param-list){ /* */ } #include<stdio.h> int f1(int, int); int main(viod){ int a=10, b=20, sum; sum= f1(a, b); printf("Thesumof the two integers is = %d", sum); } int f1(intx, int y){ return x+y; } #include<stdio.h> int f1(int x, int y); int main(viod){ int a=10, b=20; printf("The sum of the two integers is = %d", f1(a, b)); } int f1(int x, int y){ return x+y; } Function prototype Function prototypeis the declaration of user defined function. Which is declared before it is used & terminated by a semicolon. Only main function does not needa prototype , because it is predefinedby the C language Function Definition in C Programming I Defining a function: What is Function Definition in C Programming? 1. Functiondefinition isnothing but actualFunction. 2. FunctionCall is short term used, however functiondefinitionis“Actual Broad Elaboration” offunctioncall. 3. Functiondefinitionisdifferent from macroexpansion. 4. It contain ExecutableCode ( Executablestatements) 5. First Line is called as FunctionHeader . 6. FunctionHeader should be identicaltofunctionPrototypewith the exceptionof semicolon 7. Argument nameshasto specify here !! Syntax : Function Definitionin C Programming return-type function-name(parameter lists) { declarations statements return value; } return_type function_name(type(1) argument(1),..,type(n) argument(n)) { //body of function }1. Return type 2. Function name 3. Parameters list 4. statement