0% found this document useful (0 votes)
11 views25 pages

ALITS_C&DS_Online Training

The document provides an overview of the C programming language, its significance, and basic programming concepts such as variables, data types, operators, user inputs, and control structures. It includes code snippets and examples to illustrate how to print output, perform arithmetic operations, and handle user inputs, along with explanations of comments and best practices. Additionally, it discusses the importance of test cases in programming and provides examples of how to handle multiple inputs.

Uploaded by

kiranmaiii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views25 pages

ALITS_C&DS_Online Training

The document provides an overview of the C programming language, its significance, and basic programming concepts such as variables, data types, operators, user inputs, and control structures. It includes code snippets and examples to illustrate how to print output, perform arithmetic operations, and handle user inputs, along with explanations of comments and best practices. Additionally, it discusses the importance of test cases in programming and provides examples of how to handle multiple inputs.

Uploaded by

kiranmaiii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Introduction, Outputting & Math Operators

Variables and Data Types

Operators

Strings

User Inputs

Conditional Statements

Debug your code

Loops

Arrays

Functions in C

Pointers and Structures

Getting started with algorithmic problems

C is a programming language created by Dennis Ritchie at Bell Labs in the 1970s. It's important
because many well-known operating systems like Unix, Microsoft Windows, Mac OS X, and
GNU/Linux are written in C.

Besides operating systems, many other popular programming languages like Perl, PHP, Python, R,
Matlab, and Mathematica are based on or influenced by C.

As of July 2012, C has been ranked as the most popular programming language according to the
TIOBE index - a well known website which ranks the programming langauages. This shows that C is
trusted by many programmers and is still widely used today.

Why still C is popular programming Language?

 Operating Systems: Many major operating systems are written in C, which means it's
fundamental to how computers work.

 Influence on Other Languages: C's concepts and syntax have influenced many other popular
programming languages, making it a foundational language for many programmers.

 Trust and Usage: The TIOBE index ranking shows that C is still widely used and trusted by
programmers today.

Let us output an integer in C.

C has a few lines of code which we write in almost all programs.

#include <stdio.h>
int main() {

rintf("%d", 12);

Let's break down this line of code:

1. #include is a preprocessor directive that tells the compiler to include the contents of another
file before compiling the program.

2. <stdio.h> stands for Standard Input Output Header. This file contains functions that allow us
to perform input and output operations, such as printf() (for displaying output)
and scanf() (for taking user input).

3. main() is the starting point of any C program. The execution of the program begins from this
function.

4. int before main() means that the function returns an integer value. A return value of 0
generally indicates successful execution.

5. printf: This is a function in C used for printing or displaying information on the screen.

6. "%d": This is a format specifier. It tells printf how to interpret the data it's given. In this
case, %d is used for integers (whole numbers).

7. 12: This is the actual data you want to print. Here, it's the number 12.

So, when you write printf("%d", 12);, it tells the computer to print the integer 12 on the screen.

Note that this line contains a (;) semicolon at the end. Semicolon is mandatory at the end of
statements in C.

First 2 lines will be explained in more detail in the upcoming modules.

Click on Submit below the IDE to know the result. Then click on next to continue.

Common Doubts?

What does #inlcude<stdio.h> do?

Why is semicolon mandatory?

Can %d print other data types?

Printing a number

#include <stdio.h>

int main() {

/ Delete __ (underscore) and add 20 at it's place

printf("%d", 20);

}
Arithmetic Operations

We can also perform mathematical operations (like addition, subtraction etc) with printf().

These use the familiar symbols of:

 ++ for addition

 −− for subtraction

 ∗∗ for multiplication

 // for division

To add two number we do this:

printf("%d", 21 + 40);

The above line of code will output: 61

Again, printf is the function we use when we want to print. "%d" tells the compiler that we want to
print a number. And writing 21 + 40 tells the compiler to add these two number and print the sum.

Task

Try to add 21 and 40 in code and print the result. Remember, we don't need "" (double quotes) when
printing numbers.

#include <stdio.h>

int main() {

// Replace the underscores

printf("%d", 21+40);

Common doubts:

Why use %d in print?

Can we subtract numbers in print?

What happen if we use quotes?

Comments:

In last section, you might have noticed this symbol // and some text instruction in the code editor.
That was a comment.

Comments in C are notes added to code to explain what the code does or any other kind of
information about the code. They are helpful for making the code easier to understand.

Types of Comments in C

In C, there are two primary ways to add comments to your code:


1. Single-Line Comments:

o Syntax: // Your comment here

o Example:

int main() { printf("%d", 12); // This is a single-line comment. the printf statement
prints 12. }

2. Multi-Line Comments:
Syntax: /* Your multi-line comment here *
Example:
/* This is a multi-line comment
spanning multiple lines */
int main()
{ printf("%d", 12); }
Multi-line comments start with /* and end with */. They can span multiple lines and are
typically used for longer explanations or for commenting out large blocks of code.
Best Practices for Using Comments in C
 Be Descriptive: Always strive to write clear and descriptive comments that explain the
purpose, functionality, or reasoning behind the code.
 Update Regularly: Remember to update comments when you modify the code to ensure
they remain accurate and relevant.
 Avoid Redundancy: Avoid writing comments that only restate the obvious. Comments
should provide additional information or insights that are not immediately evident from the
code itself.

Printing text:

#include <stdio.h>

int main() {

// Replace the _ (underscores) with the correct value

printf("I love C");

Task

Write a program which does the following

 Add a printf statement and output the sum of 3 + 4

 Add another printf statement and output the sum of 2 + 1.

Use the printf syntax we learned in last problem.

Note - Notice that in the output they are printed together without any space between them.

Expected Output

73
Data Types

Lets look at some common data types found in programming problems for beginners

 Integers

o Integers are whole numbers that can be negative, zero or positive. Examples
- 15, 0, -5

 Float

o A float will have a decimal place. Examples - 4.5, -2.778

o Note that 4.0, -2.0 are also floats

 Strings

o Strings are a group of characters. Examples - abcde, CodeChef, START69

o Note that C does not contain a string datatype we can declare a string using a char
array.

 Arrays

o Arrays are used to store multiple variables or input types. Examples of arrays

 Array containing 6 integers - [1 , 5, 7, 10, 15, 2]

 Array containing 4 strings - ["abcd", "d", "ccc", "c123"]

 NOTE - Array containing a combination of string and integers - ["abcd", 4,


"ccc", 25] is not possible in C

o Note that the strings in the array were denoted as "abcd" - we will come to this at
a later stage

 Bool

o Bools are available under the header stdbool.h

o They are used to obtain true or false output from the code

//Click on Submit in the IDE to proceed

#include <stdio.h>

#include <stdbool.h>

int main() {

// Integer

int a = -5;
printf("%d\n", a);

// Float

float b = 4.0;

printf("%f\n", b);

// Character

char c = 'a';

printf("%c\n", c);

// String, ie, character array

char string[] = "1234abc";

printf("%s\n", string);

// Integer array

int array[] = {1,2,3,4,5,6};

for (int i = 0; i < 6; i++)

printf("%d ", array[i]);

printf("\n");

// Boolean

// Note: bools can be represented with the %d format specifier

bool boolean = true;

printf("%d\n", boolean);

return 0;

How to accept integer inputs

In the previous problem, we saw common data types found in programming problems for
beginners. Now lets try to take an integer as input.

Task
Let us define a variable nn that accepts integer inputs.
Output the same variable nn.
Code the solution in the IDE and then click Submit to continue.

//update the _ in the code

#include <stdio.h>

int main() {

___ n;

_____("%_", &n );

printf("%_", n );

return 0;

//update the _ in the code

#include <stdio.h>

int main() {

int n;

scanf("%d", &n );

printf("%d", n );

return 0;

How to accept multiple inputs in a line

Sometimes - we have to accept multiple inputs in a single line.


The syntax for the same is as follows -

int a, b, c; // assigns integer datatype to variables a, b and c

scanf("%d %d %d", &a, &b, &c);

Now lets try and solve the following

 Accept 3 space separated integers given in a line into 3 variables - AA, BB and CC

 Print them out to a single line on the console


You can play around with the exact syntax in the IDE -> refer to the solution in case you are unable
to get this correct.
Code the solution in the IDE and then click Submit to continue.

//Update the blanks below to solve the problem

#include <stdio.h>

int main() {

int A, B, C;

scanf("%d %d %d", &A , &B , &C );

printf("%d %d %d ", A, B, C);

return 0;

How to accept string inputs

Lets try the same exercise with strings.

Task

You need to write a program that does the following

 Accepts 22 space separated alphanumeric strings as input in 1st1st line as the


variables AA, BB

 Accepts 33 space separated alphanumeric strings as input in 2nd2nd line as the


variables CC, DD, EE

 Accepts 44 space separated alphanumeric strings as input in 3rd3rd line as the


variables FF, GG, HH, II

 Prints out 99 space separated strings as output in a single line to the console

Remember that the scanf()scanf() function necessarily takes the parameters to be strings.
Solve the problem in the IDE and then click on Submit to proceed.

Note- C treats all whitespace similarly while taking input.


So: scanf(“%d%d”, &a, &b);
And: scanf(“%d”, &a);
scanf(“%d”, &b);
are equivalent.

Sample 1:

abc cde

fg hi jk
lmno

output:

abc cde fg hi jk l m n o

Solution:

#include <stdio.h>

int main() {

char A[10], B[10];

char C[10], D[10], E[10];

char F[10], G[10],H[10],I[10];

scanf("%s%s", A , B );

scanf("%s%s%s", C, D, E );

scanf("%s%s%s%s", F , G, H, I );

printf("%s %s %s %s %s %s %s %s %s ", A , B , C , D , E , F , G , H , I );

return 0;

How to print output

Cool - so you learnt how to accept integer inputs.

Now let's look at how to convert input into output and display the same.

Most algorithmic programming problems will need you to generate the following types of output

 Integers or Floats

 Strings

 An array of integers or strings

/Click submit to continue

#include <stdio.h>

int main() {

int N = 5;

printf("%d\n", N);

char s[10] = "abcde";


printf("%s\n", s);

int Arr[] = {2, 3, 6, 7};

for (int i = 0; i < 4; i++) {

printf("%d ", Arr[i]);

return 0;

Input mirror

Now let's write a simple program - the Input mirror. Your program needs to do the following

 Accept an integer input from the console and store it in the variable NN

 Accept a string input from the console and store it in the variable SS

 Output the integer and the string on the same line

Solve the problem in the IDE and then click on click on Submit to proceed.

Sample 1:Input

Abcde

Output:

5 abcde

#include <stdio.h>

int main() {

int N;

char S[30]; // Declaring a character array to store the string

scanf("%d", &N); // Reading an integer

scanf("%s", S); // Reading a string

printf("%d ", N ); // Printing the integer

printf("%s", S ); // Printing the string

return 0;
}

What are test cases

In the previous module, we practiced simple methods of input and output used in programming
problems.

Let's take the next small step and learn about test cases.
You will find the concept of 'test cases' on various programming platforms such as Leetcode,
Codeforces, CodeChef, Hackerrank. What are test cases?

 Test cases are multiple Inputs - multiple instances of the same problem, all of which have
to be solved by your code correctly.

o Example 1: Consider 5 test cases or 5 inputs


11
13
2
4
9

Task

Lets solve a simple problem.


Write a program in the IDE which does the following

 Accepts 5 inputs given on 5 separate lines. Each input is an integer N

 For each test cases, prints out the integer N to console on a separate line (our Input
mirror problem)

Sample1:

Input:

11

13

Output:

11

13

#include <stdio.h>
int main() {

int A, B, C, D, E;

scanf("%d \n", &A );

scanf("%d \n", &B ); // Corrected

scanf("%d \n", &C ); // Corrected

scanf("%d \n", &D );

scanf("%d \n", &E );

printf("%d \n", A );

printf("%d \n", B ); // Corrected

printf("%d \n", C ); // Corrected

printf("%d \n", D );

printf("%d \n", E );

return 0; // Added return 0 for best practice

What are test cases

In the previous problem - we wrote the program to accept 5 inputs on 5 separate lines.

 What will we do if we expect 100 inputs or test cases?

 What about 100,000 inputs or test cases?

Task

Let's solve a simple problem.


Write a program in the IDE which does the following

 Accepts the count of test cases - t - as an integer input given in the 1st line.
This is followed by t lines - Each line contains an integer N

 For each test cases, prints out the integer N to console on a separate line (our Input
mirror problem)

Sample1:

Input:

22
33

Output:

22

33

#include <stdio.h>

int main() {

int t,n;

int i = 1;

scanf("%d", &t );

while ( i <= t) {

scanf("%d", &n );

printf("%d \n", n );

i = i+1;

return 0;

Test cases with multiple lines of input

In the previous problem, we had t test cases and each test case had 1 line of input.
However, each test case can have multiple lines of input as well.

Task

Let's write a program in the IDE which performs the following:

 The 1st line of input is an integer t - the count of test cases.

 Each test case consists of 2 lines of input:

o The 1st line of input has 2 space separated integers - accept them
as variables A and B.

o The 2nd line of input has 3 space separated integers - accept them
as variables C, D and E.

 For each test case - output all integers on a single line.

Sample 1:

Input:
3

12

345

11 22

33 44 55

1 23

456 789 101112

Output:

12345

11 22 33 44 55

1 23 456 789 101112

/ Update the blanks below to solve the problem

#include <stdio.h>

int main() {

int t;

int A, B, C, D, E;

int i = 1;

_____("%d", &t );

_____ (i <= t) {

_____("%_ __", &A, &B );

_____("%_ __ __", &C, &D, &E );

printf("%_ __ __ __ __ ", A, B, C, D, E);

i = i + _;

// Update the blanks below to solve the problem

#include <stdio.h>

int main() {

int t;
int A, B, C, D, E;

int i = 1;

scanf("%d", &t );

while (i <= t) {

scanf("%d %d", &A, &B );

scanf("%d %d %d", &C, &D, &E );

printf("%d %d %d %d %d\n", A, B, C, D, E); // Added newline for correct output format

i = i + 1;

return 0; // Added return 0 for good practice

Test cases with multiple types of input

In the previous problem, each testcase had 2 lines of input - each consisting of integers.
Test cases can also contain a combination of integers and strings.

Task

Let's write a program in the IDE which performs the following:

 The 1st line of input contains t - the count of testcases.

o Each testcase consists of the following 2 lines of input:

 The 1st line of the testcase contains 2 integers - accept them


as variables A and B.

 The 2nd line of the testcase contains 1 string - accept it as a variable S.

 For each test case, output on a single line the 2 integers followed by the string.

Sample 1:

Input:

12

abcde

34 567

A1B2C3

Output:

1 2 abcde

34 567 A1B2C3
// Update the blanks below to solve the problem

#include <stdio.h>

int main() {

int t;

___ A, B;

____ C[30];

int i = 1;

_____("%d", &t);

_____ (i <= t) {

_____("%_ __", &A, &B);

_____("%_", &C);

printf("%_ __ __ ", A, B, C);

i = i+_;

// Update the blanks below to solve the problem

#include <stdio.h>

int main() {

int t;

int A, B;

char C[30];

int i = 1;

scanf("%d", &t);

while (i <= t) {

scanf("%d %d", &A, &B);

scanf("%s", C); // No '&' needed for scanning a string into an array name

printf("%d %d %s ", A, B, C);

i = i + 1;

}
return 0; // Added return 0 for good practice

What are hidden test files and test cases

o far we dealt with test files and test cases which were visible to you.

However, programming platforms typically have hidden or private test files and test cases. What
are these?

 Private test files check for the following

o Test your code for logic

o Test your code for corner cases / edge cases

o Test your code for handling scale -> does your program solve within time and space
constraints?

 What do these private test files do?

o Your code is run on each test case within the private test file

o This generates your actual output

o This is judged against the expected output.


If the actual output and expected output match, then your code is correct

What are custom inputs?


You will usually find a custom inputs box in programming problems.
Custom inputs allow you to do the following

 You are able to see the output generated by your code for inputs defined by you

 Test your code with your sample inputs.


This helps you debug Wrong Answers (WA), Runtime Errors (RE) faster

 Create your own test cases.


In programming problems - you want to find exceptions or test cases where your code /
logic can fail.
Custom inputs allow you to test your code for the same.

How to use custom input?

You are given a program which does the following:

 Accepts the count of test cases - t - in the 1st line.


First line of each test case consists of an integer N

 Outputs the integer which is greater than N by 1

 Note: The Sample 1 input values are pre-populated in the Custom inputs below the IDE

Task

You need to do the following:


 Replace the Custom inputs with Sample test case 2 and click Run to check the result.
You can click the Copy icon at the top-right of the sample testcases to copy easily.

 Replace the Custom inputs with your own created inputs and click Run to check the result.
You can experiment a few more options.

 Once done, click on Submit to test your code against the Private test files

 Note - Do not forget that the 1st integer in the custom inputs has to be t - the number
of test cases

//Change the 'custom inputs' below and click 'run'

//Click on 'Submit' once you have tried out to proceed to the next problem

#include <stdio.h>

int main() {

int t;

int n;

int i = 1;

scanf("%d\n", &t);

while (i <= t) {

scanf("%d", &n);

printf("%d\n", n + 1);

i = i + 1;

Number mirror - Negative integer

Let us now solve some programming problems. Note that

 In the IDE - the text after '//' is comments which doesn't affect the code and will give you
hints about what you need to do

 The Solution tab also has '//' - comments which give you helpful information

Task

Write a program in the IDE which does the following

 Accepts the count of test cases - t - in the 1st line

o The only line of each test case consists of an integer N


 You need to generate the following output - Change the sign of N.
That is, if the input is 4, output -4. If the input is -5, output 5.

Sample1:

Input:

-4

-5

Output:

-1

-2

-3

// Update the '_' in the code below

#include <stdio.h>

int main() {

int t;

int N;

int i = 1;

//accept the count of test cases given in the 1st line

_____("%d\n", &t);

//run a loop to accept 't' inputs

_____ (i <= t) {

//accept 1 integer on the 1st line of each test case

scanf("%_", &N);

//output the negative integer - i.e. (-N)


printf("%d\n", ____ );

i = i + 1;

#include <stdio.h>

int main() {

int t;

int N;

int i = 1;

//accept the count of test cases given in the 1st line

scanf("%d\n", &t);

//run a loop to accept 't' inputs

while (i <= t) {

//accept 1 integer on the 1st line of each test case

scanf("%d", &N);

//output the negative integer - i.e. (-N)

printf("%d\n", N * -1);

i = i + 1;

return 0; // Added return 0 for good practice

String mirror - Double strings

Write a program in the IDE which does the following

 Accepts the count of test cases - t - in the 1st line

o First line of each test case consists of a string S

 You need to perform the following operation

o Create a variable X which contains the string S concatenated with the string S

o Output X for each test case

Sample1:

Input:
3

ab

bc

cd

Output:

abab

bcbc

cdcd

// Update the '_' in the code below

#include <stdio.h>

#include <string.h>

#define MAX_LEN 1001 // maximum length of input string

int main() {

int t;

scanf("%d", &t);

char S[MAX_LEN]; // declare a character array to store the input string

for (int i = 0; i < t; i++) {

scanf("%s", S); // read in the input string

int len = strlen(S); // get the length of the input string

char X[MAX_LEN * 2]; // declare a character array to store the concatenated string

int j;

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

X[_] = S[_]; // copy S into X

int k;

for (k = 0; k < len; k++) {

X[_+_] = S[_]; // concatenate S with itself

}
X[j+k] = '\0'; // terminate the string

printf("%s\n", X); // output the concatenated string

// Update the '_' in the code below

#include <stdio.h>

#include <string.h>

#define MAX_LEN 1001 // maximum length of input string

int main() {

int t;

scanf("%d", &t);

char S[MAX_LEN]; // declare a character array to store the input string

for (int i = 0; i < t; i++) {

scanf("%s", S); // read in the input string

int len = strlen(S); // get the length of the input string

char X[MAX_LEN * 2]; // declare a character array to store the concatenated string

int j;

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

X[j] = S[j]; // copy S into X

int k;

for (k = 0; k < len; k++) {

X[j+k] = S[k]; // concatenate S with itself

X[j+k] = '\0'; // terminate the string

printf("%s\n", X); // output the concatenated string


}

Debug this code - Why is this code incorrect

o as you solve programming problems - you will need to debug and find errors in your own code.

Task

You are given a program which does the following:

 Accepts the count of test cases - t - in the 1st line.

o The only line of each test case consists of an integer N.

 For each test case, output to the console the value that is double the integer N.

Can you try and debug / fix the error in the given program?

Sample1:

Input:

Output:

// Debug the given code

#include <stdio.h>

int main() {

int t;

int N;

int i = 1;

scanf("%d", &t);

while (i <= t) {
scanf("%s", &N);

printf("%s\n", 2 * N);

i = i + 1;

// Debug the given code

#include <stdio.h>

int main() {

int t;

int N;

int i = 1;

scanf("%d", &t);

while (i <= t) {

scanf("%d", &N); // Changed %s to %d

printf("%d\n", 2 * N); // Changed %s to %d

i = i + 1;

Debug this code - Why is this code incorrect

// Debug the given code

#include <stdio.h>

int main() {

int t;

int N;

int i = 1;

scanf("%d", &t);

while (i <= t)
scanf("%d", &N);

printf("%d\n", 2 * N);

i = i+1

// Debug the given code

#include <stdio.h>

int main() {

int t;

int N;

int i = 1;

scanf("%d", &t);

while (i <= t) { // Added opening bracket

scanf("%d", &N);

printf("%d\n", 2 * N);

i = i + 1; // Added missing semicolon

} // Added closing bracket

return 0; // Added return 0 for good practice

You might also like