Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
88 views

C Prog

This document provides an overview of basic C programming concepts including: 1. Rules for integer, float, and character constants as well as variable naming. 2. Data types, operators, and precedence of operators in C. 3. Control structures like decision making statements, loops, case statements, and functions. 4. Arrays, strings, and recursion. Examples of basic programs using these concepts are also provided.

Uploaded by

Abhijit Adiga
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views

C Prog

This document provides an overview of basic C programming concepts including: 1. Rules for integer, float, and character constants as well as variable naming. 2. Data types, operators, and precedence of operators in C. 3. Control structures like decision making statements, loops, case statements, and functions. 4. Arrays, strings, and recursion. Examples of basic programs using these concepts are also provided.

Uploaded by

Abhijit Adiga
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

C PROGRAMMING BASICS

ules for integer constants:


1. 2. 3. 4. Integer constants must have at least one digit It must not have a decimal point Since sign precedes the integer constant, it may take positive or negative values No special characters are allowed. 0 to 65535 -32768 to +32767

Range of an integer is:

Rules for float constants:


1. Float constant must have at least one digit 2. It may or may not have a decimal point 3. It could either have +ve or ve values, but by default, the value is positive.

Rules for constructing characters:


1. Max length of character constant is always 1. 2. It can be used to store alphabet, numbers or special characters.

Variable: The value of a variable is never constant.


All constants have to be stored in variables

Rules for variables:


1. Combination of alphabets, numbers or underscores ( _ ) are used to construct a variable name 2. First character of a variable should always be an alphabet. 3. Max length of variable name is 40. 4. Variable name cannot be a keyword.

Keyword: They have some built in function in the compiler and hence cannot
be used as variable names.

The keywords in C are:


auto, break, case, char, const, continue, do, double, enum, extern, float, for, goto, if, int, long, near, register, return, short, signed, static, struct, switch, typedef, union, unsigned, void, while.

Types of C instructions:
1. 2. 3. 4. Declaration Input/Output Arithmetic Control (i) Sequential (ii) Decision (iii) Loop (iv) Case

Shortcut keys:
F1 Help F2 Save F3 Open a file Alt+F3 Close current file Shift + Del - Cut Ctrl + Ins Copy Shift + Ins Paste Ctrl+ Y Delete a line Alt + Backspace Undo F5 Maximise window Alt + X Close

Arithmetic Instructions:
1. Arithmetic operation between one integer and another integer gives the output as integer. 2. Arithmetic operation between one integer and float gives the output as float. 3. Arithmetic operation between float and float gives the output as float. WAP to print Hello World WAP to read in an integer, float and character Rameshs basic salary is input through the keyboard. His DA is 40% of basic and HRA is 20% of basic. WAP to calculate his gross salary

If the marks obtained by a student in 5 subjects are taken as input, WAP to find the total, percentage and class obtained. Display all 3 parameters. WAP to swap the contents of 2 variables(with and without a 3rd variable). WAP to ask a user to enter a 4 digit number and print its reverse.

Data Types:
Data type Signed char Unsigned char Short signed int Short unsigned int Long signed int Long unsigned int Float Double Long double Range -128 to 127 0 to 255 -32768 to +32767 0 to 65535 -2147483148 to +2147483147 0 to 4294967295 -3.4e38 to +3.4e38 -1.7e308 to +1.7e308 -1.7e4932 to 1.7e4932 Bytes 1 1 2 2 4 4 4 8 10 Format %c %c %d %u %ld %lu %f %lf %Lf

Operators in C
Assignment ++ -+= -= %= /= *= = Examples: Suppose a=8 b=6 c=a&&b c=1 (because it checks if both no.s are >0, so result is 1) c=a&b; a=1000 b=0110 _______ c=0000 Arithmetic + * / % Conditional > >= < <= == != Logical && || ! Bitwise & | ^

Suppose a=0; b=10 b=++a; b=a++; b=--a; b=a--; b=11;a=11; b=10;a=11; b=9;a=9; b=10;a=9;

Precedence of operators:
Sl. No. 1. Category Highest Operator () [] -> :: . !,~,+,-,+ +,--,&,*,sizeof, new, delete *,/,% .* ->* +,<<,>> <,<=,>,>= ==,!= & ^ | && || ?: =,*=,/=,%=,+=, -=, &=,^=,| =,<<=,>>= , What it is? Function Call Array subscript C++ indirect component selector C++ scope resolution C++ direct component selector

2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.

Unary Multiplicative Member Access Additive Shift Relational Equality

C++ dereference C++ dereference Shift left/right

Conditional Assignment Comma

Evaluate

Decision Control Statements 1.


Syntax:

if( )
if(condition) { . . }

2.

ifelse

Syntax: if(condition) { . . } else { . . }

3.

ifelse ifelse if

Syntax: if(condition) { . . } else if(condition2) { . . } else if(condition3) { . . } else

{ . . }

4.

Nested ifelse

Syntax: if(condition1) { if(condition) { . . } else { . . } else if(condition) { . . } else { . . }

Ternary operator:
Syntax: (condition)?true:false;

?:

(condition)?((condition)?true : false): ((condition)?true : false); WAP to accept a number and display whether it is greater, less than or equal to 100 WAP to accept 3 numbers and arrange them in ascending order. A company insures its driver in the following cases (i) if the driver is married (ii) if the driver is unmarried, male and greater than 30yrs (iii) if the driver is unmarried, female and greater than 25yrs WAP to display whether the driver is insured or not.

WAP to accept marks of 6 subjects from a user. Check if the person has passed in all subjects. If so, display the total and percentage. If not, display FAIL. An insurance company follows the following rules to calculate the premium (i) persons health is excellent, his age is b/w 25 & 35, lives in a city, is a male then the premium is Rs. 4000 and the policy amount should not exceed Rs. 2,00,000. (ii) If the person satisfies all above conditions except that the person is female then the premium is Rs. 3000 and policy amount is Rs. 1,00,000 (iii) If the persons health is poor, lives in a village, age b/w 25 & 35, is male then the premium is 6000 and policy amount cant exceed Rs. 5,00,000. WAP to display premium and policy amount. A certain graded steel is graded according to the following condition 1) Hardness >50 2) Carbon content <0.7 3) Tensile strength >500 If all the conditions are met then grade 1 If 1&2 are met then grade 2 If 1&3 are met then grade 3 If 2&3 are met then grade 4 If any of the condition is true then grade 5 Else grade 6

Loop control structures


1) While : Syntax :: while(condition) { . counter; . } 2) Do while Syntax :: do { . counter; . } while(condition); 3) for Syntax ::

:
for(initialization; condition; counter) { . . }

Case controlled structures:


switch( )
Syntax: switch(variable) { case 1: { . . } break; case 2: { . . } break; case 3: { . . } break; . . case n: { . . } break; default: { . . } break: terminates the current loop i.e. it causes abrupt death of the loop. continue : skips the particular iteration and allows the loop to die a natural death . Example: main( ) { int i; . .

for(i=0;i<10;i++) { . . if(i==3) break/continue; printf(%d\n,i); } . . } Break 0 1 2 3 (loop terminated) Continue 0 1 2(skips next iteration) 4 5 6 7 8 9

WAP to display 15 to 1 in reverse order(using while) WAP to display all even numbers from 1 to 50 (using do-while) WAP to check if a no. entered by the user is prime or not. (for loop) WAP to take in 2 numbers and an operator. Depending on the input, perform the desired operation and print the result. WAP to generate Fibonacci series WAP to find factorial of a number. Arrays: Collection of variables of same data type. Eg: int marks[5]; int marks[]={10,20,30,40,50}; int marks[]; ----------- invalid because compiler does not know how much space is to be allocated. marks[0] marks[1] marks[2] marks[3] marks[4]

Two dimensional arrays:

int marks[5][5]; int marks[][]; ----------- invalid [0] [1] [2] [3] [4] [0] [1] [2] [3] [4] Initialising a single dimensional array: for(i=0;i<5;i++) scanf(%d,&marks[i]); Initialising a two dimensional array: for(i=0;i<5;i++) for(j=0;j<5;j++) scanf(%d,&marks[i][j]); WAP to perform matrix multiplication WAP to arrange the elements of a matrix in ascending/descending order

Strings: char str[5];

Collection of character arrays.

str[0]

str[1]

str[2]

str[3]

str[4]

\0 null character

Note: For strings, we can use either %c or %s as format specifiers.


WAP to perform string comparison, string concatenation and string copy with and without using the header file <string.h> if(strcmp(str1,str2)) printf(Strings not equal); else printf(Strings are equal); strcmp returns a value :-

< 0 if str1 is less than str2 ==0 if str1 is equal to str2 > 0 if str1 is greater than str2 Thus we write Strings are equal in the else part. WAP to find a name in a given database WAP to swap two databases.

Functions:
Short module of a program that can be called as many times as needed. Execution always starts from main. Functions without argument list: func( ) { printf(Into func); } void main( ) { printf(Beginning of main); func( ); printf(End of main); getch( ); } Output: Beginning of main Into func End of main Functions with argument list void sum(int a, int b) { int c; c=a+b; printf(%d + %d = %d ,a,b,c); } void main( ) { int x,y; // formal parameters // called function

//calling function

//actual parameters

x=5;y=10; sum(x,y); getch(); } Functions that return a value: int sum(int a, int b) { int c; c=a+b; return(c); } void main( ) { int x,y; x=5;y=10; z =sum(x,y); printf(Sum = %d ,z); getch(); } // formal parameters

//actual parameters

Note: A function can return only one value.


return(a); ------------------------valid return(1); ------------------------ valid return(5.5); ------------------------ valid return(a,b); ------------------------ invalid return(1,5.5); ------------------------ invalid return; ------------------------ valid ; but returns a garbage value. Write a function that accepts two numbers from main, multiplies them and returns the result back to main. Write a function to find xn, where x is the base and n is the power. Write a function to check if the year entered by the user is a leap year or not. Write a function that finds the factorial of a number. Write a function that generates Fibonacci series.

Recursion: Recursion is a method of defining functions in which the


function being defined is applied within its own definition. Write a recursive function to find xn, where x is the base and n is the power. Write a recursive function that finds the factorial of a number. Write a recursive function that generates Fibonacci series.

Call by value: void swap(int a, int b) { int c; c=b; b=a; a=c; printf(Swap in func %d %d \n,a,b); } void main() { int x,y; clrscr(); printf(Enter 2 no.s); scanf(%d %d,&a,&b); swap(x,y); printf(Swap in main %d %d\n,x,y); getch(); } Output: Enter 2 no.s : 5 10 Swap in func 10 5 Swap in main 5 10 Call by reference: void swap(int *a, int *b) { int c; c=*b; *b=*a; *a=c; printf(Swap in func %d %d \n,*a,*b); } void main() { int x,y; clrscr(); printf(Enter 2 no.s); scanf(%d %d,&a,&b); swap(&x,&y);

printf(Swap in main %d %d\n,x,y); getch(); } Output: Enter 2 no.s : 5 10 Swap in func 10 5 Swap in main 10 5

Call by pointer: void swap(int *a, int *b) { int *c; c=b; b=a; a=c; printf(Swap in func %d %d \n,*a,*b); } void main() { int x,y; clrscr(); printf(Enter 2 no.s); scanf(%d %d,&a,&b); swap(&x,&y); printf(Swap in main %d %d\n,x,y); getch(); } Output: Enter 2 no.s : 5 10 Swap in func 10 5 Swap in main 5 10

Hand written program Text editor C Source Code Pre processor directives Expanded source code Compiler Object Code Linker Executable Code

Pre- processor directives: #define PI 3.1475 #define AND && # define ARRANGE (a>45 AND a<50) #define AREA (3.14*r*r) These are also known as macros. File inclusion: It is used in the following cases if we have a large program then the code is divided into several different files each containing a set of related functions Concerned functions or macro definitions are required in almost every program. // constants // operators // Comparisons //Functions

Eg: #include<filename> #include filename Steps:

// compiler related // user defined files

(i) Compile the program having a particular function(say factorial). (ii) Save the current file with a .h extension in your directory and make the following changes comment the pre-processor directives comment the main( ) (iii) Make a new file which consists of your main program and save it with a .C extension in your directory This file should have: pre-processor directives #include pathname\.h main program (iv) Compile the current program to obtain the desired result. Conditional Compilation: It is done to to make the same program work for 2 or more conditions to comment out absolute line of code, if the client wants some changes in execution at the last minute. Eg: #ifdef, #if, #elif, #else, #endif #define PRINT main() { #ifdef PRINT printf(This line is executed\n); #else printf(These lines are printed\n); #endif printf(Common Code\n); getch(); } Explanation: Since PRINT is defined, #ifdef holds true so that part of the code is executed, #else statements are not compiled and then the common code is executed. Hence this is known as conditional compilation. Every #ifdef or #if must be terminated with a #endif. However the #else part is not compulsory.

If we check any conditions we have to use #if instead of #ifdef as shown in the part of code below.

#define PRINT 11 main() { #if PRINT == 11 printf(This line is executed\n); #elif PRINT ==20 printf(These lines are printed\n); #else printf(Sorry\n); #endif printf(Common Code\n); getch(); }

You might also like