core c programming programming assignment chapter 6

Snapsolve any problem by taking a picture. Try it in the Numerade app?

Programming in C

Stephen g. kochan, working with arrays - all with video answers.

Chapter Questions

Type in and run the eight programs presented in this chapter. Compare the output produced by each program with the output presented after each program in the text.

Modify Program 6.1 so that the elements of the array values are initially set to 0 . Use a for loop to perform the initialization.

Program 6.2 permits only 20 responses to be entered. Modify that program so that any number of responses can be entered. So that the user does not have to count the number of responses in the list, set up the program so that the value 999 can be keyed in by the user to indicate that the last response has been entered.

Write a program that calculates the average of an array of 10 floatingpoint values.

What output do you expect from the following program?

Willis James

You don't need to use an array to generate Fibonacci numbers. You can simply use three variables: two to store the previous two Fibonacci numbers and one to store the current one. Rewrite Program 6.3 so that arrays are not used. Because you're no longer using an array, you need to display each Fibonacci number as you generate it.

Prime numbers can also be generated by an algorithm known as the Sieve of Eratosthenes. The algorithm for this procedure is presented here. Write a program that implements this algorithm. Have the program find all prime numbers up to $\mathrm{n}=150$. What can you say about this algorithm as compared to the ones used in the text for calculating prime numbers?

Find out if your compiler supports variable-length arrays. If it does, write a small program to test the feature out.

  • C Programming Home
  • ▼C Programming Exercises
  • Basic Declarations and Expressions
  • Basic Part-II
  • Basic Algorithm
  • Variable Type
  • Input - Output
  • Conditional Statements
  • Do-While Loop
  • Linked List
  • Callback function
  • Variadic function
  • Inline Function
  • File Handling
  • Searching and Sorting
  • C Programming Exercises, Practice, Solution

What is C Programming Language?

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs. It has since become one of the most widely used programming languages of all time, with C compilers from various vendors available for the majority of existing computer architectures and operating systems.

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with C programming.

Hope, these exercises help you to improve your C programming coding skills. Currently, following sections are available, we are working hard to add more exercises. Please refer to this page for important C snippets, code, and examples before starting the exercises. Happy Coding!

List of C Programming Exercises :

  • Basic Declarations and Expressions [ 150 Exercises with Solution ]
  • Basic Part-II [ 7 Exercises with Solution ]
  • Basic Algorithm [ 75 Exercises with Solution ]
  • Variable Type [ 18 Exercises with Solution ]
  • Input, Output [ 10 Exercises with Solution ]
  • Conditional Statement [ 26 Exercises with Solution ]
  • While Loop [ 11 Exercises with Solution ]
  • Do-While Loop [ 12 Exercises with Solution ]
  • For Loop [ 61 Exercises with Solution ]
  • Array [ 107 Exercises with Solution ]
  • Structure [ 9 Exercises with Solution ]
  • Pointer [ 22 Exercises with Solution ]
  • Linked List [ 64 Exercises with Solution ]
  • Stack [ 17 Exercises with Solution ]
  • Binary Heap (Tree-Based Structure) [ 9 Exercises with Solution ]
  • Queue [ 13 Exercises with Solution ]
  • Hash [ 10 Exercises with Solution ]
  • Tree [ 10 Exercises with Solution ]
  • Graph [ 10 Exercises with Solution ]
  • Numbers [ 38 Exercises with Solution ]
  • Math [ 38 Exercises with Solution ]
  • String [ 41 Exercises with Solution ]
  • Date Time [ 10 Exercises with Solution ]
  • Function [ 12 Exercises with Solution ]
  • Callback Function [ 11 Exercises with Solution ]
  • Variadic Function [ 8 Exercises with Solution ]
  • Inline Function [ 11 Exercises with Solution ]
  • Recursion [ 21 Exercises with Solution ]
  • File Handling [ 19 Exercises with Solution ]
  • Search and Sorting [ 31 Exercises with Solution ]
  • Challenges [ 35 exercises with solution ]
  • C Snippets [29]
  • More to Come !

[ Want to contribute to C exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • PHP Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • R Programming Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Chapter  5: Introduction to C Programming Embedded Systems - Shape The World

Jonathan Valvano and Ramesh Yerraballi

This chapter covers the C Programming language starting with the structure, constants and variable declarations, the main subroutine, simple input/output, arithmetic expressions, Boolean expressions, the assignment statement, the while loop and lastly simple functions with at most one input and one output. It has been updated to include C99 syntax.

, , ( and ) , , ; and for I/O. -statement and the statement and how they use the conditional Boolean expression.

                  

 Video 5.0. Introduction to Programming in C

   

5.0 Introduction

This course presents the art and science of designing embedded systems. In this module we will introduce C programming. If you need to write a paper, you decide on a theme, and then begin with an outline. In the same manner, if you design an embedded system, you define its specification (what it does) and begin with an organizational plan. In this chapter, we will present three graphical tools to describe the organization of an embedded system: flowcharts , data flow graphs , and call graphs . You should draw all three for every system you design. In this section, we introduce the flowchart syntax that will be used throughout the class. Programs themselves are written in a linear or one-dimensional fashion. In other words, we type one line of software after another in a sequential fashion. Writing programs this way is a natural process, because the computer itself usually executes the program in a top-to-bottom sequential fashion. This one-dimensional format is fine for simple programs, but conditional branching and function calls may create complex behaviors that are not easily observed in a linear fashion. Flowcharts are one way to describe software in a two-dimensional format, specifically providing convenient mechanisms to visualize conditional branching and function calls. Flowcharts are very useful in the initial design stage of a software system to define complex algorithms. Furthermore, flowcharts can be used in the final documentation stage of a project, once the system is operational, in order to assist in its use or modification.

Where does one begin when learning a new skill? To me, I begin software development with the question, “What is it the program is supposed to do?” Next, I think of how I will test it. Testing is essentially a mechanism to see if the program does exactly what it is supposed to do, no more no less. Next, I list what are the inputs, and what are the outputs. Inside the system we have data. The data defines what do I know, so I define the data and give some examples. The software algorithm connects the inputs to the data, and software must connect the data to the outputs. Lastly, I test it. So you see I begin with testing and end with testing.

We will use flowcharts to illustrate what the software does (Figure 5.1).  The oval shapes define entry and exit points. The main entry point  is the starting point of the software. Each function, or subroutine, also has an entry point. The exit point   returns the flow of control back to the place from which the function was called. When the software runs continuously, as is typically the case in an embedded system, there will be no main exit point. We use rectangles to specify process blocks. In a high-level flowchart, a process block might involve many operations, but in a low-level flowchart, the exact operation is defined in the rectangle. The parallelogram will be used to define an input/output operation. Some flowchart artists use rectangles for both processes and input/output. Since input/output operations are an important part of embedded systems, we will use the parallelogram format, which will make it easier to identify input/output in our flowcharts. The diamond-shaped objects define a branch point or conditional block. Inside the diamond we can define what is being tested. Each arrow out of a condition block must be labeled with the condition causing flow to go in that direction. There must be at least two arrows out of a condition block, but there could be more than two. However, the condition for each arrow must be mutually exclusive (you can’t say “if I’m happy go left and if I’m tall go right” because it is unclear what you want the software to do if I’m happy and tall). Furthermore, the complete set of conditions must define all possibilities (you can’t say “if temperature is less than 20 go right and if the temperature is above 40 go left” because you have not defined what to do if the temperature is between 20 and 40). The rectangle with double lines on the side specifies a call to a predefined function . In this book, functions, subroutines, and procedures are terms that all refer to a well-defined section of code that performs a specific operation. Functions usually return a result parameter, while procedures usually do not. Functions and procedures are terms used when describing a high-level language, while subroutines are often used when describing assembly language. When a function (or subroutine or procedure) is called, the software execution path jumps to the function, the specific operation is performed, and the execution path returns to the point immediately after the function call. Circles are used as connectors . A connector with an arrow pointing out of the circle defines a label or a spot in the algorithm. There should be one label connector for each number. Connectors with an arrow pointing into the circle are jumps or goto commands. When the flow reaches a goto connector, the execution path jumps to the position specified by the corresponding label connector. It is bad style to use a lot of connectors.

Figure 5.1. Flowchart symbols.

There are a seemingly unlimited number of tasks one can perform on a computer, and the key to developing great products is to select the correct ones. Just like hiking through the woods, we need to develop guidelines (like maps and trails) to keep us from getting lost. One of the fundamentals when developing software, regardless whether it is a microcontroller with 1000 lines of assembly code or a large computer system with billions of lines of code, is to maintain a consistent structure. One such framework is called structured programming. C is a structured language, which means we begin with a small number of simple templates, as shown in Figure 5.2. A good high-level language will force the programmer to write structured programs. Structured programs in C are built from three basic templates: the sequence , the conditional , and the while-loop . At the lowest level, the “block” contains simple and well-defined commands, like Area = Height*Width; I/O functions are also low-level building blocks. To program in C, we combine existing structures into more complex structures. Each of the “blocks” in Figure 5.2 is either a simple well-defined command or another structure.

Figure 5.2. Flowchart showing the basic building blocks of structured programming.

Example 5.1: Using a flowchart describe the control algorithm that a toaster might use to cook toast. There will be a start button the user pushes to activate the machine. There is other input that measures toast temperature. The desired temperature is preprogrammed into the machine. The output is a heater, which can be on or off. The toast is automatically lowered into the oven when heat is applied and is ejected when the heat is turned off.

Solution: This example illustrates a common trait of an embedded system, that is, they perform the same set of tasks over and over forever. The program starts at main when power is applied, and the system behaves like a toaster until it is unplugged. Figure 5.3 shows a flowchart for one possible toaster algorithm. The system initially waits for the operator to push the start button. If the switch is not pressed, the system loops back reading and checking the switch over and over. After the start button is pressed, heat is turned on. When the toast temperature reaches the desired value, heat is turned off, and the process is repeated.

Figure 5.3. Flowchart illustrating the process of making toast.

Safety tip: When dealing with the potential for fire, you may want to add some safety features such as a time out or an independent check for temperature overflow.

Observation: The predefined functions in this chapter do not communicate any data between the calling routine and function. Data passed into a function are called input parameters, and data passed from the function back to the calling routine are called output parameters.

Observation: Notice in Figure 5.3 we defined a function Cook even though it was called from only one place. You might be tempted to think it would have been better to paste the code for the function into the one place it was called. There are many reasons it would be better to define the function as a separate software object: it will be easier to debug because there is a clear beginning and end of the function, it will make the overall system simpler to understand, and in the future we may wish to reuse this function for another purpose.

Interactive Tool 5.1

The following tool allows you to see the ordered sequence of steps (labeled A-H) executed as you interact with the Switch to give an input. When the code is executing in the Event handler subroutine you can click on the switch to turn it on and off and see the timeline (at the bottom) reflect this.

No picture

Example 5.2. The system has one input and one output. An event should be recognized when the input goes from 0 to 1 and back to 0 again. The output is initially 0, but should go 1 after four events are detected. After this point, the output should remain 1. Design a flowchart to solve this problem.

Solution: This example also illustrates the concept of a subroutine. We break a complex system into smaller components so that the system is easier to understand and easier to test. In particular, once we know how to detect an event, we will encapsulate that process into a subroutine, called Event . In this example, the main program first sets the output to zero, calls the function Event four times, then it sets the output to one. To detect the 0 to 1 to 0 edges in the input, it first waits for 1, and then it waits for 0 again. The letters A through H in Figure 5.4 specify the software activities in this simple example. In this example, execution is sequential and predictable.

Figure 5.4. Flowchart illustrating the process waiting for four events.

Before we write software, we need to develop a plan. Software development is an iterative process. Even though we list steps the development process in a 1,2,3,4 order, in reality we cycle through these steps over and over. I like to begin with step 4), deciding how I will test it even before I decide what it does.

1) We begin with a list of the inputs and outputs. This usually defines what the overall system will do. We specify the range of values and their significance.

2) Next, we make a list of the required data. We must decide how the data is structured, what does it mean, how it is collected, and how it can be changed.

3) Next we develop the software algorithm, which is a sequence of operations we wish to execute. There are many approaches to describing the plan. Experienced programmers can develop the algorithm directly in C language. On the other hand, most of us need an abstractive method to document the desired sequence of actions. Flowcharts and pseudo code are two common descriptive formats. There are no formal rules regarding pseudo code, rather it is a shorthand for describing what to do and when to do it. We can place our pseudo code as documentation into the comment fields of our program. Next we write software to implement the algorithm as define in the flowchart and pseudo code.

4) The last stage is debugging. Learning debugging skills will greatly improve the quality of your software and the efficiency at which you can develop code. 

5.1 Background

We will use C in this class for two reasons. First, over the last ten years, it has ranked one or two out of all high-level languages. Second, C is by far the most common language for writing software for embedded systems.

Figure 5.5. Graph of popular programming languages over time.  http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

1

1

C

17.809%

+0.08%

2

2

Java

16.656%

+0.39%

3

4

Objective-C

10.356%

+1.26%

4

3

C++

8.819%

-0.54%

5

7

PHP

5.987%

+0.70%

6

5

C#

5.783%

-1.24%

7

6

(Visual) Basic

4.348%

-1.70%

8

8

Python

4.183%

+0.33%

9

9

Perl

2.273%

+0.05%

10

11

JavaScript

1.654%

+0.18%

11

10

Ruby

1.479%

-0.20%

12

12

Visual Basic .NET

1.067%

-0.15%

13

17

Transact-SQL

0.913%

+0.21%

14

14

Lisp

0.879%

-0.11%

15

16

Pascal

0.779%

-0.07%

16

21

Bash

0.711%

+0.09%

17

19

PL/SQL

0.657%

+0.02%

18

13

Delphi/Object Pascal

0.602%

-0.55%

19

18

Ada

0.575%

-0.11%

20

22

MATLAB

0.563%

0.00%

Table 5.1. Top 20 popular programming languages. http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

                  

                     Video 5.1 . History of the C Programming Language

C is a general-purpose programming language initially developed by Dennis Ritchie between 1969 and 1973 while at AT&T Bell Labs, see Figure 5.6. At the time, there were programming languages called A and another named B, so Ritchie decided to name his language C. Dennis Ritchie and Brian Kernighan wrote the first book on C, The C Programming Language .  Ritchie was also one of the developers of the Unix operating system.

core c programming programming assignment chapter 6

Figure 5.6. Dennis MacAlistair Ritchie

As C became more popular, many derivative languages were introduced. C++ was developed by Bjarne Stroustrup 1979-1983 also at Bell Labs. C++ is a language originally called “C plus classes”. In 1999, a professional standard version of C, called C99, was defined. When you download Tivaware (http://www.ti.com/tool/sw-tm4c) from Texas Instruments, you will notice TI’s example code for the TM4C123 has been written in C99. In this class however, we will use the more simple C language.

A compiler is system software that converts a high-level language program (human readable format) into object code (machine readable format). It produces software that is fast but to change the software we need to edit the source code and recompile.

C code ( z = x+y; ) → Assembly code ( ADD R2,R1,R0 )  → Machine code ( 0xEB010200 )

An assembler is system software that converts an assembly language program (human readable format) into object code (machine readable format).

Assembly code ( ADD R2,R1,R0 )  → Machine code ( 0xEB010200 )

An interpreter executes directly the high level language. It is interactive but runs slower than compiled code. Many languages can be compiled or interpreted. The original BASIC (Beginner's All-purpose Symbolic Instruction Code) was interpreted. This means the user typed software to the computer, and the interpreter executed the commands as they were typed. In this class, an example of the interpreter will be the command window while running the debugger. For more information on this interpreter, run Keil uVision and execute Help->uVisionHelp . Next, you need to click the Contents tab, open the uVisionIDEusersGuide , and then click DebugCommands . It will show you a list of debugger commands you can type into the command window.

A linker builds software system by connecting (linking) software components. In Keil uVision, the build command ( Project->BuildTarget ) performs both a compilation and a linking. The example code in this module has three software components that are linked together. These components are

     startup.s      uart.c      main.c

A loader will place the object code in memory. In an embedded system, the loader will program object code into flash ROM. In Keil uVision, the download command ( Flash->Download ) performs a load operation.

A debugger is a set of hardware and software tools we use to verify system is operating correctly. The two important aspects of a good debugger are control and observability.

5.2 Structure and Organization of C

In assembly language, symbols placed at the beginning of each line have special meaning. On the contrary, C is a free field language . Except for preprocessor lines that begin with #, spaces, tabs and line breaks have the same meaning. This means we can place more than one statement on a single line, or place a single statement across multiple lines. We could write a function without any line breaks. Since we rarely make hardcopy printouts of our software, it is not necessary to minimize the number of line breaks. Furthermore, we could have added extra line breaks. I prefer the style of the program on the right because each line contains one complete thought or action. As you get more experienced, you will develop a programming style that is easy to understand. Although spaces, tabs, and line breaks are syntactically equivalent, their proper usage will have a profound impact on the readability of your software. The following three functions are identical; I like the third one.




 return(M);
}


  M = 1664525*M+1013904223;
  return(M);

Program 5.1. Three equivalent functions that return a random number.

Another situation where spaces, tabs and line breaks matter is string constants. We cannot type tabs or line breaks within a string constant. The characters between the first " and second " define the string constant. A string is a set of ASCII characters terminated with a 0. For example, the following C code will output my name:

                  printf("Jonathan Valvano");

The variable M , the function Random , the operation * , and the keyword long are tokens in C Each token must be contained on a single line. We see in the above example that tokens can be separated by white spaces, which include space, tab, line break, or by special characters. Special characters include punctuation marks (Table 5.2) and operations (Table 5.4).

End of statement

Defines a label

Separates elements of a list

Start and end of a parameter list

Start and stop of a compound statement

Start and stop of a array index

Start and stop of a string

Start and stop of a character constant

Table 5.2. Special characters can be punctuation marks.

Punctuation marks (semicolons, colons, commas, apostrophes, quotation marks, braces, brackets, and parentheses) are very important in C. It is one of the most frequent sources of errors for both the beginning and experienced programmers.

There are four sections of a C program as shown in Program 5.2. The first section is the documentation section, which includes the purpose of the software, the authors, the date, and any copyright information. When the software involves external hardware we will add information about how the external hardware is connected. The second section is the preprocessor directives. We will use the preprocessor directive #include to connect this software with other modules. We use diamond braces to include system libraries, like the standard I/O, and we use quotes to link up with other user code within the project. In this case the uart module is software we wrote to perform I/O with the universal asynchronous receiver/transmitter ( uart ). We will discuss modular programming in great detail in this class. The third section is global declarations section. This section will include global variables and function prototypes for functions defined in this module. The last section will be the functions themselves. In this class we will use the terms subroutine, procedure, function, and program interchangeably. Every software system in C has exactly one main program, which define where it begins execution.

//**** 0. Documentation Section //  This program calculates the area of square shaped rooms //  Author: Ramesh Yerraballi & Jon Valvano //  Date: 6/28/2013 // // 1. Pre-processor Directives Section #include <stdio.h>  // Diamond braces for sys lib: Standard I/O #include "uart.h"   // Quotes for user lib: UART lib // 2. Global Declarations section // 3. Subroutines Section // MAIN: Mandatory routine for a C program to be executable int main(void) {   UART_Init();  // call subroutine to initialize the uart   printf("This program calculates areas of square-shaped rooms\n"); }

Program 5.2. Software to calculate the area of a square room.

                     Video 5.2 . Your first C Program (in Keil) from scratch

There are two types of comments. The first type explains how to use the software. These comments are usually placed at the top of the file, within the header file, or at the start of a function. The reader of these comments will be writing software that uses or calls these routines. The second type of comments assists a future programmer (ourselves included) in changing, debugging or extending these routines. We usually place these comments within the body of the functions. The comments on the right of each line are examples of the second type.

Preprocessor directives begin with # in the first column. As the name implies preprocessor commands are processed first. I.e., the compiler passes through the program handling the preprocessor directives. Although there are many possibilities (assembly language, conditional compilation, interrupt service routines), I thought I’d mention the two most important ones early in the class. We create a macro using #define   to define constants.

#define SIZE 10

Basically, wherever SIZE is found as a token, it is replaced with the 10 . A second important directive is the #include , which allows you to include another entire file at that position within the program. The #include  directive will include the file named tm4c123ge6pm.h at this point in the program. This file will define all the I/O port names for the TM4C123.

#include "tm4c123ge6pm.h"

5.3 Variables and Expressions

Variables are used to hold information. In C, we define a variable by specifying the name of the variable and the type. Table 5.3 lists the possible data types.

Data type

C99 Data type

Precision

Range

8-bit unsigned

0 to +255

8-bit signed

-128 to +127

compiler-dependent

 

compiler-dependent

 

16-bit unsigned

0 to +65535

16-bit signed

-32768 to +32767

unsigned 32-bit

0 to 4294967295L

signed 32-bit

-2147483648L to 2147483647L

32-bit float

±10-38 to ±10+38 

64-bit float

±10-308 to ±10+308

Table 5.2. Data types in C. C99 includes the C types.

On the Keil compiler, there is an option to specify whether char all by itself without a signed or unsigned before it is considered signed or unsigned. Keil considers int as 32 bits. In this class we will avoid int and use long for 32-bit variables so there is no confusion. We will assume char is signed, but it is good practice to see exactly how char and int are treated by your compiler.

Variables declared outside of a function, like M in Program 5.1, are properly called external variables because they are defined outside of any function. While this is the standard term for these variables, it is confusing because there is another class of external variable, one that exists in a separately compiled source file. In this document we will refer to variables in the present source file as globals, and we will refer to variables defined in another file as externals. There are two reasons to employ global variables. The first reason is data permanence. The other reason is information sharing. Normally we pass information from one module to another explicitly using input and output parameters, but there are applications like interrupt programming where this method is unavailable. For these situations, one module can store data into a global while another module can view it.

Local variables are very important in C programming. They contain temporary information that is accessible only within a narrow scope. We can define local variables at the start of a compound statement. We call these local variables since they are known only to the block in which they appear, and to subordinate blocks. The variables side and area in Program 5.3 are local. In C, local variable must be declared immediately after a brace { that begins a compound statement. Unlike globals, which are said to be static, locals are created dynamically when their block is entered, and they cease to exist when control leaves the block. Furthermore, local names supersede the names of globals and other locals declared at higher levels of nesting. Therefore, locals may be used freely without regard to the names of other variables. Although two global variables cannot use the same name, a local variable of one block can use the same name as a local variable in another block. Programming errors and confusion can be avoided by understanding these conventions. Local variables are implemented in registers or allocated on the stack.

Program 5.3 illustrates the assignment operator. Notice that in the line side=3; the side is on the left hand side of the = . The left side of the assignment specifies the address into which the data transfer will occur. On the other hand, if we were to wrote area=side; the side is on the right hand side of the = . The right side of an assignment statement will evaluate into a value, which specifies the data to be transferred. Notice that the line area=side; creates two copies of the data. The original value remains in side , while area also contains this value. As mentioned above, variables have a type (Table 5.3), and the expression on the right of an assignment statement must evaluate to a value of that same type. If side has the value 3, the expression side*side evaluates to a 9, and the 9 is stored into the variable area . The printf is used to output the results to the uart port.

int main(void) {   unsigned long side; // room wall meters   unsigned long area; // size squared meters   UART_Init();        // call subroutine to initialize the uart   side = 3;   area = side*side;   printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area); }

Program 5.3. Simple program illustrating variables and assignment statements.

                     Video 5.3 . Variables and Assignment operation

Program 5.4 illustrates the arithmetic operations of addition, subtraction, multiplication and division. In the operation x+4*y , multiplication has precedence over addition. Table 5.4 lists the operators available in the C language.

void main(void){ long x,y,z;    // Three local variables    x=1; y=2;   // set the values of x and y    z = x+4*y;  // arithmetic operation      x++;        // same as x=x+1;          y--;        // same as y=y-1;         x = y<<2;   // left shift same as x=4*y;          z = y>>2;   // right shift same as x=y/4;         y += 2;     // same as y=y+2;       }

Program 5.4. Simple program illustrating C arithmetic operators.

Assignment statement

 

Equal to comparison

Selection

 

Less than or equal to

Less than

 

Greater than or equal to

Greater than

 

Not equal to

Logical not (true to false, false to true)

 

Shift left

1’s complement

 

Shift right

Addition

 

Increment

Subtraction

 

Decrement

Multiply or pointer reference

 

Boolean and

Divide

 

Boolean or

Modulo, division remainder

 

Add value to

Logical or

 

Subtract value to

Logical and, or address of

 

Multiply value to

Logical exclusive or

 

Divide value to

Used to access parts of a structure

 

Or value to

 

 

And value to

 

 

Exclusive or value to

 

 

Shift value left

 

 

Shift value right

 

 

Modulo divide value to

 

 

Pointer to a structure

Table 5.4. Special characters can be operators; operators can be made from 1, 2, or 3 characters.

As with all programming languages the order of the tokens is important. There are two issues to consider when evaluating complex statements. The precedence of the operator determines which operations are performed first. In expression z=x+4*y , the 4*y is performed first because * has higher precedence than + and =. The addition is performed second because + has higher precedence than =. The assignment = is performed last. Sometimes we use parentheses to clarify the meaning of the expression, even when they are not needed. Therefore, the line z=x+4*y; could have been written as z=(x+4*y); z=(x+4*y); or z=(x+(4*y));

The second issue is the associativity . Associativity determines the left to right or right to left order of evaluation when multiple operations of equal precedence are combined. For example + and - have the same precedence, so how do we evaluate the following?

          z = y-2+x;

We know that + and - associate the left to right, this function is the same as z=(y-2)+x; . Meaning the subtraction is performed first because it is more to the left than the addition. Most operations associate left to right, but the Table 5.5 illustrates that some operators associate right to left.

Observation: When confused about precedence (and aren't we all) add parentheses to clarify the expression.

Precedence

Operators

Associativity

Highest

  (postfix)  (postfix)

Left to right

 

(prefix)   (prefix)   (type) (unary)

  (unary)   (address)   (dereference)

Right to left

 

Left to right

 

Left to right

 

Left to right

 

Left to right

 

Left to right

 

Left to right

 

Left to right

 

Left to right

 

Left to right

 

Left to right

 

Right to left

 

Right to left

Lowest

Left to right

Table 5.5. Precedence and associativity determine the order of operation.

Checkpoint 5.1 : Which C data type does one use for numbers in the range of 0 to 200?

Checkpoint 5.2 : Which C data type does one use for numbers in the range of -10 to +10?

Checkpoint 5.3 : Which C data type does one use for numbers in the range of -1000 to +1000?

Checkpoint 5.4 : Which C data type does one use for numbers in the range of zero to a million?

Checkpoint 5.5 : What is the range of values possible with a C data type of int ?

Checkpoint 5.6 : Add parentheses to clarify this expression    x&1&&y+1<z*4 ;

5.4 Functions

A function is a sequence of operations that can be invoked from other places within the software. We can pass zero or more parameters into a function. A function can have zero or one output parameter. It is important for the C programmer to distinguish the two terms declaration and definition. A function declaration specifies its name, its input parameters and its output parameter. Another name for a function declaration is prototype . A data structure declaration specifies its type and format. On the other hand, a function definition specifies the exact sequence of operations to execute when it is called. A function definition will generate object code, which are machine instructions to be loaded into memory that perform the intended operations. A data structure definition will reserve space in memory for it. The confusing part is that the definition will repeat the declaration specifications. The C compiler performs just one pass through the code, and we must declare data/functions before we can access/invoke them. To run, of course, all data and functions must be defined. A function to calculate the area of a square room is shown in Program 5.5. We can see that the declaration shows us how to use the function, not how the function works. Because the C compilation is a one-pass process, an object must be declared or defined before it can be used in a statement. Actually the preprocessor performs the first pass through the program that handles the preprocessor directives.  A top-down approach is to first declare a function, use the function, and lastly define the function as illustrated in Program 5.5.

unsigned long Calc_Area(unsigned long s); int main(void) {   unsigned long side; // room wall meters   unsigned long area; // size squared meters   UART_Init();  // call subroutine to initialize the uart   printf("This program calculates areas of square-shaped rooms\n");   side = 3;   area = Calc_Area(side);   printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area);   side = side+2;   area = Calc_Area(side);   printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area); } // Calculates area // Input:  side of a room (unsigned long) in meters // Output: area of the room (unsigned long) in square meters unsigned long Calc_Area(unsigned long s) {   unsigned long result;   result = s*s;   return(result); }

Program 5.5. A main program that calls a function. In this case the declaration occurs first.

A bottom-down approach is to first define a function, and then use the function as illustrated in Program 5.6. In the bottom up approach, the definition both declares its structure and defines what it does.

// Calculates area // Input:  side of a room (unsigned long) in meters // Output: area of the room (unsigned long) in square meters unsigned long Calc_Area(unsigned long s) {   unsigned long result;   result = s*s;   return(result); } int main(void) {   unsigned long side; // room wall meters   unsigned long area; // size squared meters   UART_Init();  // call subroutine to initialize the uart   printf("This program calculates areas of square-shaped rooms\n");   side = 3;   area = Calc_Area(side);   printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area);   side = side+2;   area = Calc_Area(side);   printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area); }

Program 5.6. A main program that calls a function. In this case the definition occurs before its use.

                     Video 5.4 . Functions in C

Interactive Tool 5.2

Assembly Code Registers
Address Machine Code Label Instruction Comment

0x00000660 EB010200 sum ADD R2,R1,R0 ;z=x+y
0x00000664 4610 MOV R0,R2 ;return value
0x00000666 4770 BX LR
0x00000668 F44F60FA main MOV R0,#2000 ;first parameter
0x0000066C F44F61FA MOV R1,#2000 ;second parameter
0x00000670 F7FFFFF6 BL sum ;call function
0x00000674 4603 MOV R3,R0 ;a=sum(2000,2000)
0x00000676 F04F0400 MOV R4,#0x00 ;b=0
0x0000067A 4620 loop MOV R0,R4 ;first parameter
0x0000067C F04F0101 MOV R1,#0x01 ;second parameter
0x00000680 F7FFFFEE BL sum ;call function
0x00000684 4604 MOV R4,R0 ;b=sum(b,1)
0x00000686 E7F8 B loop
Register Value
R0 0x00000000
R1 0x00000000
R2 0x00000000
R3 0x00000000
R4 0x00000000
R5 0x00000000
R6 0x00000000
R7 0x00000000
R8 0x00000000
R9 0x00000000
R10 0x00000000
R11 0x00000000
R12 0x00000000
R13(SP) 0x00000000
R14(LR) 0x00000000
R15(PC) 0x00000668

Program 5.7. A function with two inputs and one output.

To specify the absence of a parameter we use the expression void . The body of a function consists of a statement that performs the work. Normally the body is a compound statement between a {} pair. If the function has a return parameter, then all exit points must specify what to return.

Checkpoint 5.7 : What does it mean to say a function as one input parameter?

Checkpoint 5.8 : What does it mean to say a function as one output parameter?

5.5 Conditional branching and loops

In Program 5.8 we will introduce a simple conditional control structure. Assume the global variable error is initialized to zero. The goal is to make sure the function is being used properly. An effective software design approach is to test the input parameters of a function to make sure the values make sense. An unsigned long can represent a number up to 4 billion. Clearly the system is not operating properly if we are trying to calculate the size of a room with 4 billion meter sides. In this case, we define the largest possible room to have a side of 25 meters.  The expression s<=25 will return true if the side is less than or equal to 25 and will return a false if the side is strictly greater than 25. The statement immediately following the if will be executed if the condition is true . The statement immediately following the else will be executed if the condition is false .

unsigned long error; // Calculates area // Input:  side of a room (unsigned long) // Output: area of the room (unsigned long) // Notes: ... unsigned long Calc_Area(unsigned long s) {   unsigned long result;   if(s <= 25){     result = s*s;   }else{     result = 0; // mistake     error = error +1;   }   return(result); }

Program 5.8. Simple program illustrating the C if else control structure.

The goal in program 5.9 is to test the Calc_Area function. Like the if statement, the while statement has a conditional test (i.e., returns a true/false). The statement immediately following the while will be executed over and over until the conditional test becomes false.

int main(void) {   unsigned long side; // room wall meters   unsigned long area; // size squared meters   UART_Init();  // call subroutine to initialize the uart   printf("This program calculates areas of square-shaped rooms\n");   side = 1;   while(side < 50){     area = Calc_Area(side);     printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area);     side = side+1;   } }

Program 5.9. Simple program illustrating the C while control structure.

The for control structure has three parts and a body.

     for(part1;part2;part3){body;}

In Program 5.10, the first part side=1 is executed once at the beginning. Before the body is executed, the end-condition part 2 is executed. If the condition is true , side<50 then the body is executed. After the body is executed, the third part is executed, side=side+1 . The second part is always a conditional that results in a true or a false . The body and third part are repeated until the conditional is false .

int main(void) {   unsigned long side; // room wall meters   unsigned long area; // size squared meters   UART_Init();  // call subroutine to initialize the uart   printf("This program calculates areas of square-shaped rooms\n");   for(side = 1; side < 50; side = side+1){     area = Calc_Area(side);     printf("\nArea of the room with side of %ld m is %ld sqr m\n",side,area);   } }

Program 5.10. Simple program illustrating the C for-loop control structure.

                     Video 5.5 . if-then conditional and while loop

Although C is a free field language, notice how the indenting has been added to programs in this book. The purpose of this indenting is to make the program easier to read. On the other hand since C is a free field language, the following two statements are quite different

if(n1>100) n2=100; n3=0; if(n1>100) {n2=100; n3=0;}

In both cases n2=100; is executed if n1>100. In the first case the statement n3=0; is always executed, while in the second case n3=0; is executed only if n1>100.

5.6 Keyboard input using scanf

  //**** 0. Documentation Section //  This program calculates the area of square shaped rooms //  Author: Ramesh Yerraballi & Jon Valvano //  Date: 6/28/2013 // // 1. Pre-processor Directives Section #include <stdio.h>  // Diamond braces for sys lib: Standard I/O #include "uart.h"   // Quotes for user lib: UART lib // 2. Global Declarations section // global variable unsigned long error; // Function Prototypes // Compiler aid for "type checking" void Initialize(void); unsigned long Calc_Area(unsigned long s); // Says Calc_Area expects             // an unsigned long and returns an unsigned long        // 3. Subroutines Section // MAIN: Mandatory routine for a C program to be executable int main(void) {   unsigned long side; // room wall meters   unsigned long area; // size squared meters   UART_Init();  // call subroutine to initialize the uart   Initialize();    printf("This program calculates areas of square-shaped rooms\n");   while(side != 0){     printf("Give room side(zero to quit):");     scanf("%ld", &side);     area = Calc_Area(side);     if(area != 0){       printf("\nArea with side of %ld m is %ld sqr m\n",side,area);     } else {       printf("\n Size cannot exceed 25 meters\n");     }   }   printf("Goodbye (Mistake count = %ld\n", error); } // Initialize global // Inputs: none // Outputs: none // Notes: void Initialize(void){   error = 0; } // Calculates area // Input:  side of a room (unsigned long) // Output: area of the room (unsigned long) // Notes: ... unsigned long Calc_Area(unsigned long s) {   unsigned long result;   if(s <= 25){     result = s*s;   }else{     result = 0; // mistake     error = error +1;   }   return(result);   } Program 5.11. Software to calculate the area of a square room.

                     Video 5.6 . scanf for getting user input and Debugging

5.7 C Keywords and Punctuation

C has predefined tokens, called keywords , which have specific meaning in C programs, as listed in Table 5.6. This section describes keywords and punctuation.

Specify a function is written in assembly code (specific to ARM Keil™ )

Specifies a variable as automatic (created on the stack)

Causes the program control structure to finish

One possibility within a statement

Defines a number with a precision of 8 bits

Defines parameter as constant in ROM, and defines a local parameter as fixed value

Causes the program to go to beginning of loop

Used in statement for all other cases

Used for creating program loops

Specifies variable as double precision floating point

Alternative part of a conditional

Defined in another module

Specifies variable as single precision floating point

Used for creating program loops

Causes program to jump to specified location

Conditional control structure

Defines a number with a precision that will vary from compiler to compiler

Defines a number with a precision of 32 bits

Specifies how to implement a local

Leave function

Defines a number with a precision of 16 bits

Specifies variable as signed (default)

Built-in function returns the size of an object

Stored permanently in memory, accessed locally

Used for creating data structures

Complex conditional control structure

Used to create new data types

Always greater than or equal to zero

Used in parameter list to mean no parameter

Can change implicitly outside the direct action of the software.

Used for creating program loops

 Table 5.6. Keywords have predefined meanings.

The volatile  keyword disables compiler optimization, forcing the compiler to fetch a new value each time. We will use volatile  when defining I/O ports because the value of ports can change outside of software action. We will also use volatile  when sharing a global variable between the main program and an interrupt service routine. It is a good programming practice not to use these keywords for your variable or function names.

Punctuation marks  are very important in C. It is one of the most frequent sources of errors for both beginning and experienced programmers.

Semicolons  are used as statement terminators. Strange and confusing syntax errors may be generated when you forget a semicolon, so this is one of the first things to check when trying to remove syntax errors. Notice that one semicolon is placed at the end of every simple statement in Program 5.12. When executed, the function Step will output the pattern 10, 9, 5, 6 to Port D. The #define statement creates a substitution rule, such that every instance of STEPPER in the program is replaces with  (*((volatile unsigned long *)0x4000703C)) .

#define STEPPER (*((volatile unsigned long *)0x4000703C))

void Step(void){

   STEPPER = 10;

   STEPPER = 9;

   STEPPER = 5;

   STEPPER = 6;

Program 5.12. Semicolons are used to separate one statement from the next.

Preprocessor directives do not end with a semicolon since they are not actually part of the C language proper. Preprocessor directives begin in the first column with the # and conclude at the end of the line. Program 5.13 will fill the array DataBuffer with data read from the input Port A. We assume in this example that Port A has been initialized as an input. Notice that semicolons are used to separate the three fields of the for loop statement.

unsigned char DataBuffer[100];

#define GPIO_PORTA_DATA_R  (*((volatile unsigned long *)0x400043FC))

void Fill(void){ long j;

   for(j=0; j<100; j++){

    DataBuffer[j] = GPIO_PORTA_DATA_R ;

   }

Program 5.13. Semicolons are used to separate three fields of the for statement.

Colons terminate case , and default  prefixes that appear in switch  statements. In Program 5.14 one output to the stepper motor produced each time the function OneStep is called. The proper stepper motor sequence is 10–9–5–6. The default case is used to restart the pattern. For both applications of the colon (goto and switch), we see that a label is created that is a potential target for a transfer of control. Notice the use of colons in Program 5.14.

unsigned char Last=10;

void OneStep(void){

unsigned char theNext;

  switch(Last){

    case 10: theNext = 9; break;   // 10 to 9

    case 9: theNext = 5;  break;   // 9 to 5

    case 5: theNext = 6;  break;   // 5 to 6

    case 6: theNext = 10; break;   // 6 to 10

    default: theNext = 10;

  GPIO_PORTD_DATA_R = theNext;

  Last = theNext;   // set up for next call

Program 5.14. Colons are also used with the switch statement.

Commas  separate items that appear in lists. We can create multiple variables of the same type using commas.

unsigned short beginTime,endTime,elapsedTime;

Lists are also used with functions having multiple parameters, both when the function is defined and called. Program 5.15 adds two 16-bit signed numbers, implementing ceiling and floor. Notice the use of commas in Program 5.15.

short add(short x, short y){ short z;

  z = x+y;

  if((x>0)&&(y>0)&&(z<0))z = 32767;

  if((x<0)&&(y<0)&&(z>0))z = -32768;

  return(z);

void main(void){ short a,b;

  a = add(2000,2000)

  b = 0

  while(1){

    b = add(b,1);

Program 5.15. Commas separate the parameters of a function.

Lists can also be used in general expressions. Sometimes it adds clarity to a program if related variables are modified at the same place. The value of a list of expressions is always the value of the last expression in the list. In the following example, first thetime is incremented, next thedate is decremented, and then x is set to k+2 .

X = (thetime++, thedate--, k+2);

Apostrophes  are used to specify character literals. Assuming the function OutChar will display a single ASCII character, Program 5.16 will display the lower case alphabet.

void Alphabet(void){ unsigned char mych;

  for(mych='a'; mych<='z'; mych++){

    OutChar(mych); // Print next letter

  }     

Program 5.16. Apostrophes are used to specify characters.

Quotation marks  are used to specify string literals. Strings are stored as a sequence of ASCII characters followed by a termination code, 0. Program 5.17 will display “Hello World” twice.

const unsigned char Msg[]= "Hello World"; // string constant

void OutString(const unsigned char str[]){ int i;

  i = 0;

  while(str[i]){     // output until the 0 termination

    OutChar(str[i]); // Print next letter

    i = i+1;

void PrintHelloWorld(void){

  OutString("Hello World");

  OutString(Msg);

Program 5.17. Quotation marks are used to specify strings.

Braces  {} are used throughout C programs. The most common application is for creating a compound statement. Each open brace { must be matched with a closing brace }. Notice the use of indenting helps to match up braces. Each time an open brace is used, the source code is tabbed over using 2 spaces. In this way, it is easy to see at a glance the brace pairs.

Square brackets  enclose array dimensions (in declarations) and subscripts (in expressions).

Parentheses  enclose argument lists that are associated with function declarations and calls. They are required even if there are no arguments. As with all programming languages, C uses parentheses to control the order in which expressions are evaluated. Thus, (11+3)/2 yields 7, whereas 11+3/2 yields 12. Parentheses are very important when writing expressions.

5.8. Chapter 5 Quiz

5.1 Match the punctuation with its meaning

;     sEnd of statement

:     Defines a label

,     Separates elements of a list

( )   Start and end of a parameter list

{ }   Start and stop of a compound statement

[ ]   Start and stop of a array index

" "   Start and stop of a string

' '   Start and stop of a character constant

5.2 Match the variable type with its minimum and maximum value

Data type

Range

0 to +255

-128 to +127

0 to +65535

-32768 to +32767

0 to 4294967295L

-2147483648L to 2147483647L

5.3 Match the variable type with its precision

Data type

Precision

8 bits

16 bits

32 bits

5.4 Are the variables side and area local or global?   

5.5 The goal is to return true if and only if the input is a number between 0x30 and 0x39.   

long CheckInput(long input) {   if(( Input xxx 0x30) yyy (Input zzz 0x39)){

    return 1;

  } else{

    return 0; // false

a) What C code do you need to place in the xxx position of the program?  

b) What C code do you need to place in the yyy position of the program?  

c) What C code do you need to place in the zzz position of the program?  

Reprinted with approval from Embedded Systems: Introduction to ARM Cortex-M Microcontrollers , 2014, ISBN: 978-1477508992, http://users.ece.utexas.edu/~valvano/arm/outline1.htm

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, learn c programming.

C is one of the foundational programming languages used in the development of compilers, operating systems, and embedded systems where speed and efficiency matter.

It is considered the best language to start because it provides a strong understanding of fundamental coding concepts like data types, variables, loops, and functions.

With a competitive base salary, there is a significant demand for C developers in high-stake fields where high performance is essential.

In this guide, we will cover:

Beginner's Guide to C

Is c for you, best way to learn c, how to run c.

If you are simply looking to learn C step-by-step, you can follow our free tutorials in the next section.

These tutorials will provide you with a solid foundation in C and prepare you for the next step in your career.

Getting Started with C

Your First C Program

C Variables, Constants and Literals

C Data Types

C Input Output (I/O)

C Programming Operators

C if...else Statement

C while and do...while Loop

C break and continue

C switch Statement

C goto Statement

C Functions

C User-defined functions

Types of User-defined Functions in C Programming

C Recursion

C Storage Class

C Multidimensional Arrays

Pass arrays to a function in C

Relationship Between Arrays and Pointers

C Pass Addresses and Pointers

C Dynamic Memory Allocation

C Array and Pointer Examples

C Programming Strings

String Manipulations In C Programming Using Library Functions

String Examples in C Programming

C structs and Pointers

C Structure and Function

C File Handling

C Files Examples

C Keywords and Identifiers

C Precedence And Associativity Of Operators

C Bitwise Operators

C Preprocessor and Macros

C Standard Library Functions

Whether C is the right choice depends on what you want to accomplish and your career goals.

C from a Learning Perspective

If you are new to coding, learning C can help you build a strong programming foundation. However, when we compare the code of C with other modern languages like Python, C might seem a bit complex.

For example, the following programs perform the addition of two numbers in both C and Python.

As you can see, C code includes a lot of syntaxes to perform the same task.

That being said, programming languages like C++, Python, and Java are based on C, so it's relatively easier to switch to these languages once you have a good grasp of C.

You typically learn multiple languages throughout your career, so it's beneficial to have a thorough understanding of how everything works right from the start.

C as Career Choice

C is mainly used in high-performance modern applications like:

  • Embedded Systems Design
  • Operating Systems Development
  • Firmware Development
  • Kernel Design

Learning C offers significant benefits for your career opportunities if you are interested in building complex systems with high performance.

However, there are certain fields where choosing C might not be your best option. For example, if you are interested in web development, data science, machine learning, or mobile development, then C might not be the right answer.

In these cases, alternatives such as JavaScript for web development, Python for data science and machine learning, and Kotlin, Swift, or Java for mobile app development will be more suitable.

Ultimately, your career choice is important in deciding whether C is right for you.

There is no right or wrong way to learn C. It all depends on your learning style and pace.

In this section, we have included the best C learning resources tailored to your learning preferences, be it text-based, video-based, or interactive courses.

Text-based Tutorial

Best: if you are committed to learning C but do not want to spend on it

If you want to learn C for free with a well-organized, step-by-step tutorial, you can use our free C tutorials .

Our tutorials will guide you through C programming one step at a time, using practical examples to strengthen your foundation.

Interactive Course

Best: if you want hands-on learning, get your progress tracked, and maintain a learning streak

Learning to code is tough. It requires dedication and consistency, and you need to write tons of code yourself.

While videos and tutorials provide you with a step-by-step guide, they lack hands-on experience and structure.

Recognizing all these challenges, Programiz offers a premium Learn C Course that allows you to gain hands-on learning experience by solving challenges, building real-world projects, and tracking your progress.

Remember, there is no easy shortcut to learning coding!

Online Video

Best: if you are an audio-visual learner and learn by watching others code and following along

If you're more of a visual learner, we have created a C programming playlist for beginners that will guide you on your journey to C programming.

Additionally, you can also follow the C course from Freecodecamp .

Best: if you are a casual and hobby learner who wants to just get to know C

While it's possible to learn C from mobile apps, it's not the ideal way because writing code can be challenging. Additionally, it's difficult to build real-world projects with multiple files on mobile devices.

Nevertheless, you can use these apps to try things out.

Important: You cannot learn to code without developing the habit of writing code yourself. Therefore, whatever method you choose, always write code.

While writing code, you will encounter errors. Don't worry about them, try to understand them and find solutions. Remember, programming is all about solving problems, and errors are part of the process.

1. Run C in your browser.

We have created an online editor to run C directly on your browser. You don't have to go through a tedious installation process. It's completely free, and you can start coding directly.

how-to-install-c

2. Install C on Your computer.

Once you start writing complex programs and creating projects, you should definitely install C on your computer. It's needed especially when you are creating projects with multiple files and folders.

To install C on your device, you can use this guide.

how-to-install-c-2

Learn how you can install and use C on your own computer.

Programming Essentials in C: Chapter 6 Assignment (CLA) Exam Answers

How to find: Press “Ctrl + F” in the browser and fill in whatever wording is in the question to find that question/answer. If the question is not here, find it in Questions Bank .

NOTE: If you have the new question on this test, please comment Question and Multiple-Choice list in form below this article. We will update answers for you in the shortest time. Thank you! We truly value your contribution to the website.

1. What happens if you try to compile and run this program?

  • the program outputs nul
  • compilation fails
  • the program outputs NULL
  • the program outputs 0

2. What happens if you try to compile and run this program?

  • the program outputs an unpredictable value
  • the compilation fails

3. What happens if you try to compile and run this program?

  • the program outputs 1
  • the program outputs 2

4. What happens if you try to compile and run this program?

5. What happens if you try to compile and run this program?

6. What happens if you try to compile and run this program?

  • compilations fails

7. What happens if you try to compile and run this program?

8. What happens if you try to compile and run this program?

9. What happens if you try to compile and run this program?

10. What happens if you try to compile and run this program?

  • the program outputs 3

11. What happens if you try to compile and run this program?

12. What happens if you try to compile and run this program?

13. What happens if you try to compile and run this program?

14. What happens if you try to compile and run this program?

15. What happens if you try to compile and run this program?

16. What happens if you try to compile and run this program?

17. What happens if you try to compile and run this program?

18. What happens if you try to compile and run this program?

19. What happens if you try to compile and run this program?

20. What happens if you try to compile and run this program?

guest

quiz answers are not available which is been asked after completion of module

B.Durga Sony

Answer plzz

16245361769211210164289825852137.jpg

are you solving Cisco c programming course test ? me too.

  • HTML Cheat Sheet
  • CSS Cheat Sheet
  • JS Cheat Sheet
  • Bootstrap Cheat Sheet
  • jQuery Cheat Sheet
  • Angular Cheat Sheet
  • Facebook SDE Sheet
  • Amazon SDE Sheet
  • Apple SDE Sheet
  • Netflix SDE Sheet
  • Google SDE Sheet
  • Wipro SDE Sheet
  • Infosys SDE Sheet
  • TCS SDE Sheet
  • Cognizant SDE Sheet
  • HCL SDE Sheet
  • Mass Recruiters Sheet
  • Product-Based Coding Sheet
  • Company-Wise Practice Sheet
  • Love Babbar Sheet

C Cheat Sheet

This C Cheat Sheet provides an overview of both basic and advanced concepts of the C language. Whether you’re a beginner or an experienced programmer, this cheat sheet will help you revise and quickly go through the core principles of the C language.

 C Language Cheatsheet

In this Cheat Sheet, we will delve into the basics of the C language, exploring its fundamental concepts that lay the groundwork for programming. We will cover topics such as variables, data types, and operators, providing you with a solid understanding of the building blocks of C programming .

Basic Syntax

Consider the below Hello World program:

 
  • #include <stdio.h>: The header file inclusion to use printf() function.
  • int main(): The main() function is the entry point of any C program.
  • printf(“Hello World”): Function to print hello world.
  • return 0: Value returned by the main() function.

A variable is the name given to the memory location that stores some data.

Syntax of Variable

A variable can be of the following types:

  • Local Variable
  • Global Variable
  • Static Variable
  • Extern Variable
  • Auto Variable
  • Register Variable
Note: There are a few rules which we have to follow while naming a variable.

The data type is the type of data that a given variable can store. Different data types have different sizes. There are 3 types of data types in C:

  • Basic Data Types
  • Derived Data Types
  • User Defined Data Types

1. Basic Data Types

Basic data types are built-in in the C programming language and are independent of any other data type. There are x types of basic data types in C:

  • char: Used to represent characters.
  • int: Used to represent integral numbers.
  • float: Used to represent decimal numbers up to 6-7 precision digits.
  • double: Used to represent decimal numbers up to 15 precision digits.
  • void: Used to represent the valueless entity.

Example of Basic Data Types

The size of these basic data types can be modified using data type modifiers which are:

Example of Data Type Modifiers

2. Derived Data Types

Derived data types are derived from the basic data types. There are 2 derived data types in C:

3. User-Defined Data Types

The user-defined data types are the data types that are defined by the programmers in their code.  There are 3 user-defined data types in C:

  • Enumeration

Identifiers

Identifiers is the name given to the variables, functions, structure, etc. Identifiers should follow the following set of rules:

  • A variable name must only contain alphabets, digits, and underscore.
  • A variable name must start with an alphabet or an underscore only. It cannot start with a digit.
  • No whitespace is allowed within the variable name.
  • A variable name must not be any reserved word or keyword.

Example of Identifiers

Keywords are the reserved words that have predefined meanings in the C compiler. They cannot be used as identifiers.

Example of Keywords

Basic input and output.

The basic input and output in C are done using two <stdio.h> functions namely scanf() and print() respectively.

Basic Output – print()

The printf() function is used to print the output on the standard output device which is generally the display screen.

Syntax of printf()

  • formatted-string: String to be printed. It may contain format specifiers, escape sequences, etc.
  • arguments-list: It is the list of data to be printed.

Basic Input – scanf()

The scanf() function is used to take input from the standard input device such as the keyboard.

Syntax of scanf()

  • formatted-string: String that describes the format of the input.
  • address-of-arguments-list: It is the address list of the variables where we want to store the input.

Example of Input and Output

       

Format Specifiers

Format specifiers are used to describe the format of input and output in formatted string. It is different for different data types. It always starts with %

The following is the list of some commonly used format specifiers in C:

For b type.

For signed integer type.

For float type.

Double

Pointer

String

Unsigned int

Prints % character

Escape Sequence

Escape sequences are the characters that are used to represent those characters that cannot by represented normally. They start with ( \ ) backslash and can be used inside string literals.

The below table list some commonly used escape sequences:

\b Backspace It is used to move the cursor backward.
\n New Line It moves the cursor to the start of the next line.
\r Carriage Return It moves the cursor to the start of the current line.
\t Horizontal Tab It inserts some whitespace to the left of the cursor and moves the cursor accordingly.
\v Vertical Tab It is used to insert vertical space.
\\ Backlash Use to insert backslash character.
\” Double Quote It is used to display double quotation marks.
\0 NULL It represents the NLL character.

Operators are the symbols that are used to perform some kind of operation. Operators can be classified based on the type of operation they perform.

There are the following types of operators in C:

S.No. Operator Type Description Example

Operators that perform arithmetic operations. +, -, *, /, %

They are used to compare two values. <, >, <=, >=, ==, !=

They are used to perform bit-level operations on integers. &, ^, |, <<, >>, ~

They perform logical operations such as logical AND, logical OR, etc. &&, ||, !

The conditional Operator is used to insert conditional code. ? :

They are used to assign some value to the variables. =, +=, -=, <<=

comma, addressof, sizeof, etc. are some other types of operators.  , sizeof, &, *, ->, .

Conditional Statements

Conditional statements are used to execute some block of code based on whether the given condition is true. There are the following conditional statements in C:

1. if Statement

if statement contains a block of code that will be executed if and only if the given condition is true.

Syntax of if

2. if-else Statements

The if-else statement contains the else block in addition to the if block which will be executed if the given condition is false.

Syntax if-else

3. if-else-if Ladder

The if-else-if ladder is used when we have to test multiple conditions and for each of these conditions, we have a separate block of code.

Syntax of if-else-if

4. switch Case Statement

The switch case statement is an alternative to the if-else-if ladder that can execute different blocks of statements based on the value of the single variable named switch variable.

Syntax of switch

5. Conditional Operator

The conditional operator is a kind of single-line if-else statement that tests the condition and executes the true and false statements.

Syntax of Conditional Operator

Example of Conditional Statements

   

Loops are the control statements that are used to repeat some block of code till the specified condition is false. There are 3 loops in C:

1. for Loop

The for loop is an entry-controlled loop that consists initialization, condition, and updating as a part of itself.

Syntax of for

2. while Loop

The while loop is also an entry-controlled loop but only the condition is the part of is syntax.

Syntax of while

3. do-while Loop

The do-while loop is an exit-controlled loop in which the condition is checked after the body of the loop.

Syntax of do-while

Jump Statements

Jump statements are used to override the normal control flow of the program. There are 3 jump statements in C:

1. break Statement

It is used to terminate the loop and bring the program control to the statements after the loop.

Syntax of break

It is also used in the switch statement.

2. continue Statement

The continue statement skips the current iteration and moves to the next iteration when encountered in the loop.

Syntax of continue

3. goto Statement

The goto statement is used to move the program control to the predefined label.

Syntax of goto

Example of Loops and Jump Statements

           

An array is a fixed-size homogeneous collection of items stored at a contiguous memory location. It can contain elements from type int, char, float, structure, etc. to even other arrays.

  • Array provides random access using the element index.
  • Array size cannot change.
  • Array can have multiple dimensions in which it can grow.

Syntax of Arrays

Example of arrays.

       

Strings are the sequence of characters terminated by a ‘\0’ NULL character. It is stored as the array of characters in C.

Syntax of Strings

Example of strings.

           

C String Functions

C language provides some useful functions for string manipulation in <string.h> header file. Some of them are as follows:

S. No.

Function

Description

1.

Find the length of the string

2.

Compares two strings.

3.

Copy one string to another.

4.

Concatenate one string with another.

5.

Find the given character in the string.

6.

Find the given substring in the string.

Pointers are the variables that store the address of another variable. They can point to any data type in C

Syntax of Pointers

Note: The addressof (&) operator is used to get the address of a variable.

We can dereference (access the value pointed by the pointer) using the same * operator.

Example of Pointers

       

There are different types of pointers based on different classification parameters. Some of them are:

  • Double Pointers
  • Function Pointers
  • Structure Pointers
  • NULL Pointers
  • Dangling Pointers
  • Wild Pointers

Functions are the block of statements enclosed within { } braces that perform some specific task. They provide code reusability and modularity to the program.

Function Syntax is divided into three parts:

1. Function Prototype

It tells the compiler about the existence of the function.

  • Return Type: It is the type of optional value returned by the function. Only one value can be returned.
  • Parameters: It is the data passed to the function by the caller.

2. Function Definition

It contains the actual statements to be executed when the function is called.

3. Function Call

Calls the function by providing arguments. A function call must always be after either function definition or function prototype.

Example of Function

     

Type of Function

A function can be of 4 types based on return value and parameters:

  • Function with no return value and no parameters.
  • Function with no return value and parameters.
  • Function with return value and no parameters.
  • Function with return value and parameters.

There is another classification of function in which there are 2 types of functions:

  • Library Functions
  • User-Defined Functions

Dynamic Memory Management

Dynamic memory management allows the programmer to allocate the memory at the program’s runtime. The C language provides four <stdlib.h> functions for dynamic memory management which are malloc(), calloc(), realloc() and free().

1. malloc()

The malloc() function allocates the block of a specific size in the memory. It returns the void pointer to the memory block. If the allocation is failed, it returns the null pointer.

2. calloc()

The calloc() function allocates the number of blocks of the specified size in the memory. It returns the void pointer to the memory block. If the allocation is failed, it returns the null pointer.

3. realloc()

The realloc() function is used to change the size of the already allocated memory. It also returns the void pointer to the allocated memory.

The free function is used to deallocate the already allocated memory.

Example of Dynamic Memory Allocation

           

A structure is a user-defined data type that can contain items of different types as its members. In C, struct keyword is used to declare structures and we can use ( . ) dot operator to access structure members.

Structure Template

To use structure, we first have to define its template.

Structure Variable Syntax

Example of structure.

           

A union is also a user-defined data type that can contain elements of different types. However, unlike structure, a union stores its members in a shared memory location rather than having separate memory for each member.

Syntax of Union

Union members can be accessed using dot operator ( . ) but only one member can store the data at a particular instance in time.

Example of Union

           

Enumeration (enum)

Enumeration, also known as enum is a user-defined data type that is used to assign some name to the integral constant. By default, the enum members are assigned values starting from 0 but we can also assign values manually.

Syntax of enum

Example of enum.

   

File Handling

File handling is the process of performing input and output on a file instead of the console. We can store, retrieve, and update data in a file. C supports text and binary files.

C File Operations

We can perform some set of operations on a file and C language provide some functions for it.

  • Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
  • Opening an existing file – fopen()
  • Reading from file – fscanf() or fgets()
  • Writing to a file – fprintf() or fputs()
  • Moving to a specific location in a file – fseek() , rewind()
  • Closing a file – fclose()

Preprocessor Directives

The preprocessor directives are used to provide instructions to the preprocessor that expands the code before compilation. They start with the # symbol.

The following table lists all the preprocessor directives in C/C++:

S.No.

1.

Used to define a macro

2.

Used to undefine a macro

3.

Used to include a file in the source code program

4.

Used to include a section of code if a certain macro is defined by #define

5.

Used to mark the end of #endif

6.

Used to include a section of code if a certain macro is not defined by #define

7.

Check for the specified condition

8.

Alternate code that executes when #if fails

9.

This directive is a special purpose directive and is used to turn on or off some features.

Common Library Functions

C languages come bundled with some Standard Libraries that contain some useful functions to make it easier to perform some common operations. These are as follows:

C Math Functions

The <math.h> header file contains functions to perform the arithmetic operations. The following table contains some common maths functions in C:

S.No.

1.

Returns the largest integer smaller than or equal to x.

2.

Returns the smallest integer larger than or equal to x.

3.

Returns the absolute value of x.

4.

Returns the square root of x.

5.

Returns the cube root of x.

6.

Returns the value of x raised to the power y.

7.

Returns the value of e(Euler’s Number) raised to the power x.

8.

Returns the remainder of x divided by y.

9.

Returns the natural logarithm of x.

10.

Returns the common logarithm of x.

11.

Returns the cosine of radian angle x.

12.

Returns the sine of radian angle x.

13.

Returns the tangent of radian angle x.

Conclusion 

In summary, this C Cheat Sheet offers a concise yet comprehensive reference for programmers of all levels. Whether you’re a beginner or an experienced coder, this cheat sheet provides a quick and handy overview of the core principles of C. With its organized format, code examples, and key syntaxes, it serves as a valuable resource to refresh your knowledge and navigate through the intricacies of C programming. Keep this cheat sheet close by to accelerate your coding journey and streamline your C programming endeavors.

Please Login to comment...

Similar reads.

  • Best PS5 SSDs in 2024: Top Picks for Expanding Your Storage
  • Best Nintendo Switch Controllers in 2024
  • Xbox Game Pass Ultimate: Features, Benefits, and Pricing in 2024
  • Xbox Game Pass vs. Xbox Game Pass Ultimate: Which is Right for You?
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

swayam-logo

Introduction to Programming in C

  • What is an algorithmic solution to the problem?
  • How do we translate the algorithm into C code?
  • How efficient is the code?
  • How maintainable is the code?
  • Attempting algorithmic solutions to problems
  • Designing and coding moderate sized programs running to the order of a few hundred lines of code, and
  • Reading, understanding and modifying code written by others.
--> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> -->

Note: This exam date is subject to change based on seat availability. You can check final exam date on your hall ticket.

Page Visits

Course layout, books and references, instructor bio.

core c programming programming assignment chapter 6

Prof. Satyadev Nandakumar

Course certificate.

  • Assignment score = 25% of average of best 6 assignments out of the total 8 assignments given in the course. 
  • ( All assignments in a particular week will be counted towards final scoring - quizzes and programming assignments). 
  • Unproctored programming exam score = 25% of the average scores obtained as part of Unproctored programming exam - out of 100
  • Proctored Exam score =50% of the proctored certification exam score out of 100

core c programming programming assignment chapter 6

DOWNLOAD APP

core c programming programming assignment chapter 6

SWAYAM SUPPORT

Please choose the SWAYAM National Coordinator for support. * :

Browse Course Material

Course info, instructors.

  • Daniel Weller
  • Sharat Chikkerur

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Programming Languages
  • Software Design and Engineering

Learning Resource Types

Practical programming in c, problem set 1.

Problem set on writing, compiling, and debugging C programs, preprocessor macros, the C file structure, variables, functions and program statements, and returning from functions.

facebook

You are leaving MIT OpenCourseWare

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

IMAGES

  1. C++ for C programmers (Chapter 6 Unit 9)

    core c programming programming assignment chapter 6

  2. Intro to Programming in C-program 6 Assignment

    core c programming programming assignment chapter 6

  3. Assignment 6C++

    core c programming programming assignment chapter 6

  4. Core C programming -- Chapter 6 '함수'

    core c programming programming assignment chapter 6

  5. Solved C Programming Assignment 6 Arrays Due Tuesday, March

    core c programming programming assignment chapter 6

  6. Programming Essentials in C: Chapter 6 Assignment (CLA) Exam Answers

    core c programming programming assignment chapter 6

VIDEO

  1. 01.1 C Programming

  2. C programming

  3. Module 0: Setup for C

  4. C For Everyone : programming fundamentals week 6 answers

  5. OPERATORS NOTES

  6. NPTEL Problem Solving through Programming In C WEEK6 Programming Assignment Solutions

COMMENTS

  1. C Programming

    Chapter Six of C Programming by Brian W. Kernighan and Dennis M. Ritchie. In this chapter we cover structures in C.For more detail see https://www.cc4e.comF...

  2. Answers to Selected Exercises in Chapter 6 of C Programming: A Modern

    Answers to selected exercises in Chapter 6 of the book C Programming: A Modern Approach, Second Edition

  3. C Programming

    Study with Quizlet and memorize flashcards containing terms like What is a block?, Name the six basic things which make up a C program., Does a C program start at the beginning? (Where is the beginning?) and more.

  4. Core C: Control Structures, Variables, Scope, and Uninitialized Memory

    This section provides materials for a lecture on writing code in C, including lecture notes, lab exercises, and an assignment.

  5. ohkimur/the-c-programming-language-2nd-edition-solutions

    Introduction The C Programming Language is a very popular book and sometimes people refer to it as K&R. The authors Brian W. Kernighan and Dennis M. Ritchie did a very good job of explaining the core concepts of programming. The focus of the book is the C programming language, however, the approach is general, so it can be extrapolated to other programming languages.

  6. C Exercises

    The best way to learn C programming language is by hands-on practice. This C Exercise page contains the top 30 C exercise questions with solutions that are designed for both beginners and advanced programmers. It covers all major concepts like arrays, pointers, for-loop, and many more.

  7. Programming Essentials in C: Chapter 6 Assignment (CLA) Test Online

    1. the program outputs 2 2. the program outputs 0 3. the program outputs 1 4. the compilation fails

  8. Structure of the C Program

    The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and understand in a particular format. C program must follow the below-mentioned outline in order to successfully compile and execute. Debugging is easier in a well-structured C program.

  9. Chapter 6, Working with Arrays Video Solutions, Programming in C

    Video answers for all textbook questions of chapter 6, Working with Arrays, Programming in C by Numerade

  10. C Programming Language Tutorial

    C Programming Language Tutorial. In this C Tutorial, you'll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who're looking to learn and enhance their knowledge of the C programming language.

  11. C Examples

    The best way to learn C programming is by practicing examples. The page contains examples on basic concepts of C programming. You are advised to take the references from these examples and try them on your own.

  12. C Programming Exercises, Practice, Solution

    C programming Exercises, Practice, Solution: C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations.

  13. Chapter 5: Introduction to C Programming

    Jonathan Valvano and Ramesh Yerraballi. This chapter covers the C Programming language starting with the structure, constants and variable declarations, the main subroutine, simple input/output, arithmetic expressions, Boolean expressions, the assignment statement, the while loop and lastly simple functions with at most one input and one output.

  14. Learn C Programming

    Learn C Programming. C is one of the foundational programming languages used in the development of compilers, operating systems, and embedded systems where speed and efficiency matter. It is considered the best language to start because it provides a strong understanding of fundamental coding concepts like data types, variables, loops, and ...

  15. HaeBun/Core-C-Programming

    Core C Programming 예제 및 문제 풀이. Contribute to HaeBun/Core-C-Programming development by creating an account on GitHub.

  16. Lectures and Assignments

    This section contains links to individual pages for the first 6 lectures of the course, containing lecture notes, lab exercises, and assignments. Only lecture slides are available for Lectures 7 and 8 as there were no associated labs and assignments for those sessions.

  17. Practical Programming in C

    Daily programming assignments and weekly laboratory exercises are required. Knowledge of C is highly marketable for summer internships, UROPs, and full-time positions in software and embedded systems development.

  18. Programming Essentials in C: Chapter 6 Assignment (CLA) Exam Answers

    Programming Essentials in C: Chapter 6 Assignment (CLA) Exam Answers. How to find: Press "Ctrl + F" in the browser and fill in whatever wording is in the question to find that question/answer. If the question is not here, find it in Questions Bank. NOTE: If you have the new question on this test, please comment Question and Multiple-Choice ...

  19. C Programming Language Cheat Sheet

    This C Cheat Sheet provides an overview of both basic and advanced concepts of the C language. Whether you're a beginner or an experienced programmer, this cheat sheet will help you revise and quickly go through the core principles of the C language.

  20. Introduction to Programming in C

    Assignment score = 25% of average of best 6 assignments out of the total 8 assignments given in the course. ( All assignments in a particular week will be counted towards final scoring - quizzes and programming assignments).

  21. Problem Set 1

    Problem set on writing, compiling, and debugging C programs, preprocessor macros, the C file structure, variables, functions and program statements, and returning from functions.

  22. Core-C-Programming/Chapter5/ex05_05.c at master

    Core C Programming 예제 및 문제 풀이. Contribute to HaeBun/Core-C-Programming development by creating an account on GitHub.

  23. Core C Programming 2nd edition 연습문제 정답지

    Core C Programming 2nd edition 연습문제 정답지 언어와 프로그래밍 개요 1장 응용 프로그램, 프로그램, 애플리케이션 15. 링커 10.

Course Status : Completed
Course Type : Elective
Duration : 8 weeks
Category :
Credit Points : 2
Undergraduate/Postgraduate
Start Date : 14 Sep 2020
End Date : 06 Nov 2020
Enrollment Ends : 25 Sep 2020
Exam Date : 18 Dec 2020 IST