0% found this document useful (0 votes)
331 views56 pages

C

Uploaded by

skumar4787
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
331 views56 pages

C

Uploaded by

skumar4787
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 56

Basic C Programs : C Programs A-Z Chapter 1 : Basic C Programs No Programs 1 2 Print Hello Word Declaring Variable and Printing

its Value

Chapter 2 : Area Programs No Programs 1 2 3 4 5 6 7 8 C Program to Calculate Area and Circumference of Circle C Program to Calculate Area of Scalene Triangle C Program to Calculate Area of Equilatral Triangle C Program to Calculate Area of Right angle Triangle C Program to Calculate Area of Circle C Program to Calculate Area of Rectangle C Program to Calculate Area of Square C Program to Calculate Area of Circle using Pointer

Chapter 3 : Mathematical Programs

No Programs 1 2 3 4 5 6 7 8 9 Compute sum of the array elements using pointers ! Find exponent Power Series !! Read the values of x y and z and print the results expressions in one line. Reads customer number and power consumed and prints amount to be paid Find greatest in 3 numbers Calculate gross salary of a person. Reverse a given number ! Calculate sum of 5 subjects and Find percentage Convert temperature from degree centigrade to Fahrenheit

10 Find the simple interest 11 Find area and circumference of circle 12 Find sum of two numbers 13 Solve Second Order Quadratic Equation 14 Find Factorial of Number Using Recursion 15 Find Factorial of Number without using function 16 Print table of n and square of n using pow() Chapter 4 : Number Programs in C Programming

No Programs 1 2 3 4 5 6 7 8 9 Calender Program in C Programming Language : Display Day of the month Find greatest in 3 numbers Reverse a given number ! Swap of two nos without using third variable Calculate sum of 5 subjects and find percentage Find sum of two numbers Generate the Fibonacci Series starting from any two numbers Print First 10 Natural Numbers Find Factorial of Number Using Recursion

10 Check Whether Given Number is Palindrome or Not ???? 11 Check Whether Number is Prime or not 12 Check for Armstrong Number in C 13 Check Whether Number is Perfect Or Not 14 Print All ASCII Value Table in C Programming 15 Find Factorial of Number without using function Chapter 5 : 1-D Array Programs

No Programs 1 2 3 4 5 6 7 8 9 C Program to implement Stack Operations Using Array C Program to read integers into an array and reversing them using pointers C Program to delete duplicate elements in an array C Program to calculate Addition of All Elements in Array C program to find Smallest Element in Array in C Programming C Program to find Largest Element in Array in C Programming C Program to reversing an Array Elements in C Programming Merging of Two arrays in C Programming Searching element in array

10 copy all elements of an array into another array in C 11 Program Insert element in an Array 12 Program for deletion of an element from the specified location from Array 13 Printing Array Elements in C Language 14 C Program : Rading Array Elements 15 One Dimensional Array All Programs 2-D Array Programs : C Programming

No Programs 1 2 3 4 5 6 7 8 9 C Program to Check whether Matrix is Magic Square or Not ? C Program to Print Square of Each Element of 2D Array Matrix Program to find Transpose of Given Square Matrix C Program to find addition of Lower Triangular Elements in C Programming C program to calculate sum of Upper Triangular Elements in C C Program to evaluate Subtraction of two matrices ( matrix ) in C C program for addition of two matrices in C Addition of Diagonal Elements in Matrix Addition of All Elements in Matrix

10 Accessing 2-D Array Elements In C Programming 11 C Program to Find Inverse Of 3 x 3 Matrix in 10 Lines 12 C Program to Multiply Two 3 X 3 Matrices Algorithms Programs : C Programming No Programs 1 2 3 C Progran to Implement N Queens Problem using Backtracking C Program to implement prims algorithm using greedy method Program to implement knapsack problem using greedy method

Command Line Arguments Programs : C Programming No Programs 1 How to print all Arguments passed using Command Line in C !

Conversion Programs : C Programming

No Programs 1 2 3 4 5 6 C Program to convert temperature from degree centigrade to Fahrenheit Decimal to Binary using Bitwise and operator Program to Convert Binary to Decimal number:Number System Program for Decimal to Hexadecimal Conversion in C >> Number System Program for Decimal number to Octal Conversion : Number System Program to Convert Decimal number into Binary : Number System :

Dos Programs : C Programming No Programs 1 2 How to print all Arguments passed using Command Line in C ! C Program to Add two numbers using Command Line Arguments Parameters

Expressions Programs : C Programming No Programs 1 2 C Program to demonstrates binary expressions using floating-point arithmetic C Program to demonstrates binary expressions using interger arithmetic !

File Handling Programs : C Programming No Programs 1 2 3 4 5 6 7 C program to copy the contents of one file into another using fputc C Program to read last n characters from the file ! C program to convert the file contents in Upper-case & Write Contents in a output file C Program to Compare two text/data files in C Programming C Program to Write on Data File and Read From Data File C Program to Copy Text From One File to Other File How to display same source code as output in c programming?

Electrical Programs : C Programming

No Programs 1 2 3 4 5 C Programs Electrical Circuit Formulae Varification C Program To find equivalent capacitance of parallel combination of capacitive circuit C Program To find equivalent capacitance of series combination of capacitive circuit Program To find equivalent resistance of Parallel combination of resistive circuits Program To find equivalent resistance of series combination of resistive circuits

Graphics Programs : C Programming No Programs 1 2 3 4 5 6 7 8 9 Drawing Line in Graphics Mode : Line Function C Program to draw Inductive Coil using Graphical Function C Program to Draw Resistance using Graphics Function C Program to Draw PNP Transistor using Graphics Function C Program to Draw Eclipse using Graphics Function C Program to Draw NPN Transistor using Graphics Function C Program to Draw Capacitor using Graphics Function C Program to Draw a Triangle using Graphics Function Printing Text in Graphics Using Outtextxy Function

10 First Turbo Graphics Program in C Language 11 C Program to draw Op-amp Symbol Using Graphics Function 12 C Program to display mouse pointer in textmode 13 C Program to check if mouse support is available or not. 14 Drawing Circle in Graphics Mode : Circle Function >> Graphics.h Mouse Programs : C Programming No Programs 1 2 C Program to display mouse pointer in textmode C Program to check if mouse support is available or not.

Pointer Programs : C Programming No Programs 1 C Program to Swap Two Numbers / Variables using Pointer109">C Program to Print Value and Address of Variable of Pointer C Program to perform Stack Operations Using Pointer ! C Program to compute sum of the array elements using pointers ! C Program to count number of words digits and vowels using pointers in C Programming C Program to Find Length of the String using Pointer C Program to read integers into an array and reversing them using pointers C Program to Add Two Numbers Using Pointer ! C Program to Calculate Size of Pointer in C Programming Pointer Program : Difference between two float Pointers

2 3 4 5 6 7 8 9

10 Pointer Program : Difference between two integer Pointers 11 Pointer Program : Increment Structure Pointer having far pointer as structure member 12 Pointer Program : Incrementing Array of Float Pointer 13 Pointer Program : Incrementing Double Pointer 14 Pointer Program : Increment Integer Pointer 15 Pointer Program : Declaring Pointer 16 Pointer Program : Address operator in C 17 C Program to calculate Area of Circle using Pointer 18 C program to Accessing Value from Address using Pointer 19 C Program to Access Address of Variable using Pointer Pyramid Programs : C Programming

No Programs 1 Pyramid Program in C Programming Mirror Image of Right Angled Triangle666">How to write c program to print FLOYDS triangle in C Programming ? Number Pyramid Pattern in C Programming Program Even Number Pyramid in C Print prime number Pyramid in C Print the Rectangle using Line and Special Symbols Number Pyramid in C Programming Program to Print Largest Number Pyramid Program to Print the Double Pyramid Pattern Program to Print Pyramid of Multiplication Tables

2 3 4 5 6 7 8 9

10 Program to print 1-10 Numbers in Pyramid fashion 11 C Program to Print Inverted Pyramid 12 Print the Pattern of Binary Numbers (Pyramid) 13 Program to Print this Right angled Pyramid in C using Nested Loops in C 14 Index : Pyramid Programs in C Programming Recursive Programs : C Programming No Programs 1 C Program to print Fibonacci Series using recursion !!662">C Program to Multiply two Matrices using Recursion !! C Program to calculate sum of numbers 1 to N using recursion Find Sum of Digits of the Number using Recursive Function in C Programming C Program to print Tower of Hanoi using recursion !! Find Factorial of Number Using Recursion

2 3 4 5

C Programs : Series No Programs 1 C Program to find exponent Power Series !!

C Programs : Sizeof Operator No Programs 1 2 3 4 5 6 C Program to Calculate Size of Structure using Sizeof Operator Pointer Program : Size of Pointer to Structure Pointer Program : Size of Integer Far Pointer Pointer Program : Size of Float Pointer Pointer Program : Size of Character Pointer Pointer Program : Size of Integer Pointer

C Programs : Sorting No Programs 1 2 3 4 5 C Program to sort array of Structure in C Programming C Program for sorting the list of Strings C Program to Implement Bubble Sort in C Programming Sorting Two Structures on the basis of any structure element and Display Information Program to Implement Insertion Sort in C Programming

C Programs : Stack No Programs 1 2 3 C Program to perform Stack Operations Using Pointer ! C Program to implement Stack Operations Using Array C Program to Implement Stack Operations using Singly Linked List

C Programs : String Operations With using Library Function

No Programs 1 2 3 4 5 6 7 C Program to Sort set of strings in alphabetical order using strcmp() C Program to Convert String to Integer !! Program to convert String into Uppercase Using Library Function Program to convert String into Lowercase Using Library Function Program to copy one string into other with using library function [ strcpy ] Program to Concat Two Strings with using Library Function : Strcat Find Length of String Using Library Function

C Programs : String Operations Without using Library Function

No Programs 1 2 3 4 5 6 7 8 9 C Program to count number of words digits and vowels using pointers in C Programming C Program for sorting the list of Strings C Program to Find Length of the String using Pointer Write a C Program to Reverse Letter in Each Word of the Entered String C Program to Encode a String and Display Encoded String ! C program to Delete all occurrences of Character from the String. C Program to Concat Two Strings without Using Library Function C Program to Find Substring Of String Without Using Library Function !!! C Program : Reverse String Without Using Library Function [ Strrev ]

10 C Program to Compare Two Strings Without Using Library Function [Strcmp] 11 C Program to Copy One String into Other Without Using Library Function. 12 Check Whether Character is Lowercase or Not without using Library Function 13 Check Whether Character is Uppercase or Not without using Library function 14 C Program to Count number of Uppercase and Lowercase Letters 15 Search occurrence of Character in String : 16 With using User-defined Function Write a Program to Find Length of String 17 Program to Find Length of String Without using Library Function C Programs : Structure Concept No Programs 1 2 3 4 5 C Program to read and print name and other details of 50 students using Structure? C Program to sort array of Structure in C Programming C program to use structure within union & display the contents of structure elements C Program to Calculate Size of Structure using Sizeof Operator Sorting Two Structures on the basis of any structure element and Display Information

C Programs : Typical Programs

No Programs 1 2 3 4 5 6 7 8 9 Calender Program in C Programming Language : Display Day of the month C Program to show swap of two nos without using third variable How to write c program to count number of digits in number without using mod operator ? How to Input Password in C : Validation of User name How to write inline assembly language code inside C Program ? Accept Paragraph using scanf in C Print Hello word without using semicolon in C Nested Printf statements : Example 2 Printf inside printf in C : Example 1

10 C program to add reversed number with Original Number ? 11 C program to reverse the digits of a number ? [ In 3 Steps ] 12 How to Add Digits of the Number Using Single Statement ? 13 Swap two numbers without using third variable and using XOR Operator in C Programming 14 How to Add two numbers without using arithmetic Operators in C Programming ? 15 How to Create Your Own Header File in C Programming ? 16 How to write C Program Without using Main Function (in 3 ways) ? 17 Swap / Interchange two variables [numbers] without using Third Variable 18 How do i Return Multiple Values From a Function ? 19 C Program to Create directory in C using Interrupts. 20 How to use Interrupts in C Programming ? 21 How to print 1-10 numbers without using Conditional Loop in C Programming ?

What is C

C vs C++ vs Java

Program Structure

Data Types in C Switch Case Command Line Arguments

Basic Rules of C & C++ Arrays Type Casting

Functions If, Else Conditions Loops in C in C Pointers Structures in C Strings in C

Linked Lists

Recursion

Binary Trees Object Oriented Programming

Inheritance Data Structures in C

Multiple Inheritance C interview Questions

Templates File I/O

C programming Tutorial : Free C Programs, C Programs Download Basic C Programs Sorting Programs in C Fun C programs String C programs Miscellaneous C programs

If-Else Statement in C++ language Loops in C++ Language Functions in C C++ interview Questions Fundamental Data types used in C fundamental data types in C are integral, floating arithmetic types Basic C Programs Binary Search C program Binary search algorithm (or binary chop) is a technique for locating a particular value in a sorted list. Creation Of Binary Search tree Learn How to Create a BST Simple Linked List In computer science, a linked list is one of the fundamental data structures, and can be used to implement other data structures Doubly Linked List Doubly Linked List Implementation Push and Pop in Linked list Learn how to Push & Pop in a Linked List Sparse Matrix A sparse matrix obtained when solving a finite element problem in two dimensions Threaded Binary tree A binary tree is threaded by making all right child pointers Program to merge two polynomials Merging two Polynomials Sorting Programs in C language Bubble Sort Insertion Sort Selection Sort Shell Sort Heap Sort Merge Sort Other C Programs Matrix Multiplication Multiplying Matrices with Each Other Source code to implement Warshall' s Algorithm Implementation of Warshall Algo Fun C programs Program To Disable and Enable the Keyboard Typing Speed Calculator program A to Z pattern Piano Game in C C program that produces its own source code as output String related C Programs Auto Storage Class Count Number of Vowels, Characters and words in a paragraph

Use of Strlen( ) function Use of Strcat( ) function Use of Strcpy( ) function Use of Strcmp( ) function Use of Strrev( ) function C program to sort a list of names More C Programs Checks a number is Prime or non Prime Ambiguity in Multiple Inheritance Calculate Number of Consonants in a string Sparse Matrix Evaluation Invoke Function Without main() AVL Tree Implementation Midpoint Circle Algorithm Bresenham Algorithm Human Face Applet

Learn C Programming, A short C Tutorial So you want to be a hero.... I mean programmer, well by reading this tutorial maybe we'll be able to help you accomplish your goal. First a little about C and its derivative C++. It is considered to be the most commonly used programming language. If you want a job in programmming, you will need to know this language. But what makes C the language that everyone wants to use. Well, its been around for quite some time. The original C since the 70s, and C++ since the early 80s, which is like eons in computer time. C is the most versatile high level language. C permits just about anything, allowing programmers to write straight to the metal. Its code runs very fast. Note that this tutorial will not cover C++ (C with classes). Table of Contents: Your First Program Data Types and Printf Loops and Conditions Pointers and Arrays Functions Other Resources This tutorial is meant to be a brief introduction to C, it is by no means exhaustive. If you need more information try looking at our Other Resources. Learning a programming language is a lot like learning a language that people speak like German or French. The best way to learn a 'human' language is to start speaking, listening, and repeating, and then leaving the grammar for later. The same can be applied to C, you need to start writing programs as quickly as possible. So, this tutorial will provided a lot of well commented sample programs that you can run and tinker with. 1. Your First Program If you've ever read another tutorial or a book on a programming language, then you've probably seen a program like this before. The hello world program. It is a perfect starting place for our tutorial. So, type the following program into your favorite editor. If you are using Windows then try notepad or DOS Edit, if using a *Nix variant use VI or emacs. Without further adew here is the program : /* hello world program */ #include "stdio.h" void main() { printf("\nHello World\n"); // print to screen } Save this code into a file, and call the file hello.c, then compile it by typing at a command prompt: gcc hello.c If you are using *Nix you should have an a.out file now, but if you are using Windows you might be wondering what is gcc, and where do I type the above line into. On Windows getting up and started with C is little bit more difficult than with a *Nix variant. You can get a variation of gcc to output Windows code

called DJGPP at www.delorie.com/djgpp/ Setting up the compiler is probably the hardest part to getting started programming, and unfortunately this site doesn't cover setting up DJGPP. Another compiler option is to get Microsoft Visual C++, an excellent editor, with lots of nice features. The draw back is that the standard edition costs around $100. But if you can afford a copy, get it. If you have Visual C++ and it is already installed then load it, click File, then New, then select Win32 Console application from the project list. Type in a project name, and then press ok. Next it will ask you what it should automatically create. Select the hello world application, and then you should get a program very similar to the one above. F7 compiles, and Ctrl-F5 will run it. From now on the tutorial will refer to the *Nix method and output files. If you compiled the program in Windows instead of *Nix you would have a hello.exe instead of a a.out Note:If you are coming from the gameboy advance tutorial, please note you will need a separate compiler for this tutorial. The reason is the gcc with the devkit advance is for the gameboy, so the code it generates will not run on a PC, also becuase the gameboy has no standard font built in, you will not be able to see the output of the printf statement, basically the above program will do nothing. This creates an executable file a.out, which is then executed simply by typing its name. The result is that the characters Hello World are printed out, preceded by an empty line. A C Program contains functions and variables. The functions specify the tasks to be performed by the program. The above program has one function called main. This function tells your program where to start running. main functions are normally kept short and calls different functions to perform the necessary sub-tasks. All C codes must have a main function. Also notice that C is case-sensitive. The commands have to be written like they are above. C also denotes the end of statement with a semi-colon like Java & Pascal. Brackets signify either to "{" begin a group of statements, or "}" end a group of statements. The // or /* comment */ designates a comment. Anything after two slashes the compiler ignores. The last part of the program you should notice is the #include. This simply includes a group of functions from the filename specified between then less than and greater than signs (<...>). The file above stdio.h contains a list of standard functions for C to use, the function the our above program uses is printf. Printf takes a string of characters between quotation marks, and outputs them to the screen. Now that you understand the hello world program it's time to learn more about data types, and the printf statement. 2. Data Types and Printf Here is our next program to discuss. It declares several variables, performs some computations, and then outputs the results of those computations to the screen. #include <stdio.h> void main() { int numcandy; // declare a number variable double cost; // declare a variable that can store decimals printf("How many lollipops do you want: "); scanf("%d", &numcandy); // get input from user cost = 0.55 * numcandy; // do some math printf("\nPlease pay %f to the cashier!\n", cost);

This program when run, well prompt the user for how many lollipops they would like. After they enter a number and press enter, it will print out how much it will cost them to buy that many lollipops assuming lollipops cost 55 cents each. The main, {} brackets, comments, and include should be familiar. The new part of this program is the scanf, variables, and the use of printf to print out numbers. of this program that we haven't seen before. First lets talk about the variables. This program has two variables numcandy, and cost. These are the names of the variables. Before a variable can be used it must be declared. Declaring a variable in C is easy, you simply tell the compiler the type, and the name you want the variable to have. So in the above example. The line int numcandy; tells the compiler you want a variable of type integer with the name numcandy. Then you can simply use numcandy through out your program to store int's (integers). Integers are non decimal numbers like -13, 0, 10, 5, etc. The other variable in the above program is a double which is used for storing numbers with decimals.

Next the scanf, and printf statements. After running the program you will notice that the scanf function simply gets a value from the user. It waits for the user to enter a number, and then press enter. It puts this value into our variable numcandy. Next notice some special character sequences contained in both the scanf and printf. First the printf has the sequence "\n". This sequence simply means move to the next line. Next we have the %f and %d. These tell printf and scanf what type of variables to expect. %f corresponds to double, and %d is for int. So if you changed the above programs printf line to ...pay $%d to... then you would get wierd output since printf would try to print cost as an integer, which doesn't make sense, because cost is a double. You need to make sure the "%" go with the right types. Variable names are arbitrary (with some compiler-defined maximum length, typically 32 characters). C uses the following standard variable types: int -> integer variable short -> short integer long -> long integer float -> single precision real (floating point) variable double -> double precision real (floating point) variable char -> character variable (single byte) The printf function can be instructed to print integers, floats and strings properly. The general syntax is printf( "format", variables ); where "format" specifies the converstion specification and variables is a list of quantities to print. Some useful formats are %.nd %m.nf %ns %c \n \t integer (optional n = number of columns; if 0, pad with zeroes) float or double (optional m = number of columns, n = number of decimal places) string (optional n = number of columns) character to introduce new line or tab

So using this new knowledge, you could change the above program where it prints the cost to ...pay $.2f to... which would print the number, and then only two decimal places of the double. Look back up at the program one more time at the line cost = 0.55 * numcandy;. This is the math of the program. This line is fairly self explanatory. It takes the value which is stored in numcandy multiplies it with 0.55 and puts the resulting value into cost. Here are a list of the standard math operators you can use in your programs: + * / = add subtract multiply divide equals (assignment operator)

Now that we've covered printf and the basic data types, we can move onto program control meaning loops and conditions. 3. Loops and Conditions Real programs are than just getting input, performing some math, and then printing out the results. The next obvoius step would be to add some sort of control. Like for the above example program if they put in that they wanted to buy more than 1000 lollipops. We could print out, that the store doesn't have that many. This section will describe the basic loop and condition statements available in C, and then will end with a short example program putting a few to use. First Conditional statements. C has three types of conditional statements if, else, and switch. Here is the syntax for if and else: if (condition_1) { ...block of statements executed if condition_1 is true ...statements are either more ifs and conditions or normal normal lines of code that end with semi-colons } else if (condition_2)

{ } else { } ...statements executed if condition_2 is true and condition_1 was false

...statements executed otherwise meaning 1 and 2 were false

and any variant that derives from the above. Either by omitting branches or by including nested conditionals. Meaning having an if inside of another if. Now that we can make an if we need to make the condition that goes inside of the parenthesis of the if. Conditions are logical operators involving the comparison of quantities (of the same c type). Here are a list of the basic conditional operators. < <= == != >= > and the boolean operators && || ! and or not smaller than smaller than or equal to equal to not equal to greater than or equal to greater than

Now that you know the operators here are some sample conditions. For instance using the above example. if (numcandy > 1000) { printf("The store does not have that much candy in stock!"); } else .... print out the cost ..... The boolean operators are for combining more than one condition into a single if statement. So for instance if (money>500 && cost<10) ... This condition would only be true if both money was greater than 500, and cost less than 10. If you replace the && with || then the condition would be true if either money is bigger than 500 OR cost less than 10. I think you get the picture. Another couple things to notice about conditional statements in C is that the equality operator is == (two equals) and not = one equals sign. The single equals sign as we learned in lesson two is the assignment operator. You use it to assign values to variables so when you want to test if a variable is equal to something use two equals signs == and not one. Remember THIS! It is very important. Next with C conditional statements you can also omit (leave out) the operator. if you had a conditional statement: if (numcandy) {...} This would evaluate to true and the statements inside the {} brackets would be executed, if numcandy was not equal to zero. Understand? If you have no operators inside the parenthesis then C will simply check to see if the value is anything but zero. Another conditional use is in the switch construct: switch (variable) { case const_1: { ...block of statements... break;

} case const_2: { ...block of statements... break; } default: { ...block of statements.. }

The appropriate block of statements is executed according to the value of the expression, compared with the constant expressions in the case statement. The break statements insure that the statements in the cases following the chosen one will not be executed. If you would want to execute these statements, then you would leave out the break statements. This construct is particularly useful in handling input variables. Here is an example, if you had a integer variable called race position. switch (race_position) { case 1: { printf("First place, you get gold!\n"); break; } case 2: { printf("Second place, you get silver!\n"); break; } case 3: { printf("Third place, you get bronze!\n"); break; } default: // all other numbers (anything but 1,2,3) { printf("You dont get anything, you lose!\n"); break; } } // end switch You could have easily done this same thing with three if's and and else. But we wanted to demonstrate the switch. As an excersize rewrite the above code segment to use if's instead of the switch. That's it for conditional statements, now we come to the next part of lesson three loops. C provides two basic types of loops a while and a for loop. While and for loops continue to repeat basically until certain conditions are met. Here is the syntax for while and for loops: while (condition) { ...block of statements to execute... } and the for loop: for (expression_1; expression_2; expression_3) { ...block of statements to execute... } The while loop continues to loop until the condition becomes false. The condition is tested upon entering the loop. Any logical construction (see below for a list) can be used in this context. The for loop is a special case, and is equivalent to the following while loop:

expression_1; while (expression_2) { ...block of statements... expression_3; } For instance, the following structure is often encountered: i = initial_i; while (i <= i_max) { ...block of statements... } i = i + i_increment;

This structure may be rewritten in the easier syntax of the for loop as: for (i = initial_i; i <= i_max; i = i + i_increment) { ...block of statements... } Infinite loops are possible (e.g. for(;;)), but not too good for your computer budget! C permits you to write an infinite loop, and provides the break statement to ``breakout'' of the loop. For example, consider the following (admittedly not-so-clean) re-write of the previous loop: angle_degree = 0; for ( ; ; ) { ...block of statements... angle_degree = angle_degree + 10; if (angle_degree == 360) break; } The conditional if simply asks whether angle_degree is equal to 360 or not; if yes, the loop is stopped. Finally, to wrap up lesson three we will introduce #define's and then give the sample program. You can define constants of any type by using the #define compiler directive. Its syntax is simple--for instance #define ANGLE_MIN 0 #define ANGLE_MAX 360 would define ANGLE_MIN and ANGLE_MAX to the values 0 and 360, respectively. C distinguishes between lowercase and uppercase letters in variable names. It is customary to use only capital letters in defining global constants. Then inside your program you could insert ANGLE_MAX anytime you wanted to use the number 360. Now here is the sample program. You should be able to understand all the code there in. Basically there is a #define for a number of lollipopps, and you sell lollipopps until you run it, but there is also a limit too how many you can get at one time. Then after all are sold, the amount of money for all purchases is printed out. #include <stdio.h> #define START_NUMBERLOLLIPOPS 100 #define MAX_AT_ONCE 30 void main()

{ int numcandy; double cost; int numberlollipopps; double totalcost; numberlollipopps = START_NUMBERLOLLIPOPS; // set start value to our constant totalcost = 0; while (numberlollipopps > 0) { printf("(%d left) How many lollipops do you want (-1 quits): ", numberlollipopps); scanf("%d", &numcandy); if (numcandy == -1) // since this if has only one statement brackets are not needed break; // exit out of the while loop else if (numcandy > MAX_AT_ONCE || numcandy <= 0 || numcandy > numberlollipopps) { } else { printf("You cannot have that many, enter another number\n");

cost = 0.55 * numcandy; printf("\nPlease pay $%.2f to the cashier!\n", cost); totalcost = totalcost + cost; numberlollipopps = numberlollipopps - numcandy; } printf("All the lollipopps have been sold for : $%.2f\n", totalcost); }

4. Pointers and Arrays The C language takes a lot of flack for its ability to peek and poke directly into memory. This gives great flexibility and power to the language, but it also makes it one of the great hurdles that the beginner must have in using the language. Arrays are very interesting since they can be accessed through pointers or array syntax, that is why they are grouped into the same lesson. With that said, let's get started. All variables obviously have to be stored into memory, but where are they stored? Imagine memory as this big long street with houses on it. Each variable is a house on a street. Each house can hold a number of people (value of variable). But how do you find out how many people (what value is stored) are in a particular house. You have to have some kind of address. Then with the address, you can go to the house and then ask it: How many are there? Then you can get the value of a variable. This is the basic concept behind pointers. This should seem very logical, if not please reread this paragraph tell makes sense. Let us use this new knowledge to examine a couple of statements. int var_x; int* ptrX; var_x = 6; ptrX = &var_x; *ptrX = 12; printf("value of x : %d", var_x); The first line causes the compiler to reserve a space in memory for a integer. The second line tells the compiler to reserve space to store a pointer. As you can notice the way you declare a pointer is simply to add a "*" asterick to the end of the datatype. A pointer is a storage location for an address. The third line should remind you of the scanf statements. The address "&" operator tells C to goto the place it stored var_x, and then give the address of the storage location to ptrX. The fourth line is a bit more complex. An asterick * in front of a variable tells C to dereference the pointer, and go to memory. Then you can make assignments to variable stored at that location. Since ptrX points

to var_x, line 4 is equivalent to this command: var_x = 12; Pretty cool, eh? You can reference a variable and access its data through a pointer. Windows and all sorts of programs do this all the time. They hand pointers of data to each other, and allow other applications to access the memory they have. Now you may be wondering, why are pointers so comlpex, or I've heard the using pointers can cause problems. It can, and for those who aren't careful misuse of pointer can do a lot of damage. Suppose that we forget to type in line 3 ptrX = &var_x; when we entered the program. What would happen if we executed it, who knows? Without this line ptrX is never assigned an address. Basically it points to some random data anywhere in memory. If you executed line 4 without line 3. You could get very wierd results. Since ptrX hasn't been pointed to our var_x, maybe its points to system memory, and then you assign a value someplace you shouldn't and your computer crashes. This may not always happen, but it is certainly a possibility, so be very careful when using pointers. Make sure they are assigned to something before you use them. With that basic understanding of pointers, it is time to move to arrays. The most obvious use of arrays would be an array of characters also commonly knows as a string. The following program will make a string, access some data in it, print it out. Access it again using pointers, and then print the string out. It should print out "Hi!" and "012345678" on different lines. The explanation of the code and arrays will follow #include <stdio.h> #define STR_LENGTH 10

void main() { char Str[STR_LENGTH]; char* pStr; int i; Str[0] = 'H'; Str[1] = 'i'; Str[2] = '!'; Str[3] = '\0'; // special end string character printf("The string in Str is : %s\n", Str); pStr = &Str[0]; for (i = 0; i < STR_LENGTH; i++) { *pStr = '0'+i; pStr++; } Str[STR_LENGTH-1] = '\0'; printf("The string in Str is : %s\n", Str); } First off, let's talk about the array notation to declare an array in C, you use [] square braces. The line of the program char Str[STR_LENGTH]; declares an array of ten characters. Basically this is just ten individual chars which are all put together in memory into the same place. An apartment complex in memory to use our pointer metaphor. They can all be access through our variable name Stralong with a [n] where n is the element number (apartment number at same address). Also notice that when C declares an array of ten. The elements you can access are numbered 0 to 9. Accessing the first apartment corresponds to accessing the zeroeth element in C. Arrays are always like this, so learn to deal with it. Always count from 0 to size of array - 1. Next notice that we put the letters "Hi!" into the array, but then we put in a '\0' You are probably wondering what this is. If you recall in lesson two on printf, there are special charcter sequences that do special things like "\n" stands for new line. Well time to learn a new one. "\0" stands for end string. All character strings need to end with this special character '\0'. If they do not, and then someone calls printf on the string. Then printf would start at the memory location of your string, and continue printing tell it encounters '\0' So you will end up with a bunch of garbage at the end of your string. So make sure to terminate your strings properly. The next part of the code to discuss is our pointer access to the string. Just like we learned, I declared a character pointer with an asterick and gave it the name pStr. I then pointed pStr to the starting address of our character string using the line pStr = &Str[0];. Now pStr points to the start of our char array Str. Then I used a for loop, and started at 0, went through 10 elements of the array (STR_LENGTH) and assigned the corresponding value of i. The line pStr++; may seem a bit confusing. C has a bunch of short

cuts to manipulate variables the ++ just means add one to the variable (in this case it moves the pointer to the next element in the array). The ++ syntax here is equivalent to pStr = pStr + 1;. After manipulating the string, I terminated it with '\0' and printed it out. That about does it for pointers and arrays, here are a few quick notes. You should note that you will see other shortcuts in C like -- (subtracts one) or +=3; (adds three). I won't bother covering them, since you should be able to figure them out just by looking at them. Another note is that you can make arrays of any of C's types, I just used char arrays since they seem to be the most common. Here is a sample line to make an array of five integers: int arrayofint[5];. 5. Functions This part should be quite simple compared to the last part. Functions are easy to use; they allow complicated programs to be parcelled up into small blocks, each of which is easier to write, read, and maintain. We have already encountered the function main and made use of printf from the standard library. Now let's look at writing and using our own functions. Calling a Function The call to a function in C simply entails referencing its name with the appropriate arguments. The C compiler checks for compatibility between the arguments in the calling sequence and the definition of the function. When someone writes a function for someone to use that funciton will often be contained in a different C source file. Sometimes, however we may not have access to all the source code for all the functions. This is the case for most standard library functions like printf. However, we still know how to use printf, and the arguments it requires because those arguments are listed in the header file called stdio.h, which we have been including in our programs. Library functions are generally not available to us in source form. Argument type checking is accomplished through the use of header files (like stdio.h) which contain all the necessary information. The most commonly used header files are <stdio.h> -> defining I/O routines <string.h> -> defining string manipulation routines <math.h> -> defining mathematical routines <stdlib.h> -> defining number conversion, storage allocation and similar tasks <stdarg.h> -> defining libraries to handle routines with variable numbers of arguments <time.h> -> defining time-manipulation routines To find out more about there header files and the functions they contain you can either by a book about C or visit our Other Resources. In addtion to those header files, we can of course make our own functions and header files. A function has the following layout: return-type function-name ( argument-list-if-necessary ) { ...local-declarations... ...statements... } return return-value;

If return-type is omitted, C defaults to int. The return-value must be of the declared type. A function may simply perform a task without returning any value, in which case it has the following layout: void function-name ( argument-list-if-necessary ) { ...local-declarations... ...statements... } Arguments are always passed by value in C function calls. This means that local ``copies'' of the values of the arguments are passed to the routines. Any change made to the arguments internally in the function are made only to the local copies of the arguments. In order to change (or define) an argument in the argument list, this argument must be passed as an address, thereby forcing C to change the ``real'' argument in the calling routine.

As an example, consider exchanging two numbers between variables. First let's illustrate what happen if the variables are passed by value: #include <stdio.h> void exchange(int a, int b); void main() { int a, b; /* WRONG CODE */

a = 5; b = 7; printf("From main: a = %d, b = %d\n", a, b); exchange(a, b); printf("Back in main: "); printf("a = %d, b = %d\n", a, b); } void exchange(int a, int b) { int temp; temp = a; a = b; b = temp; printf(" From function exchange: "); printf("a = %d, b = %d\n", a, b);

Run this code and observe that a and b are NOT exchanged! Only the copies of the arguments are exchanged. The RIGHT way to do this is of course to use pointers. Also note that in the above code how the function exchange was prototyped. It was declared with a semicolon, and ZERO statements before the main function. This is called forward declaration. This allows the C Compiler to compile main, without not yet knowing the code for exchange. All it needs to know is what exchange arguments look like. This way we can put the exchange function after our main function. We could have easily put exchange before main and gotten rid of the declaration. The next code segment will fix exchange to use pointers, and move exchange above main to eliminate the need for the forward declaration. #include <stdio.h> void exchange ( int *a, int *b ) { int temp; temp = *a; *a = *b; *b = temp; printf(" From function exchange: "); printf("a = %d, b = %d\n", *a, *b);

void main() { int a, b;

/* RIGHT CODE */

a = 5; b = 7; printf("From main: a = %d, b = %d\n", a, b);

exchange(&a, &b); printf("Back in main: "); printf("a = %d, b = %d\n", a, b); } The rule of thumb here is that You use regular variables if the function does not change the values of those arguments You MUST use pointers if the function changes the values of those arguments Lastly, I noticed that none of the examples with functions have returned values. So this quick example will illustrate returning values with functions. Functions may not seem that useful yet, but as your program grows you will no longer want to have all your code in main. So you will want to split it up into functions. Below we have a function that adds the two arguments it receives and returns their value. Not to complex, but does its job well. Take a look: #include <stdio.h> int addints(int a, int b) { return a+b; } void main() { int a; int b; int sum; a = 6; b = 7; sum = addints(a, b); printf("The sum of a and b is : %d\n", sum); }

6. Other Resources That concludes our tutorial on C, you should have a fairly good handle on all the basics of the C langauge now. There are still quite a few things that such a short tutorial could not cover like structs, file I/O, typedefs, c standard library functions, and more. But we have gathered a few links to some further resources here. Where you can learn more about. We also have two books listed that come highly recommended. Good luck with you adventures as a hero.... I mean programmer. If you have any comments or questions feel free to contact us. CProgramming.Com this is the resource for C programmers. It is the source for tons of information. It has good tutorials, which are easy to understand and message boards so you can get help for any problems you may encounter. This is the place for C! DJGPP Want a great *free* C++ compiler this is it. Easy to setup, and with Allegro you'll be making games in no time! DEV C++ another free compiler for C/C++ Dr. Dobb's Journal software tools for the professional programmer. We used to link to the Programmer's Vault, but as this has been integrated into Dr. Dobb's we will link there instead. C Tutorial at Drexel.edu - contains a little bit more information about file i/o and command line arguments. Parts of the above tutorial were based on this one here. BOOK : C Programming Language (2nd Edition) by Brian W. Kernighan, Dennis M. Ritchie. This is slightly more complex than a tutorial or a book to learn C. It is more of a reference. But is was written by the guys who invented C, so what can I say. It is the definite source for accurate information on the C language. BOOK : C For Dummies, Volume One & Two Bundle by Dan Gookin. This is an excellent book to start learning C from. It's simple, and takes you step by step through the world of making programs, and becoming a programmer. 1. main() This is nonstandard, the ISO C standard defines main to be declared as either int main( void ) or int main(

int argc, char **argv ). Anything else is just wrong. 2. clrscr() Not everyone has a compiler that defines this function, conio.h is nonstandard and programs using it that are ported to other compilers will flag errors. Learners shouldn't be thrown into that kind of debugging early on. 3. getch() See above comment on clrscr(). I don't recommend getch at all unless you write it yourself, getchar() does the same thing and is a standard function so it will work regardless of the compiler or system. 4. fflush( stdin ); This is undefined, anyone who wants to write good programs should think of undefined as illegal. You can't flush stdin, this was stated explicitly in the ISO C standard. A better way to eat the garbage left by scanf if is to either not use scanf or use a loop. while( getchar() != '\n' ); 5. len = strlen( word ); len is declared as an int, strlen returns size_t. This is nitpicking, but truly portable code will declare len as size_t len; 6. gets( word ); Normally I wouldn't even comment on code that uses gets, but I'll make an exception. NEVER use gets, it's been proven to be broken and caused serious problems in the past. gets doesn't check for overflow, you could declare an array of size 20 and enter 500 characters as input and gets will happily write them all to memory that you don't own, possibly crashing your system or worse. Sample C# programs for beginners namespace base_kw_usage { class A { public int a; public int b; public A() { } public A(int a, int b) { this.a = a; this.b = b; } public void sub() { int s = a - b; Console.WriteLine("subtraction of two numbers {0} and {1} results {2}",a,b,s); } } class B:A { public int a; public int b; public int c; public B(int a, int b, int c) : base(a, b) // By using this base method the value of a and b from this contructor is transmitted o the constructor of the base class { this.a = a; this.b = b; this.c = c;

} public int add() {

} }

int z = a + b + c; return z;

class Program { static void Main(string[] args) { B b = new B(15,6,4); // Constructor initialized at the object creation step int x=b.add(); Console.WriteLine("sum is "+x); b.sub(); // the value from the derived class constr. will get passed to base class constr. with that base method usage } } } namespace Findlargest { class Program { static void Main(string[] args) { Console.WriteLine("Enter any ten elements to compare for largest number"); large(); } public static void large() { int[] input ={ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < 9; i++) { int a = Convert.ToInt32 (Console.ReadLine()); input[i] = a; } for (int k = 1; k<9;k++ ) { if (input[0] > input[k]) {} else { // int temp; // temp = input[0]; input[0] = input[k]; // input[k] = temp; } } Console.WriteLine("Largest no. is" + input[0]); } } } 3. class outkw { public int add(int a, int b,out int o) // method having argument and return value with out keyword in

input argument { o = a + b; return o; } } namespace outkeywordus { class Program { static void Main(string[] args) { int m; // variable declared for out variable outkw ok = new outkw(); int z=ok.add(30,7,out m); // variable m declared with keyword out to get from the function Console.WriteLine(z); } } } class Program { static void Main(string[] args) { int[] list ={ 1,2,3,4,5,6,7,8,9}; Console.WriteLine("Even numbers"); for (int i = 0; i < 9; i++) { if (list[i]%2 == 0) { Console.WriteLine(list[i]); } } Console.WriteLine("Odd numbers"); for (int i = 0; i < 9; i++) { if (list[i] %2!= 0) { Console.WriteLine(list[i]); } } } } 5. class MatrixA { public int[,] mata = new int[3, 3]; //Declaring the matrix A to have 3 rows and 3 columns public int i; public int j; public void matrixa() { Console.WriteLine("Enter the Matrix A elements\n"); { for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { mata[i, j] = Convert.ToInt32(Console.ReadLine()); }

} } } class MatrixB : MatrixA // Interfacing Matrix A to Matrix B { public int[,] matb = new int[3, 3]; //Declaring the matrix B to have 3 rows and 3 columns public int i; public int j; public void matrixb() { matrixa(); Console.WriteLine("Enter the Matrix B elements\n"); { for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { matb[i, j] = Convert.ToInt32(Console.ReadLine()); } } }

} class MatrixAdd : MatrixB // Interfacing the matrix B to this class { public int[,] matc = new int[3, 3];//Declaring the matrix C to have 3 rows and 3 columns public int j; public int i; public void matadd() { matrixb(); Console.WriteLine("Matrix A is\n"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { Console.Write("\t" + mata[i, j]); } Console.WriteLine(); Console.WriteLine(); } Console.WriteLine("Matrix B is\n"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { Console.Write("\t" + matb[i, j]); } Console.WriteLine(); Console.WriteLine(); } Console.WriteLine("Matrix C is\n"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { matc[i, j] = mata[i, j] + matb[i, j]; Console.Write("\t" + matc[i, j]); } Console.WriteLine(); Console.WriteLine(); } } }

class Program { static void Main(string[] args) { MatrixAdd ma = new MatrixAdd(); // mm.matrixa();accessing the method by object // mm.matrixb(); ma.matadd();// accessing the parent classes through the derived class object by having the methods included in the class by interface } } 6. class MatrixA { public int[,] mata = new int[3, 3]; public int i;public int j; public void matrixa() { Console.WriteLine("Enter the Matrix A elements\n"); { for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { mata[i,j] = Convert.ToInt32(Console.ReadLine()); } } } }

} class MatrixB:MatrixA { public int[,] matb = new int[3, 3]; public int i; public int j; public void matrixb() { Console.WriteLine("Enter the Matrix B elements\n"); { for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { matb[i, j] = Convert.ToInt32(Console.ReadLine()); } }

} class MatrixMult:MatrixB // Interfacing the matrix A to this class { public int[,] matc = new int[3, 3]; public int j; public int i; public void matmul() { Console.WriteLine("Matrix A is"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) {

Console.Write("\t"+mata[i, j]); } Console.WriteLine(); Console.WriteLine(); } Console.WriteLine("Matrix B is"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { Console.Write("\t"+matb[i, j]); } Console.WriteLine(); Console.WriteLine(); } Console.WriteLine("Matrix C is"); for (i = 0; i < 3; i++) { for ( j = 0; j < 3; j++) { matc[i,j]=mata[i,j]*matb[i,j]; Console.Write("\t"+matc[i, j]); } Console.WriteLine(); Console.WriteLine(); } } class Program { static void Main(string[] args) { MatrixMult mm = new MatrixMult(); mm.matrixa(); mm.matrixb(); mm.matmul(); } } 7. class paramex { public static void parray(params int[] m) { Console .WriteLine("array elements"); foreach (int i in m) { Console.WriteLine(i); } } } namespace paramsusage { class Program { static void Main(string[] args) { int[] x ={ 1,2,3}; paramex. parray(x); paramex.parray(); paramex.parray(100,200); } } } 8. class ClassI { }

public int x; public int y; public ClassI() { Console.WriteLine(@" ClassI: Default Constructor is employed in this class ClassII: addition process done and the result is "); } } class ClassIII:ClassI { public ClassIII() { Console.WriteLine("Class III accessed"); } } class ClassII : ClassIII { public ClassII(int a, int b) { this.x = a; this.y = b; } public void adder() { int c = x + y; Console.WriteLine(c); } } namespace Inheritanceex { class Program { static void Main(string[] args) { ClassII c2 = new ClassII(5,5); c2.adder(); } } } 9. SUM OF DIGITS class SoDprocess { public void SoDcal(int a) { int b; int sum = 0; while (a != 0) { b = a % 10; a = a / 10; sum = sum + b; } Console.WriteLine("The sum of digits in given number is " + sum); } } namespace sumofdigitsclass { class Program { static void Main(string[] args) { int m; Console.WriteLine("Enter a number"); string ah = Console.ReadLine(); m = Int32.Parse(ah); SoDprocess sod = new SoDprocess();

sod.SoDcal(m); } } 10. namespace print_no_in_rev_order { class Program { static void Main(string[] args) { int[] input ={1,2,3,4,5,6,7,8,9,0}; { for (int i = 0; i < 10; i++) { input[i]=Int16 .Parse ( Console.ReadLine()); } // Array.Sort(input);// ascending sort Array.Reverse(input); foreach (int j in input) { Console .WriteLine (j); } } } } } 11. class Input { public int x; public int y; public Input() { } /* public Input(int a, int b) { this.x = a; this.y = b; }*/ public void printer() { for (int i = 1; i <= 500; i++) { Console.WriteLine(i); if (i == 100) { Console.WriteLine("101 to 199 skipped"); i = 200; } else if (i == 300) { Console.WriteLine("301 to 399 skipped"); i = 400; } } } } class Program { static void Main(string[] args) }

{ Input i = new Input(); i.printer(); } } 12. SWAPPING OF TWO NUMBERS class SwapInput { public int s; public int t; public SwapInput() // Default constructor {} public SwapInput(int x, int y) // Constructor with two arguments { this.s = x; this.t = y; } ~SwapInput() // Destructor {} public void swapper() { int temp; Console.WriteLine(@"Before swapping x=" + s + "\n\t\ty=" + t); temp = s; s = t; t = temp; Console.WriteLine(@"After swapping x=" + s + "\n\t\ty=" + t); } } class Program { static void Main(string[] args) { SwapInput si = new SwapInput(50,5); si.swapper(); } } 13. class methodregion { // public int a; public int b; public void add(int x, int y ,out int c) { c=x+y; Console.WriteLine(c); } public void sub(int a, int b) { int z=a-b; Console.WriteLine(z); } } class MainProgram { static void Main(string[] args) { methodregion mr = new methodregion(); int o; Console.WriteLine("Enter 1 to add and 2 to sub"); int m=Convert.ToInt16 (Console.ReadLine()); switch (m)

{ case 1: mr.add(5,5,out o); // invoking the method add from the class methodregion break; case 2: mr.sub(10, 5); // invoking the method sub from the class methodregion break; default: break; } } } 14. SORTING NUMBERS IN ASCENDING ORDER class Sort { /* public Sort(int a, int b, int c,int d) { this.a = a; this.b = b; this.c = c; this.d = d; }*/ public void sorter(int[] n) { for (int i = 0; i < 4; i++) { for (int j = i+1; j <4 ; j++) { if (n[i] > n[j]) { int t = n[i]; n[i] = n[j]; n[j] = t; } else { } } Console.WriteLine(n[i]);

} }

} namespace sortingnumbers { class Program { static void Main(string[] args) { Sort s = new Sort() ; int[] num ={ 22,10,67,4}; Console.WriteLine("Before sorting" ); foreach (int ar in num) { Console.WriteLine(+ar); } Console.WriteLine("The ascending sorted numbers are"); s.sorter(num); } } 15. TWO DIMENSIONAL ARRAY DECLARING AND INITIALIZATION class TwoDArray { public int[,]arr=new int[2,2]{{1,1},{2,2}};// Initializing the two dimensional array public string[,] name = new string[2, 2] { { "venkatesh","venkat" }, { "venu","vee" } }; }

public void arraydis() { } foreach(object i in arr) {Console .WriteLine(i);} public void arraydis1() { foreach (object i in name ) Console .WriteLine (i); } } class Program { static void Main(string[] args) { TwoDArray td = new TwoDArray(); td.arraydis(); td.arraydis1(); } } 16. FINDING LARGEST NUMBER public class Program { static void Main(string[] args) { Console.WriteLine("Enter any ten elements to compare for largest number"); large(); } public static void large() { int[] input =new input[10]; for (int i = 0; i < 9; i++) { int a = Convert.ToInt32 (Console.ReadLine()); input[i] = a; } for (int k = 1; k<9;k++ ) { if (input[0] > input[k]) { input[0] = input[k];} else { } } Console.WriteLine("Smallest no. is" + input[0]); } } 17. BANK ACCOUNT MGMT USING CONSTRUCTOR class AccMgmt { public int amt; public AccMgmt(int x) // Constructor with one argument { this.amt = x; } public string name = "Venkatesh"; public void benq() // method for balance enquiry

{ Console.WriteLine("\nName : {0}\n Balance : {1}",name ,amt ); } public void withdrawl(int w) // method for money withdrawl { if (w > amt) Console.WriteLine("Not sufficient balance you have only Rs: {0} in your account", amt); else { int b = amt - w; Console.WriteLine("Balance after your last transaction is" + b); } } public void deposit() // method for deposition { Console.WriteLine("Enter the amount to deposit"); int d = Int16.Parse(Console .ReadLine ()); int b = d + amt; Console.WriteLine("Your balance after your deposition of Rs {0} is {1}",d,b); }

} // Start of Main Program class Program { static void Main(string[] args) { AccMgmt am = new AccMgmt(10000); // passing the value to the constructor by object Console.WriteLine("\t\t\tWelcome to My Bank\n\n"); start: Console.WriteLine("Select your choice");

Console.WriteLine(@" 1.Balance Enquiry 2.Cash Withdrawl 3.Deposition 4.Exit"); int i=Int16.Parse(Console.ReadLine ()); switch (i) { case 1: am.benq(); Console.WriteLine("Would you like to have an other transaction. If yes press Y or press any key to exit"); string s=Console.ReadLine(); int n = string.Compare(s,"Y"); int nn = string.Compare(s, "y"); if(n==0 || nn==0) goto start; else break; case 2: Console.WriteLine("Enter the amount to withdraw "); int w = Int16.Parse(Console .ReadLine ()); am.withdrawl(w); Console.WriteLine("Would you like to have an other transaction. If yes press Y or press any key to exit"); string s1 = Console.ReadLine(); int n1 = string.Compare(s1, "Y"); int n11 = string.Compare(s1, "y"); if (n1 == 0 || n11==0)

goto start; else break; case 3: am.deposit(); Console.WriteLine("Would you like to have an other transaction. If yes press Y or press any key to exit"); string s2 = Console.ReadLine(); int n2 = string.Compare(s2, "Y"); int n21 = string.Compare(s2, "y"); if (n2 == 0 || n21==0) goto start; else break; case 4: break; default: Console .WriteLine ("Sorry wrong option select the correct choice"); goto start; } } } 18. FACTORIAL USING CLASS class factorial { public void fact(int a) { int b = a; int c = a; { for (int i = 1; i < c; i++) { b = b - 1; a = a * b; //a=a*(b-1); //b--; } } } Console.WriteLine("Factorial for:" + b + "is" + a);

} namespace factex { class MAinPgm { public static void Main(string [] args) { factorial fact=new factorial (); Console.WriteLine("Ehter a value to find the factorial"); string it=Console .ReadLine (); int i = Int32.Parse(it); Console.WriteLine(); fact.fact(i); } } } 19. SUM OF SQUARE OF DIGITS class squaredigit { int x;

public squaredigit(int a) { this. x = a; } public void process() { int ss = 0; while (x != 0) { int y = x % 10; x = x / 10; ss = ss + (y*y); } Console.WriteLine(ss); } } namespace squareofdigit { class MainPgm { public static void Main(string[] args) { squaredigit sd = new squaredigit(55); sd.process(); } } } 20. SCOPE AND VISIBILTY OF PRIVATE AND PUBLIC MEMBERS // Showing the scope of private and public members in class namespace scope_of_pub_pri_mem { class A { int a; int b; int c; // private members declares and hence the scope of the members are within this class A only and the method using this private members cannot be inherited nor accessed by the object of the derived class public A(int x, int y) { this.a = x; this.b = y; } public int add() { return c = a + b; } } class B { public void sub( int x, int y) { //add(); //The method cannot be called here since the members involved in this are private int c; //return c = x - y; c = x - y; Console.WriteLine("Subtraction result : "+c); } } class C:B // class B is inherited in to this class { public int a; public int b; public int c;

public void mul(int a,int b) { sub(a, b); // the members a and b since declared as public it is passed to the method sub() which is in class B c=a*b; Console .WriteLine ("Multiplication result: "+c); } } class Program { static void Main(string[] args) { A a = new A(5,5); int m=a.add(); Console.WriteLine("Addition result : " + m); B b = new B(); // b.sub();// cannot be accessed by object b of class B since it takes the input arguments from the

class C // int z=b.sub(45,5); // Console.WriteLine("Subtraction result : "+z); // b.add(); //cannot be accessed by the object b since it cannot pass any arguments to the private members of the class C c=new C (); c.mul(15,7); } } } 20. SWAPPING OF TWO NUMBERS WITHOUT USING A TEMPORARY VARIABLE namespace swapof2numwithouttempvaar { class Program { static void Main(string[] args) { int a; int b; a = Convert.ToInt16(Console.ReadLine()); b = Int16.Parse(Console.ReadLine() ); Console.WriteLine("Before swapping a={0} and b={1}", a, b); a = a + b; b = a-b; a = a-b; Console.WriteLine("After swapping a={0} and b={1}", a, b); } } 21. SIMPLE ARRAYLIST EXAMPLE using System; using System.Collections;// Remove the generic from it to make arraylist to work using System.Text; namespace ArrayListex { class Program { static void Main(string[] args) { }

} }

ArrayList a = new ArrayList();// Declaring the arraylist a.Add("a"); // Adding elements to arraylist a.Add("b"); a.Add("c"); foreach (string s in a) { Console.WriteLine(s); }

} 22. ARRAYLIST EXAMPLE USING CLASS using System; using System.Collections;// Remove the generic from it to make arraylist to work using System.Text; // ArrayList class usge: Accessed by the object of the main class namespace ArrayListex2 { class ArrayListExample // Class defined for declaring the array list { public void getdata() { ArrayList al = new ArrayList(); //ArrayList declaration al.Add("venkatesh"); // Adding elements to arraylist al.Add(1); // Adding elements to arraylist al.Add("name"); // Adding elements to arraylist foreach (object i in al) { Console.WriteLine(i); } } } class Program { static void Main(string[] args) { ArrayListExample ale = new ArrayListExample(); ale.getdata(); } } } 23. STRING SORTING USING ARRAY LIST class Program { static void Main(string[] args) { ArrayList name = new ArrayList();// Array list declaration name.Add("Venkatesh"); // Adding elements starting from the index 0 name.Add("Babu"); name.Add("Kumar"); name.Add("Ramesh"); Console .WriteLine ("\nBefore Sorting\n"); foreach (string j in name) { Console.WriteLine(j); } Console.WriteLine("\nAfter sorting\n"); name.Sort(); foreach (string i in name) {

Console.WriteLine(i); } } 24. STRING SORTING USING ARRAY class Program { static void Main(string[] args) { string[] name ={ "venkat","kumar","zebastin","karna"}; Console.WriteLine("Before Sorting "); foreach (string j in name) { Console.WriteLine(j); } Console.WriteLine("After Sorting "); Array.Sort(name); foreach (string i in name) { Console.WriteLine(i); } } } 25. // PROGRAM TO SHOW HOW TO ACCESS THE MEMBER WHICH IS DECLARED AS A STATIC MEMBER class StatMemAcc { public static void disp() { Console.WriteLine("Static member is accessed"); } } namespace staticmemberaccess { class Program { static void Main(string[] args) { StatMemAcc.disp(); } } } 26. class stringarray { public static void Main() { string[] name=new string[] {"Mon", "Tue", "Wed"}; {foreach(object i in name) {Console.WriteLine(i);} } } } 27. // STRUCTURE is a value type // It cannot be inherited // STRUCTURE can have constructor and methods as like CLASS. // It does not support default constructor // It does not support INHERITANCE }

namespace Structure2 { public struct baseclass { public int c; public int x; public int y; // public baseclass() // default constructor not possible in structures //{ } public baseclass(int a, int b) { // this.x = a; 'this' keyword is required for assigning for the variable which are alike // this.y = b; // this.c = a + b; x = a; y = b; c = a + b; } public void disp(baseclass b) { baseclass m; m.c = x+b.c; m.x = x + b.x; m.y = y + b.y; Console.WriteLine("c={0}\nx={1}\ny={2}",m.c,m.x,m.y); } } class MainProgram { static void Main(string[] args) { baseclass b = new baseclass(5, 4);// structure initialization b.disp(b); Console.WriteLine(b.c); } } } 28. namespace structex3 { struct details {public string name; public string adr; public int phn;public int pin; public string cty; public details(string n, string adr, int phn, int pin, string cty) { this.name = n; this.adr = adr; this.phn = phn; this.pin = pin; this.cty = cty; } public void getdet(details d) { // Console.WriteLine(" Name: {0}\nAddr: {1}\n City: {2}\n Pin no. :{3}\n Phone no. : {4}\n",d.name ,d.adr,d.cty ,d.pin ,d.phn ); Console.WriteLine(" Name: {0}\nAddr: {1}\n City: {2}\n Pin no. :{3}\n Phone no. :{4}\n", name, adr, cty, pin, phn); } } class Program { static void Main(string[] args)

{ Console.WriteLine("Enter your name"); string a = Console.ReadLine(); Console.WriteLine("Address"); string b = Console.ReadLine(); Console .WriteLine ("city"); string c = Console.ReadLine(); Console.WriteLine("Pin no"); int d = Int32.Parse(Console .ReadLine ()); Console.WriteLine("phone no."); int e = Int32.Parse(Console .ReadLine ()); details dt =new details (a,b,e,d,c); dt.getdet(dt); } } } Output: Enter your name Venkatesh Address geetha nagar city trichy Pin no 620017 phone no. 0 Name: Venkatesh Addr: geetha nagar City: trichy Pin no. :620017 Phone no. :0 29. namespace Structure_example { struct Example { public int x; public int y; /* public Example() Structures cannot have a default constructor { }*/ public Example(int a, int b) // But structures can have the constructor with arguments { this.x = a; this.y = b; } public Example structaccess(Example e) // Structure employed as a datatype for both the input and output arguments { Example ex; // object created for the structure ex.x = x + e.x; // Accessing the variable by object ex.y = y + e.y; return ex; // returning the object } } class Program { static void Main(string[] args) { Example el = new Example(5, 5); // invoking the constructor class with input

Example v; v=el.structaccess(el); Console.WriteLine(v.x + v.y); } } }

Programming Concepts
Here are a few basic programming concepts to help you get started. I focus on concepts which are important to C and C++ programming, because that is what I'm trying to explain. Other languages have different emphasis, or perhaps entirely different concepts.

Bits and Bytes


Computers only deal with numbers. Even though when you are programming you may be dealing with letters of the alphabet, to the computer these are all numbers which just happen to represent letters. Furthermore, a computer doesn't even understand digits from zero to nine; it only really understands one and zero. When you write down a large number each digit represents a power of ten (ones, tens, hundreds, thousands). The computer, basically, deals with any number larger than one in the same way, with each digit representing a power of two (ones, twos, fours, eights and so on). This system, binary arithmetic, can represent any number that normal decimal arithmetic (with powers of ten) can. Each digit (zero or one) in binary arithmetic is called a binary digit or bit. Computers often deal with these bits in groups which allow them to store a certain range of numbers:

A byte is a group of eight bits, which can represent 256 different values (integers from 0 to 255 for example, or 256 different letters and symbols). A byte is sometimes also called an octet, usually in connection with communications systems (like the protocols used on the Internet). A word is a larger group of bytes. In Win32 programming a word is usually regarded as two bytes, or 16 bits (this is a holdover from the days before Win32; the 32 in Win32 stands for 32-bits to differentiate it from the old 16-bit system). A group of four bytes, or 32 bits, is called a double-word.

Representation
To a computer everything is a number. A picture is just a big list of numbers which happen to mean what colors get drawn where on a screen. A novel is just a different big list of numbers, where some of the numbers represent letters and others represent the font (shape of characters to be displayed) or things like the size of the page.

At the fundamental level, everything in a computer is a string of bits. For convenience, these strings of bits are arranged in groups (bytes or words). Furthermore, different meaning can be assigned to the same group of bits or bytes. The arrangement of bits to carry a certain meaning or value can be called the representation. For example, a single byte can represent numbers between 0 and 255. This is called the unsigned integerrepresentation of a byte. However, a single byte can also represent numbers between -128 and 127. Because this allows numbers with a sign to be represented, this is called the signed integer representation of the byte. A single byte can also represent a letter (A, B, C... Y, Z) or symbol (#, $, %). This is called the character representation. A collection of bytes can represent a word or sentence, and this is called a string. A word might also represent an address in memory. A number of bytes together can represent a real number (with a decimal point, like 3.14123), called the floating point representation. There is no limit on the set of possible representations (although only a certain set of the possible representations are standard).

Memory
A computer's memory is a very large set of bytes in which it stores the numbers (and letters and so on, but they're really all just bits) that it is using at the moment. When you write a letter using a word processor for example, the computer loads the word processing program file into memory, and also keeps the letter in memory as you write it. When you have finished the letter you can save it, and exit the word processor program, which is then discarded from memory along with your letter (but the files stay on disk where you can use them to load the program again later). I say the memory is a collection of bytes because the bytes are arranged and numbered in order from zero to some very large number (if you have 128 Mbytes of memory for example, the bytes are numbered from zero to 134,217,727). The number of each byte is called its address.

Program
This is important. The whole point of programming is to create programs, so it's important to know what a program is. A program is a list of step by step instructions telling the computer how to do something. Computers are very stupid, so they need explicit, detailed, step-by-step instructions in order to do anything. Reading a file from a disk into memory, displaying a word on the screen, and so on are all accomplished by telling the computer exactly which signals need to be sent to the hardware (the disk drive, or the video controller) at what time. A collection of these instructions strung together to make the computer do something useful (or at least do something) is a program.

File
A file is a collection of data stored together under one name on a disk (or some other permanent media). The computer must read the data from a file into memory before it can do anything with it, and in order to save data so that it will not be lost when the computer is turned off (or the program ends), the data will usually have to be written to a file.

Variables
A variable in math is a symbol representing an arbitrary number. In programming, a variable is also a symbol (the variable name) which represents an arbitrary number (the value of the variable). However, that is pretty much where the similarity ends. In math you write and manipulate equations to prove things which are true for all possible values of a variable, or to find the set of possible values for which the equation is true. In programming a variable has a particular value at any given time, and the reason it is called a variable is because that value can be changed as the program runs. A variable can be used to store a number input by a user, or the position of the mouse (periodically updated), or the result of a calculation, and so on. Each variable in C or C++ has a type. The type of a variable determines its size in memory (the number of bytes it takes to store) and its representation, such as int for integer words, char for character bytes, and float for floating point numbers. There is more on variables in C and C++ in the section on Variables.

Assignment and Arithmetic


Variables can be used to perform arithmetic. That is, you can add, subtract, multiply and divide using variables (as well as ordinary numbers, or constants). You have to assign the result of such arithmetic to a variable (or otherwise make use of it immediately). Thus the following statement:
x = y + 4;

This assigns the result of adding four to the current value of the variable y to the variable x. Note that this is very different from what the same set of symbols means in math. To further illustrate, the following doesn't make much sense in math:
x = x + 1;

There is no (ordinary) number which is equal to itself plus one, which is what the above would mean in math, but in programming it is perfectly ordinary and results in the variable x having a value one greater after the statement has been performed.

Functions
Again functions in programming are something like functions in math. In math a function is something that takes a number or set of numbers and produces a result (generally another number or set of numbers). A function in C programming can take a number (or any combination of variables and constants) and can return a single value. For example, a (trivial) function that adds two numbers and returns the sum could look like this:
int Add (int x, int y) { return (x + y); }

The first line says that "Add is a function that takes two integer arguments, x and y, and returns an integer." The stuff (or code) inside the braces {} tells the computer how to accomplish the function. In this case, it tells the computer to add together x and y and then return the result. Each C program starts with a single function, usually called main, from which all other functions are called. The real reason to use functions is to structure your program so that it is easier to write, more efficient, more flexible and easier to change. Consider, for example, if you were writing a program to show a list of information about people in your electronic address book. Say you design the program to take a name and display all the entries that match the name, showing either the phone number or the address of the person. You could write this as one long main function. However, it would be much better to break it down into smaller functions. For example:

A function to read the option settings and arguments (the name to search for, and whether it is phone numbers or addresses). If the user didn't enter the data properly this function could call another function to display some help. A function which takes a name and fills in a list with the data (probably a structure) for each entry matching the name. It does this by calling a function which finds the next entry matching the name repeatedly until it reaches the end of the address book. A function which displays a list of phone numbers from the list obtained by the function above. A function which displays a list of addresses from the list obtained by the function above.

If you do this then the main function could look something like this:
int main (int argc, char* argv[]) { struct option_t options; /* A structure to hold the options settings */ struct person_t* list; /* A pointer to the first entry in the list */ /* Read the options and fill the options structure. */ if (!read_options (argc, argv, &options)) { /* Reading options failed. Stop. */ return -1; } /* Get the list of people matching the name. */ if (!get_list (options.name, &list)) { /* No matches. Stop. */ printf ("No names match!\n"); return 1; } /* Print the list of phone numbers or addresses */ if (options.phone_numbers_flag) { print_phone_numbers (list); } else { print_addresses (list); }

/* Finished, clean up and exit. */ free_list (list); return 0;

Although there are a lot of details in there that probably don't make much sense right now, even a novice can see basically what is happening. Even without the comments it wouldn't be very difficult. On the other hand, if everything was in one long function it would be very difficult to figure out what the program was supposed to do. Also, if you want to change the way options are set, or the format used to print the entries, you don't have to change this function at all, only the function which reads the options or prints the report.

Flow Control
Flow control is a general term for deciding what gets done next in a program. There are a number of generally useful forms that show up in many programming languages including C. See the section on Flow Control and Statement Blocks for more detailed information.
If, then, else

Perhaps the simplest form of flow control is a statement which is performed if some condition is met. In C, for example, the following fragment of code will output (using a function called printf) the words "x is too small" if x is less than 10:
if (x < 10) { printf ("x is too small\n"); }

The part that gets executed if the condition is met is sometimes called the then clause. It is also possible to add statements which are executed if the condition is not met, for example:
if (x < 10) { printf ("x is too small\n"); } else { printf ("x is ok\n"); }

If the value of the variable x is greater or equal to ten, "x is ok" is output. The set of statements executed when the condition is not met is called, appropriately enough, the else clause.
Loops

A loop is a block of code that can be executed more than once. In C there are three types of loop, but probably the easiest one to understand is the 'while' loop. It looks like this:
c = getchar(); while (c != EOF) { printf ("%02x ", c); c = getchar(); /* Read a single character */ /* If not End Of File then... */ /* Print the value of the character */ /* Get another character */

This loop starts after the function getchar has been used to read a character into the variable c. If the character 'read' was a special end-of-file character then the loop doesn't get executed, and the program will continue after the final '}', otherwise printf is used to display the value of the character (in hexadecimal, just to make it interesting) and another character is read. At that point the loop checks the condition "c != EOF" again and, if c is not EOF, does the loop again. It will keep running the loop until the condition "c != EOF" is false, that is, until the special EOF character is returned by getchar.

Pointers
Pointers are very important in C, and still pretty important in C++, but they are often very difficult for new programmers to understand and use. Recall that the computer has a memory divided into bytes, and that each byte of that memory has an address. Each variable in your program is stored somewhere in the computer's memory, and therefore there is an address for that variable. A pointer is a variable which stores an address, so it can point to another variable. Below is a simple example of pointers and the operators '&' ("address of"), and '*' ("the variable pointed to by"). Don't worry if it doesn't make perfect sense. I'll try to explain in more detail in the section on pointers.
int x = 10; int* px; px = &x; printf ("%d\n", x); *px = 5; printf ("%d\n", x); /* Initialize an integer variable x with the value 10 */ /* Declare a variable px with the type "pointer to integer" */ /* /* /* /* Assign the address of x to px */ Prints the value of x, "10" */ Assign 5 to the variable pointed to by px (that is, x) */ Print the value of x again, now its "5"! */

The above example is pretty pointless, but in practice pointers make it possible to do some very useful things because they allow your code to choose which variables it works with at run time (that is, while the program is running and probably based on some sort of input one way or another). In addition to memory allocation (which allows you to create arbitrary new variables at run time) this is essential for almost any program. C++ insulates the programmer from some of the more mundane uses of pointers (for example, using pointers to create variable length lists and such), but you will still run into them with great regularity.

Data Structures
C and C++ offer certain basic types for variables which correspond to some different representations. However, sometimes you want to group together a set of data for some reason. For example, in the address book example above (under functions) we wanted to group together various pieces of information associated with a person, such as the name, address and phone number. For this you can use a structure. A structure is a set of variables grouped together, and structures themselves can be treated as variables. For the address book, say that each person has a name, address, telephone number, sex and age. We could define a structure like this:

struct person_t { char struct address_t int char unsigned int };

name[64]; address; telephone; sex; age;

/* /* /* /* /*

A 64-character array for the name */ An address structure for the address */ The telephone number, stored as an integer */ The sex, stored as a single character ('M' or 'F') */ The age, stored as an unsigned integer. */

That is not really a great structure, but it would do the job. Notice that a structure can contain other structures, like the address structure above (that would have to be defined as well, but I haven't shown the definition). Then we could define variables of the "person" type and use them for various things. For example, we could write a function which read in the data for a person input by the user and then another function which searched for the 'best match' for that person.
struct person_t search_for, found; get_person_from_user (&search_for); find_match (&search_for, &found); display_person (&found);

Classes
In C++ there is a type of structure called a class (or, from a C++ perspective, a structure is just a kind of class). A class is a way of representing an abstract object. Like a structure, a class contains data about the object it represents. However, a class also has functions. For example, if we defined a person class corresponding to the structure defined in the example above (under data structures), it could have member functions which performed tasks related to the object, such as filling it with user input data, or displaying the contents:
class cPerson { // Declarations of various data members go here... public: void Display (); void GetFromUser (); };

Then the code fragment to get a person's data from the user and then search for a match could look like this:
cPerson search_for, found; search_for.GetFromUser(); Match (&search_for, &found); found.Display();

For more on why this can be a good thing (and the other things that classes can do), read Stroustrup's book, or any number of other books on object oriented programming.

Here are Some Important C Programs For Beginners 1)

Swapping two numbers (using two variables) - SWAPTWO.C

Code:
# include <stdio.h> # include <conio.h> void main() { int a, b ; clrscr() ; printf("Enter two numbers : ") ; scanf("%d %d", &a, &b) ; printf("\nBefore swapping : \n\n") ; printf("a = %d \t b = %d", a, b) ; a = a + b ; b = a - b ; a = a - b ; printf("\n\nAfter swapping : \n\n") ; printf("a = %d \t b = %d", a, b) ; getch() ; } /*RUN 1 : ~~~~~~~ Enter two numbers : 10 20 Before swapping : a = 10 b = 20 After swapping : a = 20 b = 10*/

2)

Program to find the sum of digits of an integer - DIGITSUM.C

Code:
# include <stdio.h> # include <conio.h> void main() { int n, r, s = 0 ; clrscr() ; printf("Enter a number : ") ; scanf("%d", &n) ; while(n > 0) { r = n % 10 ; s = s + r ; n = n / 10 ; } printf("\nThe sum of the digits is : %d", s) ; getch() ; } /*RUN 1 : ~~~~~~~ Enter a number : 12345 The sum of the digits is : 15*/

3)

Program to find the sum of fibonacci series - SUMFIBO.C


Code:
# include <stdio.h> # include <conio.h> void main() { int a = -1, b = 1, c = 0, i, n, sum = 0 ; clrscr() ; printf("Enter the limit : ") ; scanf("%d", &n) ; printf("\nThe fibonacci series is : \n\n") ; for(i = 1 ; i <= n ; i++) { c = a + b ; printf("%d \t", c) ; sum = sum + c ; a = b ; b = c ; } printf("\n\nThe sum of the fibonacci series is : %d", sum) ; getch() ; } /*RUN 1 : ~~~~~~~ Enter the limit : 5 The fibonacci series is : 0 1 1 2 3 The sum of the fibonacci series is : 7*/

4)

To find the given no. is perfect no. or not - CHKPERNO.C


Code:
# include <stdio.h> # include <conio.h> # include <math.h> void main() { int i, n, s = 0 ; clrscr() ; printf("Enter a number : ") ; scanf("%d", &n) ; for(i = 1 ; i < n ; i++) { if(n % i == 0) s = s + i ; } if (s == n) printf("\n%d is a perfect number", n) ; else printf("\n%d is not a perfect number", n) ; getch() ; } /*RUN 1 : ~~~~~~~ Enter a number : 6 6 is a perfect number RUN 2 : ~~~~~~~ Enter a number : 28

28 is a perfect number RUN 3 : ~~~~~~~ Enter a number : 12 12 is not a perfect number */

5)

To check whether the given no. is prime or not - CHKPRIME.C

Code:
# include <stdio.h> # include <conio.h> void main() { int i, n, flag = 0 ; clrscr() ; printf("Enter the Number : ") ; scanf("%d", &n) ; if(n <= 3) flag = 0 ; else { for(i = 2 ; i <= n / 2 ; i++) if(n % i == 0) { flag = 1 ; break ; } } if(flag == 1) printf("\nThe number is not prime") ; else printf("\nThe number is prime") ; getch() ; } /*RUN 1 : ~~~~~~~ Enter the Number : 6 The number is not prime RUN 2 : ~~~~~~~ Enter the Number : 11 The number is prime */

You might also like