+ All Categories
Home > Documents > Sample Cprog

Sample Cprog

Date post: 06-Apr-2018
Category:
Upload: starirayako
View: 221 times
Download: 0 times
Share this document with a friend

of 22

Transcript
  • 8/3/2019 Sample Cprog

    1/22

    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:

    http://www.loirak.com/prog/ctutor.php#firsthttp://www.loirak.com/prog/ctutor.php#datahttp://www.loirak.com/prog/ctutor.php#loopshttp://www.loirak.com/prog/ctutor.php#pointershttp://www.loirak.com/prog/ctutor.php#functionshttp://www.loirak.com/prog/ctutor.php#otherhttp://www.loirak.com/prog/ctutor.php#otherhttp://www.loirak.com/prog/ctutor.php#firsthttp://www.loirak.com/prog/ctutor.php#datahttp://www.loirak.com/prog/ctutor.php#loopshttp://www.loirak.com/prog/ctutor.php#pointershttp://www.loirak.com/prog/ctutor.php#functionshttp://www.loirak.com/prog/ctutor.php#otherhttp://www.loirak.com/prog/ctutor.php#other
  • 8/3/2019 Sample Cprog

    2/22

    gcc hello.c

    If you are using *Nix you should have an a.outfile 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 togetting 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 youwill need a separate compiler for this tutorial. The reason is the gcc with thedevkit advance is for the gameboy, so the code it generates will not run on aPC, also becuase the gameboy has no standard font built in, you will not beable to see the output of the printf statement, basically the above programwill do nothing.

    This creates an executable file a.out, which is then executed simply by typing its name. Theresult 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 yourprogram 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 abovestdio.hcontains 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.

    http://www.delorie.com/djgpp/http://www.delorie.com/djgpp/http://msdn.microsoft.com/visualc/http://www.loirak.com/gameboy/gbatutor.phphttp://www.delorie.com/djgpp/http://www.delorie.com/djgpp/http://msdn.microsoft.com/visualc/http://www.loirak.com/gameboy/gbatutor.php
  • 8/3/2019 Sample Cprog

    3/22

    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

    void main(){

    int numcandy; // declare a number variabledouble cost; // declare a variable that can store decimals

    printf("How many lollipops do you want: ");scanf("%d", &numcandy); // get input from usercost = 0.55 * numcandy; // do some mathprintf("\nPlease pay %f to the cashier!\n", cost);

    }

    This program when run, well prompt the user for how many lollipops they would like. After theyenter 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 ofprintfto 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 arethe 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 variableof type integer with the name numcandy. Then you can simply use numcandy through out yourprogram 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 thescanf, andprintfstatements. After running the program you will notice that thescanf

    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 thescanfandprintf. First theprintfhas the sequence "\n". This

    sequence simply means move to the next line. Next we have the %fand %d. These tellprintfandscanfwhat type of variables to expect. %fcorresponds 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 sinceprintfwould try to print costas an integer, which doesn't make sense, because costis 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 variableshort -> short integer

  • 8/3/2019 Sample Cprog

    4/22

    long -> long integerfloat -> single precision real (floating point) variabledouble -> double precision real (floating point) variablechar -> 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 integer (optional n = number of columns; if 0, pad with zeroes)%m.nf float or double (optional m = number of columns,

    n = number of decimal places)%ns string (optional n = number of columns)%c character\n \t 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.

  • 8/3/2019 Sample Cprog

    5/22

    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 willdescribe 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, andswitch.

    Here is the syntax forifand else:

    if (condition_1){

    ...block of statements executed if condition_1 is true

    ...statements are either more ifs and conditions or normalnormal lines of code that end with semi-colons}else if (condition_2){

    ...statements executed if condition_2 is true and condition_1 wasfalse

    }else{

    ...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 ifinside of another if. Now that wecan make an ifwe 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.

    < smaller than= greater than or equal to> greater than

    and the boolean operators

    && and|| or! not

    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!");

  • 8/3/2019 Sample Cprog

    6/22

    }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

  • 8/3/2019 Sample Cprog

    7/22

    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. Cprovides two basic types of loops a while and aforloop. While andforloops continue to repeat

    basically until certain conditions are met. Here is the syntax forwhile andforloops:

    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:

  • 8/3/2019 Sample Cprog

    8/22

    expression_1;

    while (expression_2){

    ...block of statements...

    expression_3;}

    For instance, the following structure is often encountered:

    i = initial_i;

    while (i

  • 8/3/2019 Sample Cprog

    9/22

    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

    #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 ourconstant

    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 neededbreak; // exit out of the while loop

    else if (numcandy > MAX_AT_ONCE || numcandy numberlollipopps)

    {printf("You cannot have that many, enter another

    number\n");

    }else{

    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);

    }

  • 8/3/2019 Sample Cprog

    10/22

    4. Pointers and Arrays

    The C language takes a lot of flack for its ability to peek and poke directly intomemory. 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 noticethe 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 scanfstatements. 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 thatlocation. 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 3ptrX = &var_x; when we entered the program. Whatwould 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

  • 8/3/2019 Sample Cprog

    11/22

    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 programwill 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 explanationof the code and arrays will follow

    #include #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 characterprintf("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 Str along 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 probablywondering 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, andthen 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.

  • 8/3/2019 Sample Cprog

    12/22

    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 linepStr = &Str[0];. Now pStr points to thestart 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 ofi. The linepStr++; may

    seem a bit confusing. C has a bunch of short cuts to manipulate variables the ++ just means addone to the variable (in this case it moves the pointer to the next element in the array). The ++

    syntax here is equivalent topStr = 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. Youshould 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: intarrayofint[5];.

    5. Functions

    This part should be quite simple compared to the last part. Functions are easy touse; 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 ofprintf 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 isaccomplished through the use of header files (like stdio.h) which contain all the necessary

    information. The most commonly used header files are

    -> defining I/O routines -> defining string manipulation routines -> defining mathematical routines -> defining number conversion, storage allocation

    and similar tasks -> defining libraries to handle routines with variable

    numbers of arguments -> defining time-manipulation routines

  • 8/3/2019 Sample Cprog

    13/22

    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;}

    Ifreturn-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 whathappen if the variables are passed by value:

    #include

    void exchange(int a, int b);

    void main(){ /* WRONG CODE */

    int a, b;

    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);

    }

    http://www.loirak.com/prog/ctutor.php#otherhttp://www.loirak.com/prog/ctutor.php#other
  • 8/3/2019 Sample Cprog

    14/22

    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 thedeclaration. The next code segment will fix exchange to use pointers, and move

    exchange above main to eliminate the need for the forward declaration.

    #include

    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(){ /* RIGHT CODE */

    int a, b;

    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 thosearguments

    You MUST use pointers if the function changes the values of those arguments

  • 8/3/2019 Sample Cprog

    15/22

    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

    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);

    }

  • 8/3/2019 Sample Cprog

    16/22

    There is a function in C which allows the programmer to accept input from a keyboard. The

    following program illustrates the use of this function,

    #include

    main() /* program which introduces keyboard input */{

    int number;

    printf("Type in a number \n");scanf("%d", &number);

    printf("The number you typed was %d\n", number);}

    Sample Program Output

    Type in a number

    23The number you typed was 23

    An integer called numberis defined. A prompt to enter in a number is then printed using thestatement

    printf("Type in a number \n:");

    Thescanfroutine, which accepts the response, has two arguments. The first ("%d") specifies

    what type of data type is expected (ie char, int, or float). List of formatters for scanf() found here.

    The second argument (&number) specifies the variable into which the typed response will be

    placed. In this case the response will be placed into the memory location associated with the

    variable number.

    This explains the special significance of the & character (which means the address of).

    http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_057.htmhttp://gd.tuwien.ac.at/languages/c/programming-bbrown/c_057.htm
  • 8/3/2019 Sample Cprog

    17/22

    Sample program illustrating use of scanf() to read integers, characters and floats

    #include < stdio.h >

    main(){

    int sum;char letter;float money;

    printf("Please enter an integer value ");scanf("%d", &sum );

    printf("Please enter a character ");/* the leading space before the %c ignores space characters in

    the input */scanf(" %c", &letter );

    printf("Please enter a float variable ");scanf("%f", &money );

    printf("\nThe variables you entered were\n");printf("value of sum = %d\n", sum );printf("value of letter = %c\n", letter );printf("value of money = %f\n", money );

    }

    Sample Program Output

    Please enter an integer value34

    Please enter a characterWPlease enter a float variable32.3The variables you entered werevalue of sum = 34value of letter = Wvalue of money = 32.300000

    Answers: Practise Exercise 3: printf() and scanf()

    1. Use a printf statement to print out the value of the integer variable sum

    printf("%d", sum);

    2. Use a printf statement to print out the text string "Welcome", followed by a newline.

  • 8/3/2019 Sample Cprog

    18/22

    printf("Welcome\n");

    3. Use a printf statement to print out the character variable letter

    printf("%c", letter);

    4. Use a printf statement to print out the float variable discount

    printf("%f", discount);

    5. Use a printf statement to print out the float variable dump using two decimal places

    printf("%.2f", dump);

    6. Use a scanf statement to read a decimal value from the keyboard, into the integer variable sum

    scanf("%d", &sum);

    7. Use a scanf statement to read a float variable into the variable discount_rate

    scanf("%f", &discount_rate);

    8. Use a scanf statement to read a single character from the keyboard into the variable operator.

    Skip leading blanks, tabs and newline characters.

    scanf(" %c", &operator);

    C program to find both the largest and smallest numbers in the given list?

    Fist of all, let's assume that by "list" you mean "array." Otherwise we would need your list

    implementation in order to be able to iterate through the elements.

    int[] nums; // assume these are the numbers you want to search through

    int nums_length; // also assume that we know how many numbers are in nums

    int min; // smallest number in nums

    int max; // largest number in nums

  • 8/3/2019 Sample Cprog

    19/22

    // special case for an empty list of numbers: set min = max = 0

    if(nums_length == 0) {

    min = 0;

    max = 0;

    }else {

    // start min and max off as equal to the first number

    min = nums[0];

    max = nums[0];

    // iterate through nums

    int i;

    for(i = 1; i < nums_length; ++i) {

    // update max, if necessary

    if( nums[i] > max ) {

    max = nums[i];

    }

    // update min, if necessary

    if(nums[i] < min) {

    min = nums[i];

    }

    }

    }

    // min and max are now properly set (or both equal to 0 if nums is empty)

  • 8/3/2019 Sample Cprog

    20/22

    Example 1:

    Write a C program that calculates the sum of two input numbers, and display the result.

    Algorithm:

    Input Enter two numbers (n1,n2)

    Process Compute the sum (sum=n1+n2)

    Output Display the sum (sum)

    Solution:

    #include

    main ( )

    {

    int sum, n1,n2;

    clrscr ( );printf (\n Enter two nos.);

    scanf (%d%d, &n1, &n2);

    sum=n1+n2;

    printf (\n The sum: %d, sum);

    getch ( );

    }

    Example 2:

    Write a program to calculate the area of a circle and display the result. Use the formula: A=?r2

    where Pi (?) is approximately equal to 3.1416.

    Algorithm:

    Input Enter the radius (r)

    Process Compute the Area (A=Pi*r*r)

    Output Display the Area (A)

    Solution:

    #include

    #define Pi 3.1416main ( )

    {

    int r;

    flaot A;

    clrscr ( );

    printf (\n Enter the radius:);

    scanf (%d, &r);

  • 8/3/2019 Sample Cprog

    21/22

    A=Pi*r*r;

    printf (\n The area: %f,A);

    getch ( );

    }

    Example 3:

    Write a program that computes the average of three input quizzes, then display the result.

    Algorithm:

    Input Enter three quizzes (q1,q2,q3)

    Process Compute the average (ave=(q1+q2+q3/3)

    Output Display the average (ave)

    Solution:

    #include

    main ( )

    {

    int q1,q2,q3;

    flaot ave;

    clrscr ( );

    printf (\n Enter three quizzes:);

    scanf (%d%d%d,&q1,&q2,&q3);

    ave= (q1+q2+q3) /3;

    printf (\n The average:%f,ave);

    getch ( );}

    Example 4:

    Write a program that converts the input Fahrenheit degree into its Celsius degree equivalent. Use

    the formula: C=(5/9) *F-32. Display the result.

    Algorithm:

    Input Enter the Fahrenheit (f)

    Process Compute the Celsius (C=(5.0/9.0)*F-32.0)Output Display the Celsius

    Solution:

    #include

    main ( )

  • 8/3/2019 Sample Cprog

    22/22

    {

    float c,f;

    clrscr ( );

    printf (\n Enter the Fahrenheit:);

    scanf (%f, &f);

    c= (5.0/9.0)*f-32.0;printf (\n the Celsius:%f,c);

    getch ( );

    }


Recommended