0
Upcoming SlideShare
×

# C Language Unit-1

3,055

Published on

Jntu C Langauage material, Unit-1

Published in: Education, Technology
3 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total Views
3,055
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
137
0
Likes
3
Embeds 0
No embeds

No notes for slide
• ### Transcript of "C Language Unit-1"

1. 1. Computer -- Hardware Input OutputKey board Storage Program Storage Area Storage Monitor Mouse Area Area Printer Working Storage AreaInput Devices Output Devices Primary or Main Memory (RAM) Register 1 Register 2 Arithmetic …… and …… Register N Logic Unit Micro Processor Secondary Storage Devices
2. 2. Algorithm: Step by step procedure of solving a particular problem.Pseudo code: Artificial informal language used to develop algorithms.Flow chart: Graphical representation of an algorithm.Algorithm to find whether a number even or odd:Step1: Begin Step1: STARTStep2: Take a number Step2: Read numStep3: if the number is divisible by2 then Step3: if(num%2=0) then print that number is even print num is even otherwise print that number is odd otherwise print num is oddStep4: End Step4: STOP(Algorithm in natural language) (Algorithm by using pseudo code)#include<stdio.h> start#include<conio.h> Flow chart:main() read num{ int num; printf(“Enter any number”); If num No Yes scanf(“%d”,&num); %2=0 if(num%2==0) printf(“%d is even”,num); else print num print num printf(%d is odd”,num); is even is odd}(Program in C language) stop
3. 3. Flow chart symbolsOval TerminalParallegram Input/outputRectangle ProcessDocument Hard copyDiamond DecisionCircle ConnectorDouble sided Rectangle Sub programHexagon IterationTrapezoid Manual OperationCylinder Magnetic Disk Storage
4. 4. Machine Language – Assembly Language – High-Level Language 1 00000000 00000100 0000000000000000 1 entry main,^m<r2> 2 01011110 00001100 11000010 0000000000000010 2 sub12 #12,sp 3 11101111 00010110 0000000000000101 3 jsb C\$MAIN_ARGS 4 11101111 10111110 0000000000001011 4 moveb \$CHAR_STRING_CON 5 11111000 10101101 11011111 0000000000010010 5 6 01100010 11011111 0000000000010101 6 pusha1 -8(fp) 7 11101111 00000010 11111011 0000000000010111 7 pusha1 (r2) 8 11110100 10101101 11011111 0000000000011110 8 calls #2,SCANF 9 00000011 10100010 11011111 0000000000100001 9 pusha1 -12(fp)10 11101111 00000010 11011111 0000000000100100 10 pusha1 3(r2)11 01111110 11110100 10101101 11 calls #2,SCANF12 11111000 10101110 11000101 0000000000101011 12 mull3 -8(fp),-12(fp),-13 00000110 10100010 11111011 0000000000110001 13 pusha 6(fp)14 11101111 00000010 11111011 0000000000110100 14 calls #2,PRINTF15 01010000 11010100 0000000000111011 15 clrl r016 00000100 0000000000111101 16 ret1 #include<stdio.h>2 int main(void) The only language the computer can understand is machine3 { language (binary language).4 int n1, n2,product;5 printf(“Enter two numbers : “); A high level language is an English like language where one6 scanf(“%d %d”,&n1,&n2); instruction typically translates into a series of machine-7 product = n1 * n2; language instructions.8 printf(“%d”,product);9 return 0; A low level language corresponds closely to machine code1 }0 so that a single low-level language instruction translates to a single machine language instruction.
5. 5. Structure of C program/*Program to find Documentation Section area and perimeter of Circle */#include<stdio.h> Linkage Section#define PI 3.1415 Definition Sectionfloat radius;float area(); Global Declaration Sectionfloat perimeter();int main(){ float a, p; Main Function Section printf(“Enter radius : “); scanf(“%f”,&radius); Local Declaration Part a = area(); Executable Code Part p = perimeter(); printf(“Area of Circle : %f”,a); printf(“Perimeter : %f”,p);}float area() Sub Program Section{ return (PI * radius * radius); Function1()} Function2()float perimeter() ……………{ FunctionN() return (2 * PI * radius);}
6. 6. Program Development Steps1)Statement of Problem 4.a)Compilation a) Working with existing system and using proper Translate the program into machine code. Thisquestionnaire, the problem should be explained process is called as Compilation. Syntactic errors areclearly. found quickly at the time of compiling the program. b) What inputs are available, outputs are required These errors occur due to the usage of wrongand what is needed for creating workable solution syntaxes for the statements.should be understood clearly. Eg: x=a*y+b2)Analysis There is a syntax error in this statement, since, each a) The method of solutions to solve the problem can and every statement in C language ends with abe identified. semicolon (;). b) We also judge that which method gives bestresults among different methods of solution. 4.b)Execution3)Designing The next step is Program execution. In this phase, we a) Algorithms and flow charts will be prepared. may encounter two types of errors. b) Keep focus on data, architecture, user interfaces Runtime Errors: these errors occur during theand program components. execution of the program and terminates the program abnormally.4)Implementation Logical Errors: these errors occur due to incorrect The algorithms and flow charts developed in theprevious steps are converted into actual programs in usage of the instructions in the program. These errorsthe high level languages like C. are neither detected during compilation or execution nor cause any stoppage to the program execution but produces incorrect ouz
7. 7. Executing a C program #include<stdio.h> Text int main() { Translators are system software Editor ……. prog1.c used to convert high-level language program into C-compiler compiles machine-language code. Compiler : Coverts the entire 010110 100 Syntax Yes source program at a time ……………. 01011 101 Errors? into object code file, and No saves it in secondary storage Object machine code permanently. The same adds prog1.obj object machine code file will Linker be executed several times, 00101010 Executable whenever needed. …………. 01010101 machine code Interpreter : Each statement of prog1.exe source program is translatedmachine code of library file into machine code and Executes executed immediately. C-Runtime Translation and execution of Feeds each and every statement is Runtime Yes Input or Logic repeated till the end of the Errors ? program. No object code is saved. Translation is repeated for every execution Output of the source program.
8. 8. Character Set of C-LanguageAlphabets : A-Z and a-zDigits : 0-9Special Symbols : ~ ! @ # \$ % ^ & ( ) _ - + = | { } [ ] : ; “ ‘ <>,.?/White Spaces : space , Horizontal tab, Vertical tab, New Line Form Feed. C-Language Keywords(C99) auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while _Bool _Imaginary restrict _Complex inline
9. 9. C-TokensTokens : The smallest individual units of a C- program are called Tokens. Key words, Identifiers, Constants, Operators, Delimiters.Key words : have a predefined meaning and these meanings cannot be changed. All keywords must be written in small letters (except additional c99 keywords).Identifiers : names of variables, functions, structures, unions, macros, labels, arrays etc., Rules for define identifiers : a) First character must be alphabetic character or under score b) Second character onwards alphabetic character of digit or under score. c) First 63 characters of an identifier are significant. d) Cannot duplicate a key word. e) May not have a space or any other special symbol except under score. f) C – language is Case-sensitive.
10. 10. C-TokensConstants : fixed values that do not change during execution of a program. Boolean constants : 0 ( false) and 1 (true) Character constants : only one character enclosed between two single quotes ( except escape characters ). wide character type - wchar_t - for Unicode characters. Integer constants : +123, -3454 , 0235 (octal value), 0x43d98 ( hexa - decimal value) 54764U, 124356578L, 124567856UL Float constants : 0.2 , 876.345, .345623 , 23.4E+8, 47.45e+6 String Constants : “Hello world” , “Have a nice day!” Complex Constants : real part + imaginary part * I ex : 12.3 + 3.45 * IOperators : a symbol, which indicates an operation to be performed. Operators are used to manipulate data in program.Delimiters : Language Pattern of c-language uses special kind of symbols: (colon, used for labels) ; (semicolon terminates statement ) ( ) parameter list [ ] ( array declaration and subscript ), { } ( block statement ) # ( hash for preprocessor directive ) , (comma variable separator )
11. 11. Data Types ( pre defined )Type Typical Size in Bits Minimal Rangechar 8 –127 to 127unsigned char 8 0 to 255signed char 8 –127 to 127int 16 or 32 –32,767 to 32,767unsigned int 16 or 32 0 to 65,535signed int 16 or 32 Same as intshort int 16 –32,767 to 32,767unsigned short int 16 0 to 65,535signed short int 16 Same as short intlong int 32 –2,147,483,647 to 2,147,483,647long long int 64 –(263) to 263 – 1 (Added by C99)signed long int 32 Same as long intunsigned long int 32 0 to 4,294,967,295unsigned long long int 64 264 – 1 (Added by C99)float 32 3.4e-38 to 3.4e+38double 64 1.7e-308 to 1.7e+308long double 80 3.4e-4932 to 1.1e+4932void -- data type that not return any value
12. 12. Conversion SpecifiersCode Format%a Hexa decimal output in the form of 0xh.hhhhp+d(C99 only)%s String of characters (until null zero is reached )%c Character%d Decimal integer%f Floating-point numbers%e Exponential notation floating-point numbers%g Use the shorter of %f or %e%u Unsigned integer%o Octal integer%x Hexadecimal integer%i Signed decimal integer%p Display a pointer%n The associated argument must be a pointer to integer, This sepecifier causes the number of characters written in to be stored in that integer.%hd short integer%ld long integer%lf long double%% Prints a percent sign (%)
13. 13. Back Slash ( Escape Sequence) CharactersCode Meaning b Backspace f Form feed n New line r Carriage return t Horizontal tab " Double quote Single quote Backslash v Vertical tab a Alert ? Question mark N Octal constant (N is an octal constant) xN Hexadecimal constant (N is a hexadecimal constant)
14. 14. Increment and Decrement Operatorsprefix increment (++a) postfix increment (a++) prefix decrement(- -a) postfix decrement (a- -) Executes all Prefix Operations Before evaluation of expression Evaluation of expression Executes all Postfix Operations After evaluation of expression and before leaving the statement/* prefix operators */ /* prefix and postfix operators */ /* postfix operators */#include<stdio.h> #include<stdio.h> #include<stdio.h>int main() { int main() { int main() { int a = 7, b = 12, c; int a = 7, b = 12, c; int a = 7, b = 12, c; c = b * (++a) + 5 * (++a); c = b * (a++) + 5 * (++a); c = b * (a++) + 5 * (a++); printf(“ a = %d”, a); printf(“ a = %d”, a); printf(“ a = %d”, a); printf(“n b = %d”,b); printf(“n b = %d”,b); printf(“n b = %d”,b); printf(“n c = %d”,c); printf(“n c = %d”,c); printf(“n c = %d”,c);} } }Output: Output: Output: a=9 a=9 a=9 b = 12 b = 12 b = 12 c = 153 ( 12 * 9 + 5 * 9) c = 136 ( 12 * 8 + 5 * 8) c = 119 ( 12 * 7 + 5 * 7)
15. 15. Bitwise Logical Operators& -- Bitwise AND A B A&B A|B A^B ~A| -- Bitwise OR 1 1 1 1 0 0 1 0 0 1 1 0^ -- Bitwise XOR 0 1 0 1 1 1~ -- Bitwise NOT 0 0 0 0 0 1 Bitwise AND Bitwise OR A (42) : 00000000 00101010 A (42) : 00000000 00101010 B (15) : 00000000 00001111 B (15) : 00000000 00001111 ----------------------------------- ----------------------------------- & (10) : 00000000 00001010 | (47) : 00000000 00101111 ----------------------------------- ----------------------------------- Bitwise XOR Bitwise NOT A (42) : 00000000 00101010 A (42) : 00000000 00101010 B (15) : 00000000 00001111 ----------------------------------- ----------------------------------- ~ (-43) : 11111111 11010101 & (37) : 00000000 00100101 ----------------------------------- -----------------------------------
16. 16. BITWISE SHIFT OPERATORS Bitwise Left Shift ( << ) Bitwise Right Shift ( >> ) Bitwise Right Shift ( >> ) (positive values) (negetive values)A (43) : 00000000 00101011 A (43) : 00000000 00101011 A (-44) : 11111111 11010100----------------------------------- ----------------------------------- -----------------------------------A << 2 : 00000000 10101100 A >> 2 : 00000000 00001010 A >> 2 : 11111111 11110101----------------------------------- ----------------------------------- ----------------------------------- Note : Right shift operator fills the left vacant fields with ‘zeros’ for positive numbers, with ‘ones’ for negative numbers.Opposite TYPE CONVERSION Explicit Type Conversion To (casting)Gravity 1.bool 2.char (forcible) (forcible) 3.short int . 4.int . 5.long int . . 6.long long int . . 7.float (natural) (automatic) 8.double 9.long doubleGravity Implicit Type Conversion (automatic)
17. 17. Precedence and Associativity of OperatorsPrecdence Group Operators Associativity(Highest to Lowest )(param) subscript etc., ( ) [ ] –>. L RUnary operators - + ! ~ ++ – – (type) * & sizeof R LMultiplicative */% L RAdditive +– L RBitwise shift << >> L RRelational < <= > >= L REquality = = != L RBitwise AND & L RBitwise exclusive OR ^ L RBitwise OR | L RLogical AND && L RLogical OR || L RConditional ?: R LAssignment = += –= *= /= %= &= ^= R L |= <<= >>=Comma , L R
18. 18. simple if: Entry if-else: Entry True Test False Test True Expression Expression ? ? False True Statement-block True-block False-block Statements Statements Next statement Next statement /* check a citizen is eligible for voting */ /* print a number is even or odd */ #include<stdio.h> #include<stdio.h> int main() int main() { { int age; int number; printf(“Enter the age : ”); printf(“Enter a number : “); scanf(“%d”,&age); scanf(“%d”, &number); if(age >= 18) if((number %2) == 0) printf(“Eligible for voting…”); printf(“%d is even number.”,number); getch(); else } printf(“%d is odd number.”,number); }
19. 19. nested if…else: /* check whether a year is leap year or not */ #include<stdio.h> Entry int main() { int year; Test printf("Enter the year ?"); False True condition1 scanf("%d",&year); ? if((year %100) == 0) Test { False True if((year % 400) == 0) condition2 ? printf("%d is leap year.",year); elseStatement-3 Statement-2 Statement-1 printf("%d is not leap year.",year); } else { if((year % 4) == 0) printf("%d is leap year.",year); else Next statement printf("%d is not leap year.",year); } getch(); }
20. 20. if…else…if : /* program to print the grade of student */ #include<stdio.h> Entry int main() { True int marks; Test condition1 Statement-1 printf("Enter marks ? "); ? scanf("%d", &marks);False if(marks >= 75) Test True printf("Distinction");condition2 Statement-2 else if(marks >= 60) ? printf("First class");False else if(marks >= 50) Test True printf("Second class");conditionN Statement-N else if(marks >= 35) ? printf("Third class"); Next statement else printf("Failed"); }
21. 21. switch statement : /* program to simulate a simple calculator */ #include<stdio.h> Entry int main() { float a,b; switch char opr; expression printf("Enter number1 operator number2 : "); ? scanf("%f %c %f",&a,&opr,&b); switch(opr)value1 value2 valueN default { ……... case +: printf("Sum : %f",(a + b));associate associate associate associate break;statement statement statement statement case -: printf("Difference : %f",(a - b)); break; case *: printf("Product : %f",(a * b)); break; case /: Exit printf("Quotient : %f",(a / b)); break; default: Next statement printf("Invalid Operation!"); } }
22. 22. Loop Statementswhile – (Entry controlled ) do-while – (Exit controlled ) Entry Entry Test False Condition Body of The loop ? true Test False Body of The loop Condition ? Following Statement True Following Statement /* average of 5 numbers *//* sum of 1 to 10 numbers */ #include<stdio.h>#include<stdio.h> int main() {int main() { int count = 1; int i = 1,sum = 0; float x, sum = 0; while(i<=10){ do { sum = sum + i; printf(“x = “); i = i + 1; scanf(“%f”,&x); } sum += x; printf(“Total : %d “,sum); ++ count;} } while(count <= 5); printf(“Average = %f “, (sum/5)) }
23. 23. for -- EntryStatement Initialization Statement Increment Statement False Test Condition ? True Body of The loop Following Statement /* check whether a number is prime or not */ #include<stdio.h> int main() { int n,i,factors = 0; printf("Enter a number : "); scanf("%d",&n); for(i = 1; i <= n; i++) { if((n % i)==0) ++factors; } if (factors == 2) printf("%d is prime number.",n); else printf("%d is not prime number.",n); }
24. 24. Important Functions in math.habs(x) absolute value of integer xceil(x) rounds up and returns the smallest integer greater than or equal to xfloor(x) rounds down and returns the largest integer less than or equal to xlog(x) returns natural logarithmpow(x,y) returns the value of xysqrt(x) returns square root of xexp(x) returns natural anti logarithmsin(x) returns sine value where x in radianscos(x) returns cosine value where x in radianstan(x) returns tangent values where x in radiansfmod(x,y) calculate x modulo y, where x and y are doublehypot(x,y) calculate hypotenuse of right angle where x,y are sides.log10(x) returns logarithm base 10
1. #### A particular slide catching your eye?

Clipping is a handy way to collect important slides you want to go back to later.